<?php
require_once __DIR__ . '/../config/helpers.php';
require_once __DIR__ . '/../config/database.php';

header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

$action = $_GET['action'] ?? '';
$db = getDB();

try {
    if ($action === 'hopitaux') {
        $sql = "SELECT id, nom, adresse, ville, region, type
                FROM hopitaux
                WHERE actif = 1
                ORDER BY region ASC, ville ASC, nom ASC";
        $stmt = $db->query($sql);
        $hopitaux = $stmt->fetchAll(PDO::FETCH_ASSOC);

        repondre([
            'succes' => true,
            'hopitaux' => $hopitaux
        ], 200);
    }

    if ($action === 'creneaux') {
        $hopital_id = (int)($_GET['hopital_id'] ?? 0);

        if (!$hopital_id) {
            repondre([
                'succes' => false,
                'erreur' => 'Identifiant établissement manquant.'
            ], 400);
        }

        $sql = "SELECT
                    po.id,
                    po.service_id,
                    po.date_plage,
                    po.heure_debut,
                    po.heure_fin,
                    po.quota,
                    po.mode_rdv,
                    s.nom AS service_nom
                FROM plages_ouvertes po
                INNER JOIN services s ON po.service_id = s.id
                WHERE s.hopital_id = :hopital_id
                  AND po.actif = 1
                  AND s.actif = 1
                  AND po.date_plage >= CURDATE()
                ORDER BY po.date_plage ASC, s.nom ASC, po.heure_debut ASC";

        $stmt = $db->prepare($sql);
        $stmt->execute([':hopital_id' => $hopital_id]);
        $plages = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (empty($plages)) {
            repondre([
                'succes' => false,
                'message' => 'Aucun créneau disponible pour cet établissement actuellement.'
            ], 200);
        }

        repondre([
            'succes' => true,
            'creneaux' => $plages
        ], 200);
    }

    repondre([
        'succes' => false,
        'erreur' => 'Action invalide.'
    ], 400);

} catch (PDOException $e) {
    error_log('disponibilites.php: ' . $e->getMessage());
    repondre([
        'succes' => false,
        'erreur' => 'Erreur de base de données.'
    ], 500);
}
