<?php

namespace App\Models;

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

class Announcement extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'body',
        'type',
        'display_mode',
        'audience',
        'is_active',
        'is_dismissible',
        'starts_at',
        'expires_at',
    ];

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

    public function dismissals()
    {
        return $this->hasMany(AnnouncementDismissal::class);
    }

    /**
     * Scope to filter only live announcements (active and within date window)
     */
    public function scopeLive($query)
    {
        return $query
            ->where('is_active', true)
            ->where(function ($q) {
                $q->whereNull('starts_at')
                    ->orWhere('starts_at', '<=', now());
            })
            ->where(function ($q) {
                $q->whereNull('expires_at')
                    ->orWhere('expires_at', '>', now());
            });
    }

    /**
     * Scope to filter by audience (authenticated vs guest)
     */
    public function scopeForAudience($query, bool $isAuthenticated)
    {
        return $query->where(function ($q) use ($isAuthenticated) {
            $q->where('audience', 'all');
            if ($isAuthenticated) {
                $q->orWhere('audience', 'authenticated');
            } else {
                $q->orWhere('audience', 'guests');
            }
        });
    }

    /**
     * Get type color classes for badge styling
     */
    public function getTypeColorAttribute(): array
    {
        return match ($this->type) {
            'info' => ['bg' => 'bg-blue-100', 'border' => 'border-blue-300', 'text' => 'text-blue-800', 'badge' => 'bg-blue-500'],
            'warning' => ['bg' => 'bg-yellow-100', 'border' => 'border-yellow-300', 'text' => 'text-yellow-800', 'badge' => 'bg-yellow-500'],
            'success' => ['bg' => 'bg-green-100', 'border' => 'border-green-300', 'text' => 'text-green-800', 'badge' => 'bg-green-500'],
            'promo' => ['bg' => 'bg-purple-100', 'border' => 'border-purple-300', 'text' => 'text-purple-800', 'badge' => 'bg-purple-500'],
            default => ['bg' => 'bg-gray-100', 'border' => 'border-gray-300', 'text' => 'text-gray-800', 'badge' => 'bg-gray-500'],
        };
    }
}
