<?php

namespace App\Models;

use App\Support\BadWordFilter;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Blog extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id', 'category_id', 'title', 'slug', 'excerpt', 'content',
        'featured_image', 'language', 'tags', 'status', 'views', 'published_at',
    ];

    protected $casts = [
        'tags'         => 'array',
        'published_at' => 'datetime',
    ];

    protected static function booted(): void
    {
        static::saving(function ($blog) {
            $blog->title = BadWordFilter::sanitize($blog->title);
            $blog->excerpt = BadWordFilter::sanitize($blog->excerpt);
            $blog->content = BadWordFilter::sanitize($blog->content);
        });

        static::creating(function ($blog) {
            if (empty($blog->slug)) {
                $blog->slug = Str::slug($blog->title) . '-' . Str::random(6);
            }
            if ($blog->status === 'published' && empty($blog->published_at)) {
                $blog->published_at = now();
            }
        });
    }

    public function author()   { return $this->belongsTo(User::class, 'user_id'); }
    public function category() { return $this->belongsTo(Category::class); }

    public function scopePublished($query)
    {
        return $query->where('status', 'published')
                     ->whereNotNull('published_at');
    }

    public function featuredImageUrl(): string
    {
        if ($this->featured_image) {
            return asset('uploads/blogs/' . $this->featured_image);
        }
        return 'https://placehold.co/800x450/1B3B2F/D4AF37?text=' . urlencode(Str::limit($this->title, 30));
    }

    public function readingTime(): int
    {
        $words = str_word_count(strip_tags($this->content));
        return max(1, (int)ceil($words / 200));
    }
}
