<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Faq extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<string>
     */
    protected $fillable = [
        'question',
        'answer',
        'sort_order',
        'is_active',
    ];

    /**
     * The attributes that should be cast.
     *
     * @return array<string, string|class-string>
     */
    protected function casts(): array
    {
        return [
            'sort_order'  => 'integer',
            'is_active'   => 'boolean',
            // 'created_at'  => 'datetime',   // already default hota hai
            // 'updated_at'  => 'datetime',
        ];
    }

    // ────────────────────────────────────────────────
    //          Commonly used query scopes
    // ────────────────────────────────────────────────

    /**
     * Scope a query to only include active FAQs.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope a query to get FAQs in the correct display order.
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order', 'asc');
    }

    /**
     * Scope a query to get FAQs sorted by creation date (newest first) as fallback.
     */
    public function scopeLatestFirst($query)
    {
        return $query->latest();
    }

    // ────────────────────────────────────────────────
    //          Optional: Accessors / Helpers
    // ────────────────────────────────────────────────

    /**
     * Get a shortened version of the question (useful for admin lists)
     */
    public function getShortQuestionAttribute(): string
    {
        return mb_strimwidth($this->question, 0, 80, '...');
    }

    /**
     * Check if this FAQ was recently created/updated
     */
    public function getIsRecentAttribute(): bool
    {
        return $this->created_at->gt(now()->subDays(7));
    }
}
