<?php

namespace App\Models;

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

class HomepageSlide extends Model
{
    use HasFactory;

    protected $fillable = [
        'eyebrow', 'title', 'description',
        'primary_cta_label', 'primary_cta_url',
        'secondary_cta_label', 'secondary_cta_url',
        'image_path', 'image_alt',
        'background_variant', 'text_alignment', 'text_color',
        'sort_order', 'is_active',
        'starts_at', 'ends_at',
    ];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'starts_at' => 'datetime',
            'ends_at' => 'datetime',
            'sort_order' => 'integer',
        ];
    }

    protected static function booted(): void
    {
        static::saved(function () {
            \Illuminate\Support\Facades\Cache::forget('homepage.hero.slides');
        });

        static::deleted(function () {
            \Illuminate\Support\Facades\Cache::forget('homepage.hero.slides');
        });
    }

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

    public function scopeScheduled($query)
    {
        return $query
            ->where(function ($q) {
                $q->whereNull('starts_at')->orWhere('starts_at', '<=', now());
            })
            ->where(function ($q) {
                $q->whereNull('ends_at')->orWhere('ends_at', '>=', now());
            });
    }

    public function scopeSortable($query)
    {
        return $query->orderBy('sort_order');
    }
}
