<?php
// ============================================
// SEN RDV SANTÉ+ — Recherche par disponibilité
// GET /api/hopitaux/recherche.php
// ============================================
require_once '../config/helpers.php';   // ← TOUJOURS en premier
require_once '../config/database.php';

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

$db = getDB();

$specialite = $_GET['specialite'] ?? '';
$dateDebut  = $_GET['date_debut'] ?? date('Y-m-d');
$dateFin    = $_GET['date_fin']   ?? date('Y-m-d', strtotime('+7 days'));
$moment     = $_GET['moment']     ?? 'tous';
$type       = $_GET['type']       ?? 'tous';
$urgence    = isset($_GET['urgence']) && $_GET['urgence'] == 1;

$heureMin = '08:00:00';
$heureMax = '18:00:00';
if ($moment === 'matin')     { $heureMin = '08:00:00'; $heureMax = '12:00:00'; }
if ($moment === 'apresmidi') { $heureMin = '14:00:00'; $heureMax = '18:00:00'; }

if ($urgence) {
    $heureMin  = date('H:i:s');
    $heureMax  = date('H:i:s', strtotime('+2 hours'));
    $dateDebut = date('Y-m-d');
    $dateFin   = date('Y-m-d');
}

// ── je récupère les services qui correspondent ──
// DISTINCT sur (service_id, hopital_id) pour éviter les doublons
$sql = "
    SELECT DISTINCT
        s.id          AS service_id,
        s.nom         AS service_nom,
        s.quota_rdv_jour,
        s.duree_consultation,
        s.mode_rdv,
        s.quota_journalier,
        h.id          AS hopital_id,
        h.nom         AS hopital_nom,
        h.type,
        COALESCE(h.ville, v.nom, '') AS ville
    FROM services s
    JOIN hopitaux h ON h.id = s.hopital_id AND h.actif = 1
    LEFT JOIN villes v ON v.id = h.ville_id
    WHERE s.actif = 1
";

$params = [];

if (!empty($specialite)) {
    $sql   .= " AND s.nom LIKE ?";
    $params[] = '%' . $specialite . '%';
}

if ($type !== 'tous') {
    $sql   .= " AND h.type = ?";
    $params[] = $type;
}

$sql .= " ORDER BY h.nom ASC, s.nom ASC";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$services = $stmt->fetchAll(PDO::FETCH_ASSOC);

$resultats = [];

foreach ($services as $service) {

    // ── Mode A : créneaux horaires ──
    if ($service['mode_rdv'] === 'creneaux' || empty($service['mode_rdv'])) {

        // je compte les RDVs déjà pris sur la période
        $stmt2 = $db->prepare("
            SELECT COUNT(*) AS pris FROM rendez_vous
            WHERE service_id = ? AND date_rdv BETWEEN ? AND ?
            AND statut NOT IN ('annule', 'expire')
        ");
        $stmt2->execute([$service['service_id'], $dateDebut, $dateFin]);
        $pris = (int)$stmt2->fetch()['pris'];

        $placesRestantes = max(0, $service['quota_rdv_jour'] - $pris);
        if ($placesRestantes === 0) continue;

        // je récupère les créneaux disponibles sans doublons
        // en excluant ceux déjà pris par un RDV existant
        $stmt3 = $db->prepare("
            SELECT DISTINCT c.id, c.heure_debut, c.heure_fin
            FROM creneaux c
            WHERE c.service_id = ?
              AND c.disponible  = 1
              AND c.heure_debut >= ?
              AND c.heure_debut <= ?
              AND c.date_specifique IS NULL
              AND NOT EXISTS (
                SELECT 1 FROM rendez_vous r
                WHERE r.service_id = c.service_id
                  AND r.heure_rdv  = c.heure_debut
                  AND r.date_rdv  BETWEEN ? AND ?
                  AND r.statut NOT IN ('annule', 'expire')
              )
            ORDER BY c.heure_debut ASC
            LIMIT 4
        ");
        $stmt3->execute([
            $service['service_id'],
            $heureMin, $heureMax,
            $dateDebut, $dateFin,
        ]);
        $creneaux = $stmt3->fetchAll(PDO::FETCH_ASSOC);

        // je cherche aussi dans les plages ouvertes
        $stmt4 = $db->prepare("
            SELECT DISTINCT p.heure_debut, p.heure_fin, p.duree_creneau
            FROM plages_ouvertes p
            WHERE p.service_id = ?
              AND p.date_plage BETWEEN ? AND ?
              AND p.actif = 1
              AND p.heure_debut >= ?
            LIMIT 2
        ");
        $stmt4->execute([$service['service_id'], $dateDebut, $dateFin, $heureMin]);
        $plages = $stmt4->fetchAll(PDO::FETCH_ASSOC);

        // j'ajoute les créneaux de plages non déjà présents
        $heuresDeja = array_column($creneaux, 'heure_debut');
        foreach ($plages as $p) {
            if (!in_array($p['heure_debut'], $heuresDeja)) {
                $creneaux[] = [
                    'id'          => 'plage_' . str_replace(':', '', $p['heure_debut']),
                    'heure_debut' => $p['heure_debut'],
                    'heure_fin'   => $p['heure_fin'],
                ];
                $heuresDeja[] = $p['heure_debut'];
            }
        }

        if (empty($creneaux) && !$urgence) continue;

        $resultats[] = [
            'service_id'           => $service['service_id'],
            'service_nom'          => $service['service_nom'],
            'hopital_id'           => $service['hopital_id'],
            'hopital_nom'          => $service['hopital_nom'],
            'type'                 => $service['type'],
            'ville'                => $service['ville'],
            'mode_rdv'             => 'creneaux',
            'places_restantes'     => $placesRestantes,
            'duree_consultation'   => $service['duree_consultation'],
            'creneaux_disponibles' => array_slice($creneaux, 0, 4),
        ];

    // ── Mode B : quota journalier ──
    } else {

        $quota = (int)($service['quota_journalier'] ?: 10);

        // je cherche les plages ouvertes en mode quota sur la période
        $stmtQ = $db->prepare("
            SELECT p.date_plage, p.heure_debut, p.heure_fin, p.quota,
                   COUNT(r.id) AS pris
            FROM plages_ouvertes p
            LEFT JOIN rendez_vous r ON r.service_id = p.service_id
                AND r.date_rdv = p.date_plage
                AND r.statut NOT IN ('annule', 'expire')
            WHERE p.service_id = ?
              AND p.date_plage BETWEEN ? AND ?
              AND p.actif = 1
              AND p.mode_rdv = 'quota'
            GROUP BY p.id
            HAVING pris < COALESCE(p.quota, ?)
            ORDER BY p.date_plage ASC
            LIMIT 1
        ");
        $stmtQ->execute([$service['service_id'], $dateDebut, $dateFin, $quota]);
        $plageQuota = $stmtQ->fetch(PDO::FETCH_ASSOC);

        if (!$plageQuota) continue;

        $placesRestantes = (int)($plageQuota['quota'] ?: $quota) - (int)$plageQuota['pris'];
        if ($placesRestantes <= 0) continue;

        $resultats[] = [
            'service_id'         => $service['service_id'],
            'service_nom'        => $service['service_nom'],
            'hopital_id'         => $service['hopital_id'],
            'hopital_nom'        => $service['hopital_nom'],
            'type'               => $service['type'],
            'ville'              => $service['ville'],
            'mode_rdv'           => 'quota',
            'places_restantes'   => $placesRestantes,
            'duree_consultation' => $service['duree_consultation'],
            'plage_horaire'      => $plageQuota['heure_debut'] . ' → ' . $plageQuota['heure_fin'],
            'creneaux_disponibles' => [], // pas de créneaux fixes en mode quota
        ];
    }
}

repondre([
    'succes'    => true,
    'total'     => count($resultats),
    'resultats' => $resultats,
    'criteres'  => [
        'specialite' => $specialite,
        'date_debut' => $dateDebut,
        'date_fin'   => $dateFin,
        'moment'     => $moment,
        'urgence'    => $urgence,
    ],
]);