<?php
// ============================================
// SEN RDV SANTÉ+ — Liste des RDV du patient connecté
// GET /api/rdv/liste.php
// Headers: Authorization: Bearer {token}
// ============================================
require_once '../config/helpers.php';
require_once '../config/database.php';

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

$userConnecte = verifierToken();
$db = getDB();

// ═══════════════════════════════════════
// ✅ POINT 7 — EXPIRE AUTO DES RDV PASSÉS
// ═══════════════════════════════════════
$db->prepare("
    UPDATE rendez_vous 
    SET statut = 'expire' 
    WHERE date_rdv < CURDATE() 
      AND statut NOT IN ('consomme', 'annule', 'expire')
")->execute();

$db->prepare("
    UPDATE rendez_vous 
    SET statut = 'expire' 
    WHERE date_rdv = CURDATE() 
      AND heure_rdv < CURTIME()
      AND statut NOT IN ('consomme', 'annule', 'expire')
")->execute();
// ═══════════════════════════════════════

$sql = "
    SELECT r.id, r.patient_nom, r.patient_prenom, r.motif,
           r.date_rdv, r.heure_rdv, r.statut,
           r.date_proposee, r.heure_proposee,
           r.numero_file,
           r.statut_file,
           s.nom        AS service_nom,
           s.mode_rdv   AS mode_rdv,
           h.id         AS hopital_id,
           h.nom        AS hopital_nom,
           h.adresse    AS hopital_adresse,
           t.code_qr, t.prioritaire,
           t.heure_validite_debut, t.heure_validite_fin,
           p.montant, p.statut AS paiement_statut, p.expire_at AS paiement_expire
    FROM rendez_vous r
    JOIN services s ON s.id = r.service_id
    JOIN hopitaux h ON h.id = s.hopital_id
    LEFT JOIN tickets t ON t.rdv_id = r.id
    LEFT JOIN paiements p ON p.rdv_id = r.id
    WHERE r.patient_id = ?
";

$params = [$userConnecte['utilisateur_id']];

if (!empty($_GET['statut'])) {
    $sql .= " AND r.statut = ?";
    $params[] = $_GET['statut'];
}

$sql .= "
    ORDER BY
        CASE WHEN r.date_rdv >= CURDATE() THEN 0 ELSE 1 END ASC,
        CASE WHEN r.date_rdv >= CURDATE() THEN r.date_rdv END ASC,
        CASE WHEN r.date_rdv < CURDATE() THEN r.date_rdv END DESC,
        r.heure_rdv ASC
";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$rdvs = $stmt->fetchAll();

foreach ($rdvs as &$rdv) {
    $rdv['prioritaire']    = (bool) $rdv['prioritaire'];
    $rdv['a_un_ticket']    = !empty($rdv['code_qr']);
    $rdv['report_propose'] = !empty($rdv['date_proposee']);
    $rdv['numero_file']    = $rdv['numero_file'] ? (int) $rdv['numero_file'] : null;
}
unset($rdv);

repondre([
    'succes' => true,
    'total'  => count($rdvs),
    'rdvs'   => $rdvs,
]);