<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class HelpCenterTopic extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'title',
        'slug',
        'icon',
        'description',
        'display_order',
        'is_active',
        'meta_title',
        'meta_description',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'display_order' => 'integer',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function (HelpCenterTopic $topic) {
            if (empty($topic->slug)) {
                $topic->slug = Str::slug($topic->title);
            }

            if (Auth::check()) {
                $topic->created_by = Auth::id();
                $topic->updated_by = Auth::id();
            }
        });

        static::updating(function (HelpCenterTopic $topic) {
            if (Auth::check()) {
                $topic->updated_by = Auth::id();
            }
        });
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function articles()
    {
        return $this->hasMany(HelpCenterArticle::class, 'topic_id')
            ->orderBy('display_order')
            ->orderBy('title');
    }
}
