<?php

declare(strict_types=1);

namespace common\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

/**
 * @property int    $id
 * @property string $name
 * @property string $role
 * @property string $quote
 * @property string $avatar_letter
 * @property int    $sort_order
 * @property int    $is_active
 * @property int    $created_at
 * @property int    $updated_at
 */
class Testimonial extends ActiveRecord
{
    public static function tableName(): string
    {
        return '{{%testimonials}}';
    }

    public function behaviors(): array
    {
        return [TimestampBehavior::class];
    }

    public function rules(): array
    {
        return [
            [['name', 'quote'], 'required'],
            [['name', 'role'], 'string', 'max' => 120],
            ['avatar_letter', 'string', 'max' => 1],
            ['quote', 'string'],
            ['sort_order', 'integer', 'min' => 0, 'max' => 9999],
            ['is_active', 'boolean'],
            // Auto-derive avatar_letter from name if empty
            ['avatar_letter', 'default', 'value' => null],
        ];
    }

    public function attributeLabels(): array
    {
        return [
            'name'          => 'Client Name',
            'role'          => 'Role / Description',
            'quote'         => 'Testimonial Quote',
            'avatar_letter' => 'Avatar Letter',
            'sort_order'    => 'Sort Order',
            'is_active'     => 'Visible on Website',
        ];
    }

    public function beforeSave($insert): bool
    {
        if (empty($this->avatar_letter) && !empty($this->name)) {
            $this->avatar_letter = strtoupper(mb_substr($this->name, 0, 1));
        }
        return parent::beforeSave($insert);
    }

    /** Return all active testimonials ordered by sort_order. */
    public static function getActive(): array
    {
        return static::find()
            ->where(['is_active' => 1])
            ->orderBy(['sort_order' => SORT_ASC, 'id' => SORT_ASC])
            ->all();
    }
}
