<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;

class Article extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'slug',
        'excerpt',
        'content',
        'featured_image',
        'author',
        'category',
        'status',
        'is_featured',
        'meta',
        'views',
        'published_at',
    ];

    protected $casts = [
        'meta' => 'array',
        'is_featured' => 'boolean',
        'published_at' => 'datetime',
        'views' => 'integer',
    ];

    protected $dates = [
        'published_at',
    ];

    // Scopes
    public function scopePublished(Builder $query): Builder
    {
        return $query->where('status', 'published')
                    ->where('published_at', '<=', now());
    }

    public function scopeFeatured(Builder $query): Builder
    {
        return $query->where('is_featured', true);
    }

    public function scopeByCategory(Builder $query, string $category): Builder
    {
        return $query->where('category', $category);
    }

    // Mutators
    public function setTitleAttribute($value)
    {
        $this->attributes['title'] = $value;
        $this->attributes['slug'] = Str::slug($value);
    }

    // Accessors
    public function getExcerptAttribute($value)
    {
        return $value ?: Str::limit(strip_tags($this->content), 150);
    }

    public function getReadTimeAttribute()
    {
        $words = str_word_count(strip_tags($this->content));
        return ceil($words / 200); // 200 mots par minute
    }

    public function getCategoryLabelAttribute()
    {
        $labels = [
            'sensibilisation' => 'Sensibilisation',
            'formation' => 'Formation',
            'evenement' => 'Événement',
            'partenariat' => 'Partenariat',
            'sante' => 'Santé',
            'distribution' => 'Distribution',
            'communaute' => 'Communauté',
        ];

        return $labels[$this->category] ?? $this->category;
    }

    public function getCategoryColorAttribute()
    {
        $colors = [
            'sensibilisation' => 'blue',
            'formation' => 'green',
            'evenement' => 'red',
            'partenariat' => 'purple',
            'sante' => 'pink',
            'distribution' => 'orange',
            'communaute' => 'teal',
        ];

        return $colors[$this->category] ?? 'gray';
    }

    // Methods
    public function incrementViews()
    {
        $this->increment('views');
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }
}
