<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Carbon\Carbon;

class Holiday extends Model
{
    use HasFactory;

    protected $fillable = [
        'company_id',
        'date',
        'name',
        'description',
        'is_recurring',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'date' => 'date',
            'is_recurring' => 'boolean',
            'is_active' => 'boolean',
        ];
    }

    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

    /**
     * Scope for active holidays
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope for holidays on a specific date
     * Also checks recurring holidays
     */
    public function scopeOnDate($query, $date, $companyId = null)
    {
        $checkDate = is_string($date) ? Carbon::parse($date) : $date;

        return $query->where('is_active', true)
            ->where(function ($q) use ($companyId) {
                $q->whereNull('company_id')
                    ->orWhere('company_id', $companyId);
            })
            ->where(function ($q) use ($checkDate) {
                // Exact date match
                $q->whereDate('date', $checkDate)
                    // Or recurring match (same month and day)
                    ->orWhere(function ($subQ) use ($checkDate) {
                        $subQ->where('is_recurring', true)
                            ->whereMonth('date', $checkDate->month)
                            ->whereDay('date', $checkDate->day);
                    });
            });
    }

    /**
     * Check if a date is a holiday for a specific company
     */
    public static function isHoliday($date, $companyId = null): bool
    {
        return static::onDate($date, $companyId)->exists();
    }

    /**
     * Get holiday info for a date
     */
    public static function getHolidayInfo($date, $companyId = null): ?Holiday
    {
        return static::onDate($date, $companyId)->first();
    }
}
