<?php
// ============================================
// SEN RDV SANTÉ+ — Services d'un hôpital
// GET /api/hopitaux/services.php?hopital_id=1
// GET /api/hopitaux/services.php?hopital_id=1&date=2025-03-20
// GET /api/hopitaux/services.php?hopital_id=1&date=2025-03-20&service_id=3
// ============================================
require_once '../config/helpers.php';
require_once '../config/database.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    repondre(['erreur' => 'Méthode non autorisée'], 405);
}
if (empty($_GET['hopital_id'])) {
    repondre(['erreur' => 'hopital_id est obligatoire'], 422);
}

$db        = getDB();
$hopitalId = (int)$_GET['hopital_id'];
$serviceIdFiltre = !empty($_GET['service_id']) ? (int)$_GET['service_id'] : null;

$stmt = $db->prepare("SELECT id, nom, ville, region FROM hopitaux WHERE id = ? AND actif = 1");
$stmt->execute([$hopitalId]);
$hopital = $stmt->fetch();
if (!$hopital) {
    repondre(['erreur' => 'Hôpital introuvable'], 404);
}

if ($serviceIdFiltre) {
    $stmt = $db->prepare("
        SELECT id, nom, description, quota_rdv_jour, duree_consultation,
               mode_rdv, quota_journalier
        FROM services
        WHERE hopital_id = ? AND id = ? AND actif = 1
    ");
    $stmt->execute([$hopitalId, $serviceIdFiltre]);
} else {
    $stmt = $db->prepare("
        SELECT id, nom, description, quota_rdv_jour, duree_consultation,
               mode_rdv, quota_journalier
        FROM services
        WHERE hopital_id = ? AND actif = 1
        ORDER BY nom ASC
    ");
    $stmt->execute([$hopitalId]);
}
$services = $stmt->fetchAll();

$date = $_GET['date'] ?? null;

foreach ($services as &$service) {
    if (!$date) continue;

    $duree = (int)($service['duree_consultation'] ?: 30);

    // je détecte le mode depuis la plage ouverte ce jour
    // la plage prime sur le mode par défaut du service
    $stmtMode = $db->prepare("
        SELECT mode_rdv FROM plages_ouvertes
        WHERE service_id = ? AND date_plage = ? AND actif = 1
        LIMIT 1
    ");
    $stmtMode->execute([$service['id'], $date]);
    $plageMode           = $stmtMode->fetch(PDO::FETCH_ASSOC);
    $modeRdv             = $plageMode ? ($plageMode['mode_rdv'] ?? 'creneaux') : ($service['mode_rdv'] ?? 'creneaux');
    $service['mode_rdv'] = $modeRdv; // je force le mode dans la réponse

    // ══════════════════════════════════════════
    // MODE QUOTA
    // ══════════════════════════════════════════
    if ($modeRdv === 'quota') {

        $stmtPlage = $db->prepare("
            SELECT id, heure_debut, heure_fin, quota
            FROM plages_ouvertes
            WHERE service_id = ? AND date_plage = ? AND actif = 1
              AND mode_rdv = 'quota'
            LIMIT 1
        ");
        $stmtPlage->execute([$service['id'], $date]);
        $plage = $stmtPlage->fetch(PDO::FETCH_ASSOC);

        if ($plage) {
            $stmtPris = $db->prepare("
                SELECT COUNT(*) AS pris FROM rendez_vous
                WHERE service_id = ? AND date_rdv = ?
                AND statut NOT IN ('annule', 'expire')
            ");
            $stmtPris->execute([$service['id'], $date]);
            $pris  = (int)$stmtPris->fetch()['pris'];
            $quota = (int)($plage['quota'] ?: $service['quota_journalier'] ?: 10);

            $service['places_restantes']   = max(0, $quota - $pris);
            $service['disponible_ce_jour'] = $service['places_restantes'] > 0;
            $service['creneaux']           = [];
            $service['plage_ouverte']      = true;
            $service['plage_horaire']      = [
                'heure_debut' => substr($plage['heure_debut'], 0, 5),
                'heure_fin'   => substr($plage['heure_fin'], 0, 5),
                'quota'       => $quota,
                'pris'        => $pris,
                'plage_id'    => (int)$plage['id'],
            ];
        } else {
            $service['places_restantes']   = 0;
            $service['disponible_ce_jour'] = false;
            $service['creneaux']           = [];
            $service['plage_ouverte']      = false;
            $service['plage_horaire']      = null;
        }

    // ══════════════════════════════════════════
    // MODE CRÉNEAUX
    // plages ouvertes uniquement — pas de créneaux récurrents
    // ══════════════════════════════════════════
    } else {

        // ✅ je charge les plages EN PREMIER avant tout check
        $stmtPlages = $db->prepare("
            SELECT id, heure_debut, heure_fin, duree_creneau
            FROM plages_ouvertes
            WHERE service_id = ? AND date_plage = ? AND actif = 1
              AND (mode_rdv = 'creneaux' OR mode_rdv IS NULL)
        ");
        $stmtPlages->execute([$service['id'], $date]);
        $plages = $stmtPlages->fetchAll();

        // pas de plage ouverte ce jour → service non disponible
        if (count($plages) === 0) {
            $service['places_restantes']   = 0;
            $service['disponible_ce_jour'] = false;
            $service['creneaux']           = [];
            $service['plage_ouverte']      = false;
            $service['plage_horaire']      = null;
            continue;
        }

        // heures déjà occupées
        $stmtPris = $db->prepare("
            SELECT heure_rdv FROM rendez_vous
            WHERE service_id = ? AND date_rdv = ?
            AND statut NOT IN ('annule', 'expire')
        ");
        $stmtPris->execute([$service['id'], $date]);
        $heuresOccupees = array_column($stmtPris->fetchAll(), 'heure_rdv');

        // je génère les créneaux depuis les plages uniquement
        $creneauxFinal = [];
        foreach ($plages as $plage) {
            $dureeUtilisee = !empty($plage['duree_creneau']) ? (int)$plage['duree_creneau'] : $duree;
            $heureDebut    = strtotime($date . ' ' . $plage['heure_debut']);
            $heureFin      = strtotime($date . ' ' . $plage['heure_fin']);

            while ($heureDebut < $heureFin) {
                $heureStr    = date('H:i:s', $heureDebut);
                $heureFinStr = date('H:i:s', $heureDebut + $dureeUtilisee * 60);

                if (!in_array($heureStr, $heuresOccupees)) {
                    $creneauxFinal[] = [
                        'id'            => 'plage_' . $plage['id'] . '_' . str_replace(':', '', $heureStr),
                        'heure_debut'   => $heureStr,
                        'heure_fin'     => $heureFinStr,
                        'source'        => 'plage_ouverte',
                        'auto_confirme' => true,
                    ];
                }
                $heureDebut += $dureeUtilisee * 60;
            }
        }

        usort($creneauxFinal, function($a, $b) { return strcmp($a['heure_debut'], $b['heure_debut']); });

        $pris = count($heuresOccupees);
        $service['places_restantes']   = max(0, $service['quota_rdv_jour'] - $pris);
        $service['disponible_ce_jour'] = count($creneauxFinal) > 0;
        $service['creneaux']           = $creneauxFinal;
        $service['plage_ouverte']      = true;
        $service['plage_horaire']      = null;
    }
}
unset($service);

repondre([
    'succes'   => true,
    'hopital'  => $hopital,
    'services' => $services,
]);