<?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 HelpCenterArticle extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'topic_id',
        'title',
        'slug',
        'hero_image',
        'summary',
        'content',
        'estimated_reading_time',
        'display_order',
        'is_featured',
        'is_published',
        'view_count',
        'meta_title',
        'meta_description',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'is_featured' => 'boolean',
        'is_published' => 'boolean',
        'display_order' => 'integer',
        'estimated_reading_time' => 'integer',
        'view_count' => 'integer',
    ];

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

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

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

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

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

    public function topic()
    {
        return $this->belongsTo(HelpCenterTopic::class, 'topic_id');
    }
}
