<?php
declare(strict_types=1);

namespace App\Modules\HR\Models;

use App\Core\Model;
use App\Core\App;

class HrHoliday extends Model
{
    protected static string $table = 'hr_holidays';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = true;
    protected static bool $autoTrackAuthor = true;

    protected static array $fillable = [
        'name_ar', 'name_en', 'holiday_type', 'date', 'duration_days',
        'is_recurring', 'recurring_month', 'recurring_day', 'religion', 'is_active',
    ];

    public static function getHolidayTypes(): array
    {
        return [
            'national'  => 'عطلة رسمية',
            'religious'  => 'عطلة دينية',
            'company'   => 'عطلة خاصة بالنادي',
        ];
    }

    public static function getForYear(int $year): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM hr_holidays
             WHERE is_active = 1 AND is_archived = 0
               AND (YEAR(`date`) = ? OR is_recurring = 1)
             ORDER BY `date` ASC",
            [$year]
        );
    }

    public static function isHoliday(string $date, ?string $religion = null): bool
    {
        $db = App::getInstance()->db();
        $month = (int) date('m', strtotime($date));
        $day = (int) date('d', strtotime($date));

        $where = "is_active = 1 AND is_archived = 0 AND ((`date` = ?) OR (is_recurring = 1 AND recurring_month = ? AND recurring_day = ?))";
        $params = [$date, $month, $day];

        if ($religion !== null) {
            $where .= " AND (religion IS NULL OR religion = ?)";
            $params[] = $religion;
        } else {
            $where .= " AND religion IS NULL";
        }

        $row = $db->selectOne("SELECT id FROM hr_holidays WHERE {$where} LIMIT 1", $params);
        return $row !== null;
    }

    public static function allActive(): array
    {
        return static::query()
            ->where('is_active', '=', 1)
            ->orderBy('date', 'ASC')
            ->get();
    }
}
