<?php
namespace App\Models;

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

class Blog extends Model
{
    use HasFactory, SoftDeletes;
    
    protected $table = 'blog_posts';
    
    protected $fillable = [
        'title',
        'slug',
        'description',
        'content',
        'type',
        'category',
        'category_name',
        'is_featured',
        'thumbnail',
        'meta_title',
        'meta_keywords',
        'meta_description',
        'meta_og_image',
        'meta_og_url',
        'hits',
        'order',
        'status',
        'moderated_by',
        'moderated_at',
        'active',
        'user_id',
        'created_by_name',
        'created_by_alias',
        'updated_by',
        'deleted_by',
        'published_at',
        'category_id',
    ];

    protected $casts = [
        'active' => 'boolean',
        'is_featured' => 'boolean',
        'published_at' => 'datetime',
        'moderated_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    protected $dates = [
        'published_at',
        'moderated_at',
        'created_at',
        'updated_at',
        'deleted_at',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function category()
    {
        return $this->belongsTo(BlogCategory::class, 'category_id');
    }

    public function moderator()
    {
        return $this->belongsTo(User::class, 'moderated_by');
    }

    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    public function deleter()
    {
        return $this->belongsTo(User::class, 'deleted_by');
    }

    // Scope for published blogs
    public function scopePublished($query)
    {
        return $query->where('status', 'Published')->where('active', true);
    }

    // Scope for featured blogs
    public function scopeFeatured($query)
    {
        return $query->where('is_featured', true);
    }

    // Accessor for thumbnail URL
    public function getThumbnailUrlAttribute()
    {
        if ($this->thumbnail) {
            return asset('storage/' . $this->thumbnail);
        }
        return null;
    }
}
