<?php

namespace App\Models;

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

class Charity extends Model
{
    use HasFactory;
    
    protected $fillable = [
        'name',
        'slug',
        'description',
        'logo',
        'logo_alt',
        'website_url',
        'status',
        'sort_order',
        'is_featured',
        'meta_title',
        'meta_description',
        'meta_keywords',
        'meta_robots',
        'canonical_url',
    ];

    protected $casts = [
        'is_featured' => 'boolean',
        'sort_order' => 'integer',
    ];

    /**
     * Boot the model.
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($charity) {
            if (empty($charity->slug)) {
                $charity->slug = Str::slug($charity->name);
            }
        });

        static::updating(function ($charity) {
            if ($charity->isDirty('name') && empty($charity->slug)) {
                $charity->slug = Str::slug($charity->name);
            }
        });
    }

    /**
     * Scope a query to only include active charities.
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * Scope a query to only include featured charities.
     */
    public function scopeFeatured($query)
    {
        return $query->where('is_featured', true);
    }

    /**
     * Get the route key for the model.
     */
    public function getRouteKeyName()
    {
        return 'slug';
    }
}
