<?php
declare(strict_types=1);

namespace App\Models;

use App\Core\Database;

final class SchoolCalendar
{
    /**
     * Renvoie les fermetures CDA configurées. Lorsque le calendrier 2026-2027
     * n'a pas encore été rempli, le calendrier officiel de la zone B sert de
     * filet de sécurité afin qu'aucun télétravail annualisé ne soit créé
     * pendant les vacances.
     */
    public static function closures(int $organisationId, string $from, string $to): array
    {
        $q = Database::connection()->prepare(
            "SELECT pf.date_debut, pf.date_fin, pf.type_fermeture, pf.libelle
               FROM periodes_fermeture pf
               INNER JOIN calendriers_scolaires cs ON cs.id=pf.calendrier_id
                AND cs.organisation_id=? AND cs.actif=1
              WHERE pf.date_debut<=? AND pf.date_fin>=?
              ORDER BY pf.date_debut"
        );
        $q->execute([$organisationId, $to, $from]);
        $closures = $q->fetchAll() ?: [];

        $fallback = [
            ['2026-10-17', '2026-11-01', 'vacances_scolaires', 'Vacances de la Toussaint'],
            ['2026-12-19', '2027-01-03', 'vacances_scolaires', 'Vacances de Noël'],
            ['2027-02-20', '2027-03-07', 'vacances_scolaires', 'Vacances d’hiver — zone B'],
            ['2027-04-17', '2027-05-02', 'vacances_scolaires', 'Vacances de printemps — zone B'],
            ['2027-07-03', '2027-08-31', 'vacances_scolaires', 'Vacances d’été'],
        ];
        foreach ($fallback as [$start, $end, $type, $label]) {
            if ($start > $to || $end < $from) {
                continue;
            }
            $alreadyCovered = false;
            foreach ($closures as $closure) {
                if ($start >= $closure['date_debut'] && $end <= $closure['date_fin']) {
                    $alreadyCovered = true;
                    break;
                }
            }
            if (!$alreadyCovered) {
                $closures[] = [
                    'date_debut' => $start,
                    'date_fin' => $end,
                    'type_fermeture' => $type,
                    'libelle' => $label,
                ];
            }
        }
        return $closures;
    }

    public static function isClosed(string $date, array $closures): bool
    {
        foreach ($closures as $closure) {
            if ($date >= $closure['date_debut'] && $date <= $closure['date_fin']) {
                return true;
            }
        }
        return false;
    }
}
