<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SEN RDV SANTÉ+ — Gérant de Service</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>tailwind.config = { theme: { extend: { colors: { primary: '#0066CC', dark: '#003F8A' } } } }</script>
    <style>
        .filtre-btn { background: white; color: #6b7280; border: 2px solid #f3f4f6; }
        .filtre-actif { background: #0066CC; color: white; border-color: #0066CC; }
        .filtre-btn:hover:not(.filtre-actif) { background: #f9fafb; border-color: #e5e7eb; }
        .duree-card {
            text-align: center; padding: 10px 8px; border-radius: 12px;
            border: 2px solid #e5e7eb; background: #f9fafb;
            font-size: 13px; font-weight: 600; color: #6b7280;
            cursor: pointer; transition: all 0.15s;
        }
        .duree-card:hover { border-color: #93c5fd; background: #eff6ff; color: #1d4ed8; }
        .duree-actif { border-color: #2563eb !important; background: #2563eb !important; color: #fff !important; }
        tr.en-cours-row { background: #f5f3ff !important; border-left: 3px solid #7c3aed; }
        tr.en-cours-row td:first-child { border-left: 4px solid #7c3aed; }
        tr.urgent-row { background: #fef2f2 !important; border-left: 3px solid #ef4444; }
        tr.urgent-row td:first-child { border-left: 4px solid #ef4444; }
        @media print {
            aside, header, .no-print { display: none !important; }
            main { margin-left: 0 !important; }
            body { background: white; }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">

<!-- ═══ SIDEBAR ═══ -->
<aside class="fixed left-0 top-0 h-full w-64 bg-[#003F8A] text-white flex flex-col z-30">
    <div class="p-6 border-b border-white/10">
        <div class="flex items-center gap-3">
            <div class="w-9 h-9 rounded-xl bg-white/10 border border-white/20 flex items-center justify-center">
                <span class="text-white text-lg font-light">+</span>
            </div>
            <div>
                <p class="font-black text-sm tracking-wide">SEN RDV SANTÉ+</p>
                <p class="text-white/50 text-xs">Gérant de Service</p>
            </div>
        </div>
    </div>
    <div class="p-4 border-b border-white/10">
        <div class="bg-white/10 rounded-xl p-3 space-y-2">
            <p id="user-nom" class="font-bold text-sm">Chargement...</p>
            <p id="user-hopital" class="text-white/60 text-xs">🏥 —</p>
            <div id="user-services-badges" class="flex flex-wrap gap-1"></div>
        </div>
    </div>
    <nav class="flex-1 p-4 space-y-1">
        <button onclick="afficherSection('rdvs')"      class="nav-btn w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-white/80 hover:text-white hover:bg-white/10 transition-all text-sm text-left"><span>📋</span> Rendez-vous</button>
        <button onclick="afficherSection('file')"      class="nav-btn w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-white/80 hover:text-white hover:bg-white/10 transition-all text-sm text-left"><span>🔢</span> File d'attente</button>
        <button onclick="afficherSection('creer-rdv')" class="nav-btn w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-white/80 hover:text-white hover:bg-white/10 transition-all text-sm text-left"><span>➕</span> Créer un RDV</button>
        <button onclick="afficherSection('plage')"     class="nav-btn w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-white/80 hover:text-white hover:bg-white/10 transition-all text-sm text-left"><span>🔓</span> Ouvrir une plage</button>
        <button onclick="afficherSection('creneaux')"  class="nav-btn w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-white/80 hover:text-white hover:bg-white/10 transition-all text-sm text-left"><span>🕐</span> Mes créneaux</button>
        <button onclick="afficherSection('stats')"     class="nav-btn w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-white/80 hover:text-white hover:bg-white/10 transition-all text-sm text-left"><span>📊</span> Statistiques</button>
        <button onclick="afficherSection('profil')"    class="nav-btn w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-white/80 hover:text-white hover:bg-white/10 transition-all text-sm text-left"><span>👤</span> Mon profil</button>
    </nav>
    <div class="p-4 border-t border-white/10">
        <button onclick="seDeconnecter()" class="w-full flex items-center gap-2 px-3 py-2.5 rounded-xl text-white/60 hover:text-white hover:bg-white/10 transition-all text-sm"><span>🚪</span> Se déconnecter</button>
    </div>
</aside>

<!-- ═══ CONTENU ═══ -->
<main class="ml-64 min-h-screen">

    <header class="bg-white border-b border-gray-100 px-8 py-4 flex items-center justify-between sticky top-0 z-20">
        <div>
            <h1 id="page-titre" class="text-lg font-bold text-gray-900">Rendez-vous du jour</h1>
            <p id="page-date" class="text-sm text-gray-400"></p>
        </div>
        <div class="flex items-center gap-3 no-print">
            <div id="filtre-service-zone" class="hidden">
                <select id="filtre-service-select" onchange="chargerRdvs()"
                    class="px-3 py-2 rounded-xl border-2 border-gray-100 bg-white text-sm font-semibold text-gray-600 focus:outline-none focus:border-blue-500">
                    <option value="">Tous mes services</option>
                </select>
            </div>
            <div id="stats-badges" class="flex gap-2"></div>
            <button onclick="imprimerListe()" class="flex items-center gap-2 px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl text-sm font-semibold text-gray-600">🖨️ Imprimer</button>
            <button onclick="chargerRdvs()" class="flex items-center gap-2 px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl text-sm font-semibold text-gray-600">🔄 Actualiser</button>
        </div>
    </header>

    <!-- toast -->
    <div id="toast" class="fixed top-6 right-6 z-50 hidden">
        <div id="toast-inner" class="px-5 py-3 rounded-2xl shadow-xl text-sm font-semibold text-white"></div>
    </div>

    <!-- modal confirm -->
    <div id="modal-confirm" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl p-6 max-w-sm w-full shadow-2xl">
            <p id="modal-message" class="text-gray-900 font-semibold text-center mb-6"></p>
            <div class="flex gap-3">
                <button id="modal-cancel" class="flex-1 py-2.5 rounded-xl border-2 border-gray-200 text-gray-600 font-semibold">Annuler</button>
                <button id="modal-ok" class="flex-1 py-2.5 rounded-xl bg-blue-600 text-white font-semibold">Confirmer</button>
            </div>
        </div>
    </div>

    <!-- modal report -->
    <div id="modal-report" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl p-6 max-w-sm w-full shadow-2xl">
            <h3 class="font-bold text-gray-900 mb-4">↻ Proposer un report</h3>
            <input type="hidden" id="report-rdv-id" />
            <div class="space-y-3">
                <div>
                    <label class="block text-sm font-semibold text-gray-600 mb-1.5">Nouvelle date</label>
                    <input type="date" id="report-date" class="w-full px-3 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500" />
                </div>
                <div>
                    <label class="block text-sm font-semibold text-gray-600 mb-1.5">Nouvelle heure</label>
                    <input type="time" id="report-heure" class="w-full px-3 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500" />
                </div>
            </div>
            <div class="flex gap-3 mt-4">
                <button onclick="document.getElementById('modal-report').classList.add('hidden')" class="flex-1 py-2.5 rounded-xl border-2 border-gray-200 text-gray-600 font-semibold">Annuler</button>
                <button onclick="envoyerReport()" class="flex-1 py-2.5 rounded-xl bg-amber-500 text-white font-semibold hover:bg-amber-600">Proposer</button>
            </div>
        </div>
    </div>

<!-- ─── SECTION RDVs ─── -->
<section id="section-rdvs" class="p-8">
    <div class="hidden print:block mb-6">
        <h2 id="print-titre" class="text-2xl font-black text-gray-900">Liste des RDVs</h2>
        <p id="print-date" class="text-gray-500 mt-1"></p>
    </div>
    <div class="flex items-center gap-3 mb-4 flex-wrap no-print">
        <button onclick="filtrerRdvs('tous')"       id="filtre-tous"       class="filtre-btn filtre-actif px-4 py-2 rounded-xl text-sm font-semibold">Tous</button>
        <button onclick="filtrerRdvs('en_attente')" id="filtre-en_attente" class="filtre-btn px-4 py-2 rounded-xl text-sm font-semibold">⏳ En attente</button>
        <button onclick="filtrerRdvs('confirme')"   id="filtre-confirme"   class="filtre-btn px-4 py-2 rounded-xl text-sm font-semibold">✅ Confirmés</button>
        <button onclick="filtrerRdvs('paye')"       id="filtre-paye"       class="filtre-btn px-4 py-2 rounded-xl text-sm font-semibold">🎫 Payés</button>
        <button onclick="filtrerRdvs('consomme')"   id="filtre-consomme"   class="filtre-btn px-4 py-2 rounded-xl text-sm font-semibold">✔️ Terminés</button>
        <input type="date" id="filtre-date" onchange="chargerRdvs()"
            class="px-4 py-2 rounded-xl border-2 border-gray-100 bg-white text-sm font-semibold text-gray-600 focus:outline-none focus:border-blue-500" />
        <button onclick="activerModeSelection()" id="btn-mode-selection"
            class="ml-auto px-4 py-2 bg-blue-600 text-white rounded-xl text-sm font-bold hover:bg-blue-700">
            ☑️ Sélection multiple
        </button>
    </div>
    <div id="barre-masse" class="hidden mb-4 p-4 bg-blue-50 rounded-xl border border-blue-200 flex items-center justify-between gap-4 no-print">
        <div class="flex items-center gap-3">
            <input type="checkbox" id="select-all-rdvs" onchange="toggleSelectAll(this.checked)" class="w-4 h-4 rounded text-blue-600 cursor-pointer" />
            <label for="select-all-rdvs" class="text-sm font-semibold text-blue-800 cursor-pointer">Tout sélectionner</label>
            <span id="selection-label" class="text-sm text-blue-600 font-bold">0 RDV sélectionné(s)</span>
        </div>
        <div class="flex gap-2">
            <button onclick="confirmerSelectionnes()" class="px-4 py-2 bg-green-500 hover:bg-green-600 text-white text-sm font-bold rounded-xl">✓ Confirmer la sélection</button>
            <button onclick="annulerBarre()" class="px-4 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 text-sm font-semibold rounded-xl">✕ Annuler</button>
        </div>
    </div>
    <div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
        <table class="w-full">
            <thead>
                <tr class="bg-gray-50 border-b border-gray-100">
                    <th class="text-left px-4 py-4 text-xs font-semibold text-gray-500 uppercase w-10">#</th>
                    <th class="text-left px-4 py-4 text-xs font-semibold text-gray-500 uppercase w-16">N° File</th>
                    <th class="text-left px-4 py-4 text-xs font-semibold text-gray-500 uppercase">Patient</th>
                    <th class="text-left px-4 py-4 text-xs font-semibold text-gray-500 uppercase">Motif</th>
                    <th class="text-left px-4 py-4 text-xs font-semibold text-gray-500 uppercase">Service</th>
                    <th class="text-left px-4 py-4 text-xs font-semibold text-gray-500 uppercase">Heure</th>
                    <th class="text-left px-4 py-4 text-xs font-semibold text-gray-500 uppercase">Statut</th>
                    <th class="text-left px-4 py-4 text-xs font-semibold text-gray-500 uppercase">Urgent</th>
                    <th class="text-right px-4 py-4 text-xs font-semibold text-gray-500 uppercase no-print">Actions</th>
                </tr>
            </thead>
            <tbody id="tableau-rdvs">
                <tr><td colspan="9" class="text-center py-16 text-gray-400">
                    <span class="text-4xl">⏳</span><p class="font-semibold mt-2">Chargement...</p>
                </td></tr>
            </tbody>
        </table>
    </div>
</section>

<!-- ─── SECTION FILE D'ATTENTE ─── -->
<section id="section-file" class="p-8 hidden">
    <div class="flex items-center justify-between mb-6">
        <div>
            <h2 class="text-xl font-black text-gray-900">🔢 File d'attente</h2>
            <p class="text-sm text-gray-400 mt-0.5">Gérez l'ordre de passage des patients</p>
        </div>
        <div class="flex items-center gap-3">
            <select id="file-filtre-service" onchange="chargerFile()"
                class="px-3 py-2 rounded-xl border-2 border-gray-100 bg-white text-sm font-semibold text-gray-600 focus:outline-none focus:border-blue-500">
                <option value="">Tous mes services</option>
            </select>
            <input type="date" id="file-date" onchange="chargerFile()"
                class="px-4 py-2 rounded-xl border-2 border-gray-100 bg-white text-sm font-semibold text-gray-600 focus:outline-none focus:border-blue-500" />
            <button onclick="chargerFile()" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl text-sm font-semibold text-gray-600">🔄</button>
        </div>
    </div>

    <!-- patient en cours -->
    <div id="file-en-cours-zone" class="mb-6 hidden">
        <div class="bg-purple-50 border-2 border-purple-200 rounded-2xl p-5">
            <div class="flex items-center justify-between flex-wrap gap-4">
                <div class="flex items-center gap-4">
                    <div class="w-14 h-14 rounded-2xl bg-purple-100 flex items-center justify-center">
                        <span class="text-2xl">🩺</span>
                    </div>
                    <div>
                        <p class="text-xs font-bold text-purple-400 uppercase tracking-wider mb-0.5">EN CONSULTATION</p>
                        <p id="file-en-cours-nom" class="text-xl font-black text-purple-900"></p>
                        <p id="file-en-cours-info" class="text-sm text-purple-600 font-semibold"></p>
                    </div>
                </div>
                <button id="btn-suivant-principal"
                    onclick="passerSuivantDepuisFile()"
                    class="flex items-center gap-2 px-6 py-3 bg-purple-600 hover:bg-purple-700 text-white font-bold rounded-xl text-base shadow-lg transition-all">
                    → Suivant
                </button>
            </div>
        </div>
    </div>

    <!-- liste file -->
    <div id="file-liste" class="space-y-3">
        <p class="text-gray-400 text-center py-12">Chargement de la file...</p>
    </div>
</section>

<!-- ─── SECTION CRÉER RDV ─── -->
<section id="section-creer-rdv" class="p-8 hidden">
    <div class="max-w-2xl">
        <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
            <div class="px-6 py-4 border-b border-blue-50 bg-blue-50">
                <h3 class="font-bold text-blue-900">➕ Créer un rendez-vous manuellement</h3>
                <p class="text-xs text-blue-600 mt-0.5">Le patient paiera directement sur place via QR code</p>
            </div>
            <div class="p-6 space-y-5">
                <div>
                    <p class="text-sm font-bold text-gray-700 mb-3">👤 Informations du patient</p>
                    <div class="grid grid-cols-2 gap-4">
                        <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Prénom *</label><input id="rdv-patient-prenom" type="text" placeholder="Aminata" class="w-full px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500" /></div>
                        <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Nom *</label><input id="rdv-patient-nom" type="text" placeholder="Diallo" class="w-full px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500" /></div>
                        <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Téléphone *</label><input id="rdv-patient-tel" type="tel" placeholder="771234567" class="w-full px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500" /></div>
                        <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Âge</label><input id="rdv-patient-age" type="number" placeholder="35" class="w-full px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500" /></div>
                    </div>
                </div>
                <div>
                    <p class="text-sm font-bold text-gray-700 mb-3">📅 Informations du RDV</p>
                    <div class="grid grid-cols-2 gap-4">
                        <div id="champ-service-rdv" class="col-span-2 hidden">
                            <label class="block text-sm font-semibold text-gray-600 mb-1.5">Service *</label>
                            <select id="rdv-service-id" class="w-full px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500">
                                <option value="">-- Choisir un service --</option>
                            </select>
                        </div>
                        <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Date *</label><input id="rdv-date" type="date" class="w-full px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500" /></div>
                        <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Heure *</label><input id="rdv-heure" type="time" class="w-full px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500" /></div>
                        <div class="col-span-2"><label class="block text-sm font-semibold text-gray-600 mb-1.5">Motif *</label><input id="rdv-motif" type="text" placeholder="Ex: Consultation prénatale..." class="w-full px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500" /></div>
                        <div class="col-span-2"><label class="block text-sm font-semibold text-gray-600 mb-1.5">Mode de paiement</label>
                            <select id="rdv-paiement" class="w-full px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500">
                                <option value="sur_place">Sur place (QR code à l'accueil)</option>
                                <option value="mobile_money">Mobile Money (SMS envoyé au patient)</option>
                                <option value="gratuit">Gratuit / Exonéré</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div id="rdv-cree-result" class="hidden bg-green-50 rounded-xl p-4 border border-green-200">
                    <p class="font-bold text-green-800 mb-2">✅ RDV créé avec succès !</p>
                    <div id="rdv-cree-details" class="text-sm text-green-700 space-y-1"></div>
                </div>
                <button onclick="creerRdvGerant()" class="w-full py-3 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-xl text-sm">✅ Créer et confirmer le RDV</button>
                <p class="text-xs text-gray-400 text-center">💡 Le RDV sera directement confirmé — le patient recevra un SMS</p>
            </div>
        </div>
    </div>
</section>

<!-- ─── SECTION PLAGE HORAIRE ─── -->
<section id="section-plage" class="p-8 hidden">
    <div class="max-w-2xl space-y-6">
        <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
            <div class="px-6 py-4 border-b border-blue-50 bg-blue-50">
                <h3 class="font-bold text-blue-900">🔓 Ouvrir une plage horaire</h3>
                <p class="text-xs text-blue-600 mt-0.5">Tout RDV pris dans cette période sera <strong>automatiquement confirmé</strong></p>
            </div>
            <div class="p-6 space-y-5">

                <div id="champ-service-plage" class="hidden">
                    <label class="block text-sm font-semibold text-gray-600 mb-1.5">Service *</label>
                    <select id="plage-service-id" onchange="onChangePlageService()"
                        class="w-full px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500">
                        <option value="">-- Choisir un service --</option>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-semibold text-gray-600 mb-2">📋 Mode de prise de RDV *</label>
                    <div class="grid grid-cols-2 gap-3">
                        <label id="toggle-creneaux-label"
                            class="mode-toggle-card cursor-pointer rounded-xl border-2 p-4 transition-all border-blue-500 bg-blue-50">
                            <input type="radio" name="plage-mode" value="creneaux" class="sr-only" checked onchange="onChangeModeRdv('creneaux')" />
                            <div class="flex items-start gap-3">
                                <span class="text-2xl mt-0.5">🕐</span>
                                <div>
                                    <p class="font-bold text-sm text-blue-900">Créneaux horaires</p>
                                    <p class="text-xs text-blue-600 mt-0.5 leading-relaxed">
                                        1 patient par créneau<br/>Ex : 9h00, 9h15, 9h30…
                                    </p>
                                </div>
                            </div>
                        </label>
                        <label id="toggle-quota-label"
                            class="mode-toggle-card cursor-pointer rounded-xl border-2 p-4 transition-all border-gray-200 bg-gray-50">
                            <input type="radio" name="plage-mode" value="quota" class="sr-only" onchange="onChangeModeRdv('quota')" />
                            <div class="flex items-start gap-3">
                                <span class="text-2xl mt-0.5">👥</span>
                                <div>
                                    <p class="font-bold text-sm text-gray-700">Quota journalier</p>
                                    <p class="text-xs text-gray-500 mt-0.5 leading-relaxed">
                                        N patients sur la journée<br/>Numéros de file N°1, N°2…
                                    </p>
                                </div>
                            </div>
                        </label>
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-semibold text-gray-600 mb-1.5">📅 Période</label>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs text-gray-400 mb-1">Date de début *</label>
                            <input type="date" id="plage-date-debut"
                                class="w-full px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500" />
                        </div>
                        <div>
                            <label class="block text-xs text-gray-400 mb-1">Date de fin *</label>
                            <input type="date" id="plage-date-fin"
                                class="w-full px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500" />
                        </div>
                    </div>
                    <p class="text-xs text-gray-400 mt-1.5">💡 Pour un seul jour, mettez la même date en début et fin</p>
                </div>

                <div>
                    <label class="block text-sm font-semibold text-gray-600 mb-1.5">⏰ Horaires</label>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs text-gray-400 mb-1">Heure de début *</label>
                            <input type="time" id="plage-debut"
                                class="w-full px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500" />
                        </div>
                        <div>
                            <label class="block text-xs text-gray-400 mb-1">Heure de fin *</label>
                            <input type="time" id="plage-fin"
                                class="w-full px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500" />
                        </div>
                    </div>
                </div>

                <div id="zone-duree-creneau">
                    <label class="block text-sm font-semibold text-gray-600 mb-1.5">⏱ Durée par créneau *</label>
                    <div class="grid grid-cols-3 gap-3">
                        <label class="duree-option"><input type="radio" name="duree" value="10" class="sr-only" /><div class="duree-card">10 min</div></label>
                        <label class="duree-option"><input type="radio" name="duree" value="15" class="sr-only" /><div class="duree-card">15 min</div></label>
                        <label class="duree-option"><input type="radio" name="duree" value="20" class="sr-only" /><div class="duree-card">20 min</div></label>
                        <label class="duree-option"><input type="radio" name="duree" value="30" class="sr-only" /><div class="duree-card duree-actif">30 min</div></label>
                        <label class="duree-option"><input type="radio" name="duree" value="45" class="sr-only" /><div class="duree-card">45 min</div></label>
                        <label class="duree-option"><input type="radio" name="duree" value="60" class="sr-only" /><div class="duree-card">1h</div></label>
                    </div>
                    <div id="apercu-creneaux" class="mt-3 hidden bg-blue-50 rounded-xl px-4 py-2 text-sm text-blue-700 font-semibold"></div>
                    <div class="mt-3 bg-amber-50 rounded-xl p-3 border border-amber-200">
                        <p class="text-xs text-amber-700">💡 <strong>Exemple :</strong> Du 01/04 au 30/04 de 08h à 12h, créneaux de 20 min → 12 créneaux/jour × 30 jours = 360 créneaux générés automatiquement.</p>
                    </div>
                </div>

                <div id="zone-quota-journalier" class="hidden">
                    <label class="block text-sm font-semibold text-gray-600 mb-1.5">
                        👥 Quota de patients pour cette plage *
                    </label>
                    <div class="flex items-center gap-3">
                        <input type="number" id="plage-quota" min="1" placeholder="Ex: 30"
                            class="flex-1 px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-purple-500" />
                        <span class="text-sm text-gray-400">patients/jour</span>
                    </div>
                    <p class="text-xs text-purple-600 mt-1.5 font-semibold">
                        💡 Ajustable à tout moment selon les directives du médecin
                    </p>
                    <div class="mt-3 bg-purple-50 rounded-xl p-3 border border-purple-200">
                        <p class="text-xs text-purple-700">💡 <strong>Exemple :</strong> Quota de 30 patients de 08h à 14h → les patients reçoivent un numéro de file N°1, N°2… sans créneau fixe.</p>
                    </div>
                </div>

                <div id="plage-resultat" class="hidden bg-green-50 rounded-xl p-4 border border-green-200">
                    <p class="font-bold text-green-800" id="plage-resultat-msg"></p>
                    <p class="text-xs text-green-600 mt-1">Les futurs RDVs dans cette plage seront confirmés automatiquement.</p>
                </div>

                <button onclick="ouvrirPlage()"
                    class="w-full py-3 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-xl text-sm transition-colors">
                    🔓 Ouvrir cette plage
                </button>
            </div>
        </div>

        <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-50 flex items-center justify-between flex-wrap gap-3">
                <h3 class="font-bold text-gray-900">📋 Plages ouvertes</h3>
                <div class="flex items-center gap-2">
                    <select id="filtre-plage-service" onchange="chargerPlages()"
                        class="px-3 py-1.5 rounded-xl border-2 border-gray-100 bg-white text-sm font-semibold text-gray-600 focus:outline-none focus:border-blue-500">
                        <option value="">Tous mes services</option>
                    </select>
                    <button onclick="chargerPlages()" class="px-3 py-1.5 bg-gray-100 text-gray-600 rounded-lg text-xs font-semibold hover:bg-gray-200">🔄</button>
                </div>
            </div>
            <div id="plages-liste" class="p-4">
                <p class="text-gray-400 text-center py-4 text-sm">Chargement...</p>
            </div>
        </div>
    </div>
</section>

<!-- ══ MODALE MODIFICATION QUOTA PLAGE ══ -->
<div id="modal-quota-plage" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl p-6 max-w-sm w-full shadow-2xl">
        <div class="flex items-center justify-between mb-4">
            <h3 class="font-black text-gray-900">👥 Modifier le quota</h3>
            <button onclick="document.getElementById('modal-quota-plage').classList.add('hidden')"
                class="w-8 h-8 rounded-lg bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-500 font-bold">✕</button>
        </div>
        <input type="hidden" id="quota-plage-id" />
        <p id="quota-plage-info" class="text-sm text-gray-500 mb-4"></p>
        <div>
            <label class="block text-sm font-semibold text-gray-600 mb-1.5">Nouveau quota *</label>
            <div class="flex items-center gap-3">
                <input type="number" id="quota-plage-valeur" min="1" placeholder="Ex: 30"
                    class="flex-1 px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-purple-500" />
                <span class="text-sm text-gray-400">patients/jour</span>
            </div>
            <p class="text-xs text-purple-600 mt-1.5">Sera aussi appliqué aux prochaines plages de ce service.</p>
        </div>
        <div class="flex gap-3 mt-5">
            <button onclick="document.getElementById('modal-quota-plage').classList.add('hidden')"
                class="flex-1 py-2.5 rounded-xl border-2 border-gray-200 text-gray-600 font-semibold">Annuler</button>
            <button onclick="sauvegarderQuotaPlage()"
                class="flex-1 py-2.5 rounded-xl bg-purple-600 text-white font-bold hover:bg-purple-700">💾 Enregistrer</button>
        </div>
    </div>
</div>

<!-- ─── SECTION CRÉNEAUX ─── -->
<section id="section-creneaux" class="p-8 hidden">
    <div class="max-w-2xl">
        <div class="flex items-center justify-between mb-4">
            <h2 class="text-lg font-bold text-gray-900">Mes créneaux horaires</h2>
            <div class="flex items-center gap-2">
                <select id="creneau-filtre-service" onchange="chargerCreneaux()"
                    class="px-3 py-2 rounded-xl border-2 border-gray-100 bg-white text-sm font-semibold text-gray-600 focus:outline-none focus:border-blue-500"></select>
                <button onclick="document.getElementById('form-creneau').classList.toggle('hidden')"
                    class="px-4 py-2 bg-blue-600 text-white rounded-xl text-sm font-semibold hover:bg-blue-700">+ Nouveau créneau</button>
            </div>
        </div>
        <div id="form-creneau" class="hidden bg-white rounded-2xl p-6 border border-gray-100 shadow-sm mb-6">
            <h3 class="font-bold text-gray-900 mb-4">Ajouter un créneau</h3>
            <div class="grid grid-cols-3 gap-4">
                <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Jour *</label>
                    <select id="creneau-jour" class="w-full px-3 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500">
                        <option value="1">Lundi</option><option value="2">Mardi</option><option value="3">Mercredi</option>
                        <option value="4">Jeudi</option><option value="5">Vendredi</option><option value="6">Samedi</option><option value="7">Dimanche</option>
                    </select>
                </div>
                <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Début *</label><input type="time" id="creneau-debut" class="w-full px-3 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500" /></div>
                <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Fin *</label><input type="time" id="creneau-fin" class="w-full px-3 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500" /></div>
            </div>
            <button onclick="creerCreneau()" class="mt-4 w-full bg-green-500 hover:bg-green-600 text-white font-bold py-2.5 rounded-xl text-sm">Créer le créneau →</button>
        </div>
        <div id="liste-creneaux" class="space-y-3">
            <p class="text-gray-400 text-center py-8">Chargement...</p>
        </div>
    </div>
</section>

<!-- ─── SECTION STATS ─── -->
<section id="section-stats" class="p-8 hidden">
    <div class="grid grid-cols-4 gap-4 mb-8" id="stats-cards">
        <div class="col-span-4 text-center py-8 text-gray-400">Chargement...</div>
    </div>
    <div class="bg-white rounded-2xl p-6 border border-gray-100">
        <h3 class="font-bold text-gray-900 mb-4">📊 Activité récente</h3>
        <div id="stats-detail" class="text-gray-400 text-center py-8">Chargement...</div>
    </div>
</section>

<!-- ─── SECTION PROFIL ─── -->
<section id="section-profil" class="p-8 hidden">
    <div class="max-w-2xl mx-auto" id="profil-content">
        <p class="text-gray-400 text-center py-8">Chargement...</p>
    </div>
</section>

</main>

<script src="/web/assets/app.js"></script>
<script>
let tousLesRdvs      = [];
let filtreActif      = 'tous';
let mesServices      = [];
let modeSelection    = false;
let rdvsSelectionnes = new Set();
let rdvEnCoursId     = null;

function onChangeModeRdv(mode) {
    const labelCreneaux = document.getElementById('toggle-creneaux-label');
    const labelQuota    = document.getElementById('toggle-quota-label');
    const zoneCreneaux  = document.getElementById('zone-duree-creneau');
    const zoneQuota     = document.getElementById('zone-quota-journalier');

    if (mode === 'creneaux') {
        labelCreneaux.classList.add('border-blue-500', 'bg-blue-50');
        labelCreneaux.classList.remove('border-gray-200', 'bg-gray-50');
        labelQuota.classList.add('border-gray-200', 'bg-gray-50');
        labelQuota.classList.remove('border-purple-500', 'bg-purple-50');
        zoneCreneaux.classList.remove('hidden');
        zoneQuota.classList.add('hidden');
    } else {
        labelQuota.classList.add('border-purple-500', 'bg-purple-50');
        labelQuota.classList.remove('border-gray-200', 'bg-gray-50');
        labelCreneaux.classList.add('border-gray-200', 'bg-gray-50');
        labelCreneaux.classList.remove('border-blue-500', 'bg-blue-50');
        zoneQuota.classList.remove('hidden');
        zoneCreneaux.classList.add('hidden');
    }
    mettreAJourApercu();
}

function getModeRdvSelectionne() {
    const checked = document.querySelector('input[name="plage-mode"]:checked');
    return checked ? checked.value : 'creneaux';
}

function getModeServiceActuel() {
    return getModeRdvSelectionne();
}

function adapterUIPlageAuMode(mode) {}

function onChangePlageService() {}

// ════════════════════════════════════
// INIT
// ════════════════════════════════════
window.addEventListener('DOMContentLoaded', async () => {
    const user = requireAuth(['gerant', 'admin_hopital']);
    if (!user) return;

    document.getElementById('user-nom').textContent = `${user.prenom} ${user.nom}`;
    await chargerMesServices();

    document.getElementById('filtre-date').value     = '';
    document.getElementById('file-date').value       = new Date().toISOString().split('T')[0];
    document.getElementById('page-date').textContent = new Date().toLocaleDateString('fr-FR', {
        weekday:'long', day:'numeric', month:'long', year:'numeric'
    });
    document.getElementById('rdv-date').value = new Date().toISOString().split('T')[0];

    const today = new Date().toISOString().split('T')[0];
    document.getElementById('plage-date-debut').value = today;
    document.getElementById('plage-date-fin').value   = today;

    document.querySelectorAll('.duree-option input[type=radio]').forEach(radio => {
        radio.addEventListener('change', () => {
            document.querySelectorAll('.duree-card').forEach(c => c.classList.remove('duree-actif'));
            radio.closest('.duree-option').querySelector('.duree-card').classList.add('duree-actif');
            mettreAJourApercu();
        });
    });
    ['plage-debut','plage-fin','plage-date-debut','plage-date-fin'].forEach(id => {
        document.getElementById(id)?.addEventListener('change', mettreAJourApercu);
    });

    await chargerRdvs();
    chargerPlages();
    chargerCreneaux();
});

// ════════════════════════════════════
// SERVICES + HÔPITAL
// ════════════════════════════════════
async function chargerMesServices() {
    const data = await api('/rdv/liste_gerant.php');
    if (!data.succes) return;

    mesServices = data.services || [];
    document.getElementById('user-hopital').textContent = `🏥 ${data.hopital_nom || 'Hôpital'}`;

    const badgesEl = document.getElementById('user-services-badges');
    badgesEl.innerHTML = mesServices.map(s =>
        `<span class="px-2 py-0.5 bg-white/20 text-white/90 rounded-full text-xs font-semibold">${s.service_nom}</span>`
    ).join('');

    const multiServices = mesServices.length > 1;
    const opts = mesServices.map(s => `<option value="${s.service_id}">${s.service_nom}</option>`).join('');

    const filtreSelect = document.getElementById('filtre-service-select');
    if (multiServices) {
        filtreSelect.innerHTML = '<option value="">Tous mes services</option>' + opts;
        document.getElementById('filtre-service-zone').classList.remove('hidden');
    }

    if (multiServices) {
        document.getElementById('rdv-service-id').innerHTML = '<option value="">-- Choisir un service --</option>' + opts;
        document.getElementById('champ-service-rdv').classList.remove('hidden');
    }

    const selectPlage = document.getElementById('plage-service-id');
    const filtrePlage = document.getElementById('filtre-plage-service');
    if (multiServices) {
        selectPlage.innerHTML = '<option value="">-- Choisir un service --</option>' + opts;
        filtrePlage.innerHTML = '<option value="">Tous mes services</option>' + opts;
        document.getElementById('champ-service-plage').classList.remove('hidden');
    } else if (mesServices.length === 1) {
        selectPlage.innerHTML = opts;
        filtrePlage.innerHTML = '<option value="">Tous mes services</option>' + opts;
    }

    const selectCreneau = document.getElementById('creneau-filtre-service');
    if (mesServices.length > 0) selectCreneau.innerHTML = opts;

    const fileSelect = document.getElementById('file-filtre-service');
    fileSelect.innerHTML = '<option value="">Tous mes services</option>' + opts;

    adapterUIPlageAuMode(getModeServiceActuel());
}

// ════════════════════════════════════
// APERÇU CRÉNEAUX
// ════════════════════════════════════
function getDureeSelectionnee() {
    const checked = document.querySelector('.duree-option input[type=radio]:checked');
    return checked ? parseInt(checked.value) : 30;
}
function mettreAJourApercu() {
    const debut = document.getElementById('plage-debut').value;
    const fin   = document.getElementById('plage-fin').value;
    const dateDebut = document.getElementById('plage-date-debut').value;
    const dateFin   = document.getElementById('plage-date-fin').value;
    const duree     = getDureeSelectionnee();
    const apercuEl  = document.getElementById('apercu-creneaux');
    if (!debut || !fin || debut >= fin) { apercuEl.classList.add('hidden'); return; }
    const [hD,mD] = debut.split(':').map(Number);
    const [hF,mF] = fin.split(':').map(Number);
    const creneauxParJour = Math.floor(((hF*60+mF)-(hD*60+mD))/duree);
    let nbJours = 1;
    if (dateDebut && dateFin && dateDebut <= dateFin) {
        nbJours = Math.round((new Date(dateFin)-new Date(dateDebut))/(1000*60*60*24))+1;
    }
    apercuEl.textContent = `📊 ${creneauxParJour} créneau(x)/jour × ${nbJours} jour(s) = ${creneauxParJour*nbJours} créneaux générés`;
    apercuEl.classList.remove('hidden');
}

// ════════════════════════════════════
// RDVs
// ════════════════════════════════════
async function chargerRdvs() {
    const date      = document.getElementById('filtre-date').value;
    const serviceId = document.getElementById('filtre-service-select')?.value || '';
    let url = '/rdv/liste_gerant.php';
    const params = [];
    if (date)      params.push(`date=${date}`);
    if (serviceId) params.push(`service_id=${serviceId}`);
    if (params.length) url += '?' + params.join('&');
    const data = await api(url);
    if (data.succes) {
        tousLesRdvs = data.rdvs;
        afficherStats(data.stats);
        filtrerRdvs(filtreActif);
    }
}

function afficherStats(stats) {
    document.getElementById('stats-badges').innerHTML = `
        <span class="px-3 py-1.5 bg-amber-100 text-amber-700 rounded-lg text-xs font-bold">⏳ ${stats.en_attente||0}</span>
        <span class="px-3 py-1.5 bg-blue-100 text-blue-700 rounded-lg text-xs font-bold">✅ ${stats.confirme||0}</span>
        <span class="px-3 py-1.5 bg-green-100 text-green-700 rounded-lg text-xs font-bold">🎫 ${stats.paye||0}</span>`;
}

function filtrerRdvs(statut) {
    filtreActif = statut;
    document.querySelectorAll('.filtre-btn').forEach(b => b.classList.remove('filtre-actif'));
    document.getElementById(`filtre-${statut}`)?.classList.add('filtre-actif');
    const rdvs = statut === 'tous' ? tousLesRdvs : tousLesRdvs.filter(r => r.statut === statut);
    rdvsSelectionnes.clear();
    afficherTableau(rdvs);
}

function afficherTableau(rdvs) {
    const tbody = document.getElementById('tableau-rdvs');
    if (!rdvs.length) {
        tbody.innerHTML = `<tr><td colspan="9" class="text-center py-16 text-gray-400">
            <span class="text-4xl">📭</span><p class="font-semibold mt-2">Aucun rendez-vous dans cette catégorie</p>
        </td></tr>`;
        return;
    }
    tbody.innerHTML = rdvs.map((rdv, i) => {
        const enCours = rdv.statut_file === 'en_cours';
        const estUrgent = parseInt(rdv.urgent) === 1;
        const rowClass = enCours ? 'en-cours-row' : (estUrgent ? 'urgent-row' : '');
        return `
        <tr class="border-b border-gray-50 hover:bg-gray-50/50 ${rowClass}">
            <td class="px-4 py-4">
                ${modeSelection && rdv.statut === 'en_attente'
                    ? `<input type="checkbox" class="rdv-checkbox w-4 h-4 rounded text-blue-600 cursor-pointer"
                        onchange="toggleRdvSelection(${rdv.id}, this.checked)"
                        ${rdvsSelectionnes.has(rdv.id) ? 'checked' : ''} />`
                    : `<span class="text-sm text-gray-400">${i+1}</span>`}
            </td>
            <td class="px-4 py-4">
                ${rdv.numero_file
                    ? `<span class="inline-flex items-center justify-center w-8 h-8 rounded-full text-xs font-black
                        ${enCours ? 'bg-purple-100 text-purple-700 ring-2 ring-purple-400' : (estUrgent ? 'bg-red-100 text-red-700 ring-2 ring-red-400' : 'bg-gray-100 text-gray-600')}">
                        ${rdv.numero_file}
                       </span>`
                    : '<span class="text-gray-300">—</span>'}
            </td>
            <td class="px-4 py-4">
                <div class="flex items-center gap-2">
                    ${enCours ? '<span class="w-2 h-2 rounded-full bg-purple-500 animate-pulse inline-block"></span>' : ''}
                    ${estUrgent && !enCours ? '<span class="text-red-500">🔴</span>' : ''}
                    <div>
                        <p class="font-semibold text-gray-900 text-sm">${rdv.patient_prenom} ${rdv.patient_nom}</p>
                        ${rdv.patient_age ? `<p class="text-xs text-gray-400">${rdv.patient_age} ans</p>` : ''}
                        ${enCours ? '<p class="text-xs text-purple-600 font-bold">🩺 En consultation</p>' : ''}
                        ${estUrgent && !enCours ? '<p class="text-xs text-red-600 font-bold">🔴 URGENT</p>' : ''}
                    </div>
                </div>
            </td>
            <td class="px-4 py-4 text-sm text-gray-600 max-w-xs">
                <p class="truncate">${rdv.motif}</p>
            </td>
            <td class="px-4 py-4">
                <span class="text-xs font-semibold text-gray-500 bg-gray-100 px-2 py-1 rounded-lg">${rdv.service_nom||'—'}</span>
            </td>
            <td class="px-4 py-4">
                <span class="text-blue-600 font-bold text-base">${formatHeure(rdv.heure_rdv)}</span>
            </td>
            <td class="px-4 py-4">${statutBadge(rdv.statut)}</td>
            <td class="px-4 py-4">
                <button onclick="toggleUrgent(${rdv.id})"
                    class="px-3 py-1.5 rounded-lg text-xs font-bold transition-all
                    ${estUrgent
                        ? 'bg-red-100 text-red-700 hover:bg-red-200 border border-red-300'
                        : 'bg-gray-100 text-gray-400 hover:bg-red-50 hover:text-red-500 border border-gray-200'}">
                    ${estUrgent ? '🔴 Urgent' : 'Marquer urgent'}
                </button>
            </td>
            <td class="px-4 py-4 no-print">
                <div class="flex items-center justify-end gap-2 flex-wrap">
                    ${!modeSelection && rdv.statut === 'en_attente' ? `
                        <button onclick="confirmerRdv(${rdv.id})" class="px-3 py-1.5 bg-green-500 hover:bg-green-600 text-white text-xs font-bold rounded-lg">✓ Confirmer</button>
                        <button onclick="ouvrirModalReport(${rdv.id})" class="px-3 py-1.5 bg-amber-100 hover:bg-amber-200 text-amber-700 text-xs font-bold rounded-lg">↻ Reporter</button>
                        <button onclick="annulerRdv(${rdv.id})" class="px-3 py-1.5 bg-red-100 hover:bg-red-200 text-red-600 text-xs font-bold rounded-lg">✕</button>
                    ` : ''}
                    ${rdv.statut === 'paye' && !enCours ? `
                        <button onclick="appelerPatient(${rdv.id}, '${rdv.patient_nom}', '${rdv.patient_prenom}', ${rdv.numero_file||0})"
                            class="flex items-center gap-1 px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold rounded-lg">
                            ▶ Appeler
                        </button>
                    ` : ''}
                    ${enCours ? `
                        <button onclick="passerSuivant(${rdv.id}, '${rdv.patient_nom}', '${rdv.patient_prenom}', ${rdv.numero_file||0})"
                            class="flex items-center gap-1 px-4 py-1.5 bg-purple-600 hover:bg-purple-700 text-white text-xs font-black rounded-lg shadow">
                            → Suivant
                        </button>
                        <button onclick="marquerAbsent(${rdv.id}, '${rdv.patient_nom}', '${rdv.patient_prenom}', ${rdv.numero_file||0})"
                            class="flex items-center gap-1 px-3 py-1.5 bg-orange-50 hover:bg-orange-100 text-orange-600 text-xs font-bold rounded-lg border border-orange-200">
                            ⏳ Absent
                        </button>
                    ` : ''}
                    ${rdv.statut === 'paye' && rdv.code_qr ? `<span class="text-xs text-green-600 font-mono font-bold">${rdv.code_qr}</span>` : ''}
                </div>
            </td>
        </tr>`;
    }).join('');
    majLabelSelection();
}

// ════════════════════════════════════
// TOGGLE URGENT
// ════════════════════════════════════
async function toggleUrgent(rdvId) {
    const data = await api('/rdv/confirmer.php', {
        method: 'POST',
        body: JSON.stringify({ rdv_id: rdvId, action: 'toggle_urgent' })
    });
    if (data.succes) {
        toast(data.message);
        chargerRdvs();
        chargerFile();
    } else {
        toast(data.erreur || 'Erreur', 'error');
    }
}

// ════════════════════════════════════
// FILE D'ATTENTE
// ════════════════════════════════════

async function chargerFile() {
    const date      = document.getElementById('file-date').value || new Date().toISOString().split('T')[0];
    const serviceId = document.getElementById('file-filtre-service').value;
    let url = `/rdv/liste_gerant.php?date=${date}`;
    if (serviceId) url += `&service_id=${serviceId}`;

    const data = await api(url);
    if (!data.succes) return;

    const rdvs = (data.rdvs || [])
        .filter(function(r) { return r.statut !== 'annule' && r.statut !== 'expire'; })
        .sort(function(a, b) {
            if ((a.urgent?1:0) !== (b.urgent?1:0)) return (b.urgent?1:0) - (a.urgent?1:0);
            return (a.numero_file||0) - (b.numero_file||0);
        });

    const enCours = rdvs.find(function(r) { return r.statut_file === 'en_cours'; });
    rdvEnCoursId  = enCours ? enCours.id : null;

    const zoneEnCours = document.getElementById('file-en-cours-zone');
    if (enCours) {
        document.getElementById('file-en-cours-nom').textContent  = `${enCours.patient_prenom} ${enCours.patient_nom}`;
        document.getElementById('file-en-cours-info').textContent = `N°${enCours.numero_file} · ${enCours.service_nom||''} · ${formatHeure(enCours.heure_rdv)}`;
        zoneEnCours.classList.remove('hidden');
    } else {
        zoneEnCours.classList.add('hidden');
    }

    const container = document.getElementById('file-liste');
    if (!rdvs.length) {
        container.innerHTML = '<p class="text-gray-400 text-center py-12 text-sm">Aucun patient dans la file pour ce jour</p>';
        return;
    }

    const STATUT_FILE = {
        en_attente: { label: 'En attente',      bg: 'bg-gray-50',   border: 'border-gray-200',   dot: 'bg-gray-400'   },
        en_cours:   { label: 'En consultation', bg: 'bg-purple-50', border: 'border-purple-300', dot: 'bg-purple-500' },
        termine:    { label: 'Terminé',         bg: 'bg-green-50',  border: 'border-green-200',  dot: 'bg-green-400'  },
    };

    container.innerHTML = rdvs.map(function(rdv) {
        const sf      = STATUT_FILE[rdv.statut_file || 'en_attente'];
        const enCours = rdv.statut_file === 'en_cours';
        const termine = rdv.statut_file === 'termine' || rdv.statut === 'consomme';
        const estUrgent = parseInt(rdv.urgent) === 1;
        const bgClass = estUrgent && !enCours && !termine ? 'bg-red-50' : sf.bg;
        const borderClass = estUrgent && !enCours && !termine ? 'border-red-300' : sf.border;

        return `
        <div class="flex items-center gap-4 p-4 rounded-2xl border-2 ${bgClass} ${borderClass} ${enCours ? 'shadow-md' : ''} ${estUrgent && !enCours && !termine ? 'shadow-red-100 shadow-md' : ''}">
            <div class="w-12 h-12 rounded-2xl flex items-center justify-center flex-shrink-0
                ${enCours ? 'bg-purple-600 text-white shadow-lg' : termine ? 'bg-green-100 text-green-600' : estUrgent ? 'bg-red-600 text-white shadow-lg' : 'bg-white text-gray-700 border-2 border-gray-200'}">
                <span class="text-lg font-black">${rdv.numero_file||'?'}</span>
            </div>
            <div class="flex-1 min-w-0">
                <div class="flex items-center gap-2 flex-wrap">
                    <p class="font-bold text-gray-900">${rdv.patient_prenom} ${rdv.patient_nom}</p>
                    ${estUrgent && !termine ? '<span class="px-2 py-0.5 bg-red-600 text-white text-xs font-bold rounded-full">🔴 URGENT</span>' : ''}
                    ${enCours ? '<span class="px-2 py-0.5 bg-purple-600 text-white text-xs font-bold rounded-full">🩺 En cours</span>' : ''}
                    ${termine ? '<span class="px-2 py-0.5 bg-green-100 text-green-700 text-xs font-bold rounded-full">✔ Terminé</span>' : ''}
                    ${rdv.prioritaire==1 ? '<span class="text-amber-500 text-xs font-bold">⭐ Prioritaire</span>' : ''}
                </div>
                <p class="text-sm text-gray-500 mt-0.5">${rdv.motif || 'Consultation'} · ${rdv.service_nom||''}</p>
                <p class="text-xs text-gray-400">${formatHeure(rdv.heure_rdv)} · ${statutBadge(rdv.statut)}</p>
            </div>
            <div class="flex-shrink-0 flex gap-2">
                ${rdv.statut === 'paye' && !enCours && !termine ? `
                    <button onclick="appelerPatient(${rdv.id}, '${rdv.patient_nom}', '${rdv.patient_prenom}', ${rdv.numero_file||0})"
                        class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-bold rounded-xl">
                        ▶ Appeler
                    </button>
                ` : ''}
                ${enCours ? `
                    <div class="flex gap-2">
                        <button onclick="passerSuivant(${rdv.id}, '${rdv.patient_nom}', '${rdv.patient_prenom}', ${rdv.numero_file||0})"
                            class="px-5 py-2 bg-purple-600 hover:bg-purple-700 text-white text-sm font-black rounded-xl shadow-md">
                            → Suivant
                        </button>
                        <button onclick="marquerAbsent(${rdv.id}, '${rdv.patient_nom}', '${rdv.patient_prenom}', ${rdv.numero_file||0})"
                            class="px-3 py-2 bg-orange-50 hover:bg-orange-100 text-orange-600 text-sm font-bold rounded-xl border border-orange-200">
                            ⏳ Absent
                        </button>
                    </div>
                ` : ''}
                ${termine ? '<span class="text-2xl">✅</span>' : ''}
            </div>
        </div>`;
    }).join('');
}

async function passerSuivantDepuisFile() {
    if (!rdvEnCoursId) { toast('Aucun patient en cours', 'error'); return; }
    const rdv = tousLesRdvs.find(function(r) { return r.id == rdvEnCoursId; }) || { patient_nom:'?', patient_prenom:'', numero_file:0 };
    passerSuivant(rdvEnCoursId, rdv.patient_nom, rdv.patient_prenom, rdv.numero_file);
}

// ════════════════════════════════════
// ACTIONS FILE D'ATTENTE
// ════════════════════════════════════
async function appelerPatient(rdvId, nom, prenom, numeroFile) {
    confirmerAction(`▶ Appeler ${prenom} ${nom} (N°${numeroFile}) en consultation ?`, async function() {
        const data = await api('/rdv/confirmer.php', {
            method: 'POST',
            body: JSON.stringify({ rdv_id: rdvId, action: 'appeler' })
        });
        if (data.succes) {
            toast(`✅ ${prenom} ${nom} appelé(e) en consultation`);
            chargerRdvs();
            chargerFile();
        } else {
            toast(data.erreur || 'Erreur', 'error');
        }
    });
}

async function passerSuivant(rdvId, nom, prenom, numeroFile) {
    confirmerAction(`→ Terminer la consultation de ${prenom} ${nom} (N°${numeroFile}) et appeler le suivant ?`, async function() {
        const data = await api('/rdv/confirmer.php', {
            method: 'POST',
            body: JSON.stringify({ rdv_id: rdvId, action: 'suivant' })
        });
        if (data.succes) {
            const msg = data.suivant
                ? `✅ Patient suivant notifié : ${data.suivant.prenom} ${data.suivant.nom} (N°${data.suivant.numero_file})`
                : '✅ Consultation terminée — plus de patients en file.';
            toast(msg);
            chargerRdvs();
            chargerFile();
        } else {
            toast(data.erreur || 'Erreur', 'error');
        }
    });
}

async function marquerAbsent(rdvId, nom, prenom, numeroFile) {
    const finDeFile = confirm(
        `⏳ ${prenom} ${nom} (N°${numeroFile}) ne s'est pas présenté.\n\nCliquez OK pour remettre en fin de file.\nCliquez Annuler pour annuler définitivement le RDV.`
    );

    if (finDeFile) {
        const data = await api('/rdv/confirmer.php', {
            method: 'POST',
            body: JSON.stringify({ rdv_id: rdvId, action: 'absent' })
        });
        if (data.succes) {
            const msg = data.suivant
                ? `✅ ${prenom} ${nom} remis en N°${data.nouveau_numero}.\nPatient suivant appelé : ${data.suivant.prenom} ${data.suivant.nom} (N°${data.suivant.numero_file})`
                : `✅ ${prenom} ${nom} remis en N°${data.nouveau_numero}.`;
            toast(msg);
            chargerRdvs();
            chargerFile();
        } else {
            toast(data.erreur || 'Erreur', 'error');
        }
    } else {
        confirmerAction(
            `❌ Annuler définitivement le RDV de ${prenom} ${nom} ? Le patient sera notifié.`,
            async function() {
                const data = await api('/rdv/annuler.php', {
                    method: 'POST',
                    body: JSON.stringify({ rdv_id: rdvId, raison: 'Patient absent — annulé par le gérant' })
                });
                if (data.succes) { toast('RDV annulé'); chargerRdvs(); chargerFile(); }
                else toast(data.erreur || 'Erreur', 'error');
            }
        );
    }
}

// ════════════════════════════════════
// SÉLECTION MULTIPLE
// ════════════════════════════════════
function activerModeSelection() {
    modeSelection = true; rdvsSelectionnes.clear();
    document.getElementById('barre-masse').classList.remove('hidden');
    document.getElementById('btn-mode-selection').classList.add('hidden');
    filtreActif = 'en_attente'; filtrerRdvs('en_attente');
    toast('Mode sélection activé — cochez les RDVs à confirmer');
}
function annulerBarre() {
    modeSelection = false; rdvsSelectionnes.clear();
    document.getElementById('barre-masse').classList.add('hidden');
    document.getElementById('btn-mode-selection').classList.remove('hidden');
    document.getElementById('select-all-rdvs').checked = false;
    filtrerRdvs(filtreActif);
}
function toggleSelectAll(checked) {
    const rdvsEnAttente = tousLesRdvs.filter(function(r) { return r.statut === 'en_attente'; });
    rdvsSelectionnes.clear();
    if (checked) rdvsEnAttente.forEach(function(r) { rdvsSelectionnes.add(r.id); });
    document.querySelectorAll('.rdv-checkbox').forEach(function(cb) { cb.checked = checked; });
    majLabelSelection();
}
function toggleRdvSelection(rdvId, checked) {
    if (checked) rdvsSelectionnes.add(rdvId); else rdvsSelectionnes.delete(rdvId);
    majLabelSelection();
    const rdvsEnAttente = tousLesRdvs.filter(function(r) { return r.statut === 'en_attente'; });
    document.getElementById('select-all-rdvs').checked = rdvsSelectionnes.size === rdvsEnAttente.length && rdvsEnAttente.length > 0;
}
function majLabelSelection() {
    document.getElementById('selection-label').textContent = `${rdvsSelectionnes.size} RDV sélectionné(s)`;
}
async function confirmerSelectionnes() {
    if (rdvsSelectionnes.size === 0) { toast('Sélectionnez au moins un RDV', 'error'); return; }
    confirmerAction(`Confirmer ${rdvsSelectionnes.size} RDV(s) ? Les patients seront notifiés.`, async function() {
        const data = await api('/rdv/confirmer_masse.php', { method:'POST', body: JSON.stringify({ rdv_ids: Array.from(rdvsSelectionnes) }) });
        if (data.succes) { toast(`✅ ${data.confirmes} RDV(s) confirmé(s)`); annulerBarre(); chargerRdvs(); }
        else toast(data.erreur||'Erreur', 'error');
    });
}

// ════════════════════════════════════
// ACTIONS RDV UNITAIRES
// ════════════════════════════════════
async function confirmerRdv(rdvId) {
    confirmerAction('Confirmer ce RDV et notifier le patient ?', async function() {
        const data = await api('/rdv/confirmer.php', { method:'POST', body: JSON.stringify({ rdv_id: rdvId, action:'confirmer' }) });
        if (data.succes) { toast('✅ RDV confirmé'); chargerRdvs(); } else toast(data.erreur||'Erreur', 'error');
    });
}
function ouvrirModalReport(rdvId) {
    document.getElementById('report-rdv-id').value = rdvId;
    document.getElementById('report-date').value   = new Date().toISOString().split('T')[0];
    document.getElementById('modal-report').classList.remove('hidden');
}
async function envoyerReport() {
    const rdvId = document.getElementById('report-rdv-id').value;
    const date  = document.getElementById('report-date').value;
    const heure = document.getElementById('report-heure').value;
    if (!date||!heure) { toast('Date et heure obligatoires', 'error'); return; }
    const data = await api('/rdv/confirmer.php', { method:'POST', body: JSON.stringify({ rdv_id:rdvId, action:'proposer_report', date_proposee:date, heure_proposee:heure }) });
    document.getElementById('modal-report').classList.add('hidden');
    if (data.succes) { toast('↻ Report envoyé'); chargerRdvs(); } else toast(data.erreur||'Erreur', 'error');
}
async function annulerRdv(rdvId) {
    confirmerAction('Annuler ce RDV ? Le patient sera notifié.', async function() {
        const data = await api('/rdv/annuler.php', { method:'POST', body: JSON.stringify({ rdv_id: rdvId, raison:'Annulé par le service' }) });
        if (data.succes) { toast('RDV annulé'); chargerRdvs(); } else toast(data.erreur||'Erreur', 'error');
    });
}

// ════════════════════════════════════
// CRÉER RDV MANUELLEMENT
// ════════════════════════════════════
async function creerRdvGerant() {
    const prenom = document.getElementById('rdv-patient-prenom').value.trim();
    const nom    = document.getElementById('rdv-patient-nom').value.trim();
    const tel    = document.getElementById('rdv-patient-tel').value.trim();
    const date   = document.getElementById('rdv-date').value;
    const heure  = document.getElementById('rdv-heure').value;
    const motif  = document.getElementById('rdv-motif').value.trim();
    if (!prenom||!nom||!tel||!date||!heure||!motif) { toast('Tous les champs obligatoires', 'error'); return; }
    let serviceId = document.getElementById('rdv-service-id').value;
    if (!serviceId && mesServices.length === 1) serviceId = mesServices[0].service_id;
    if (!serviceId) { toast('Sélectionnez un service', 'error'); return; }
    const data = await api('/rdv/creer_gerant.php', {
        method: 'POST',
        body: JSON.stringify({ patient_prenom:prenom, patient_nom:nom, patient_telephone:tel, patient_age:document.getElementById('rdv-patient-age').value||null, service_id:serviceId, date_rdv:date, heure_rdv:heure, motif, mode_paiement:document.getElementById('rdv-paiement').value })
    });
    if (data.succes) {
        toast('✅ RDV créé et confirmé !');
        document.getElementById('rdv-cree-result').classList.remove('hidden');
        document.getElementById('rdv-cree-details').innerHTML = `<p>👤 <strong>${prenom} ${nom}</strong> · 📞 ${tel}</p><p>📅 ${date} à ${heure}</p><p>🎫 Code : <strong class="font-mono">${data.code_qr||'—'}</strong></p>`;
        setTimeout(function() {
            ['rdv-patient-prenom','rdv-patient-nom','rdv-patient-tel','rdv-patient-age','rdv-motif'].forEach(function(id) { document.getElementById(id).value=''; });
            document.getElementById('rdv-cree-result').classList.add('hidden');
        }, 5000);
        chargerRdvs();
    } else toast(data.erreur||'Erreur création RDV', 'error');
}

// ════════════════════════════════════
// PLAGE HORAIRE
// ════════════════════════════════════
async function ouvrirPlage() {
    const dateDebut = document.getElementById('plage-date-debut').value;
    const dateFin   = document.getElementById('plage-date-fin').value;
    const debut     = document.getElementById('plage-debut').value;
    const fin       = document.getElementById('plage-fin').value;
    const modeRdv   = getModeRdvSelectionne();

    if (!dateDebut || !dateFin || !debut || !fin) { toast('Tous les champs sont obligatoires', 'error'); return; }
    if (dateDebut > dateFin)  { toast('Date début doit être avant date fin', 'error'); return; }
    if (debut >= fin)         { toast("L'heure de fin doit être après l'heure de début", 'error'); return; }

    let serviceId = document.getElementById('plage-service-id').value;
    if (!serviceId && mesServices.length === 1) serviceId = mesServices[0].service_id;
    if (!serviceId) { toast('Sélectionnez un service', 'error'); return; }

    const body = {
        service_id:  serviceId,
        date_debut:  dateDebut,
        date_fin:    dateFin,
        heure_debut: debut,
        heure_fin:   fin,
        mode_rdv:    modeRdv,
    };

    if (modeRdv === 'creneaux') {
        body.duree_minutes = getDureeSelectionnee();
    } else {
        const quota = parseInt(document.getElementById('plage-quota').value);
        if (!quota || quota < 1) { toast('Entrez un quota valide (≥ 1)', 'error'); return; }
        body.quota = quota;
    }

    const data = await api('/rdv/plages.php', {
        method: 'POST',
        body: JSON.stringify(body)
    });

    if (data.succes) {
        document.getElementById('plage-resultat-msg').textContent = data.message;
        document.getElementById('plage-resultat').classList.remove('hidden');
        setTimeout(function() { document.getElementById('plage-resultat').classList.add('hidden'); }, 8000);
        chargerPlages();
        chargerRdvs();
    } else {
        toast(data.erreur || 'Erreur', 'error');
    }
}

async function chargerPlages() {
    const serviceId = document.getElementById('filtre-plage-service')?.value||'';
    const data = await api('/rdv/plages.php' + (serviceId ? `?service_id=${serviceId}` : ''));
    const el   = document.getElementById('plages-liste');
    if (!data.succes||!data.plages.length) { el.innerHTML='<p class="text-gray-400 text-center py-4 text-sm">Aucune plage ouverte</p>'; return; }
    el.innerHTML = data.plages.map(function(p) { return `
        <div class="flex items-center gap-4 py-3 border-b border-gray-50 last:border-0">
            <div class="w-10 h-10 rounded-xl bg-blue-50 flex items-center justify-center flex-shrink-0"><span class="text-lg">🔓</span></div>
            <div class="flex-1">
                <div class="flex items-center gap-2">
                    <p class="font-bold text-gray-900 text-sm">📅 ${p.date_plage}</p>
                    <span class="text-xs font-semibold text-gray-400 bg-gray-100 px-2 py-0.5 rounded-full">${p.service_nom}</span>
                    ${p.duree_creneau ? `<span class="text-xs font-semibold text-blue-400 bg-blue-50 px-2 py-0.5 rounded-full">⏱ ${p.duree_creneau} min</span>` : ''}
                </div>
                <p class="text-blue-600 font-semibold text-sm">${p.heure_debut.slice(0,5)} → ${p.heure_fin.slice(0,5)}</p>
                <p class="text-xs text-gray-400 mt-0.5">Ouverte par ${p.gerant_prenom} ${p.gerant_nom}</p>
            </div>
            <div class="flex items-center gap-2">
                <span class="px-2.5 py-1 bg-green-100 text-green-700 rounded-full text-xs font-bold">✅ Active</span>
                <button onclick="fermerPlage(${p.id})" class="px-3 py-1.5 bg-red-50 text-red-500 hover:bg-red-100 rounded-lg text-xs font-bold">🔒 Fermer</button>
            </div>
        </div>`; }).join('');
}
async function fermerPlage(id) {
    confirmerAction('Fermer cette plage ?', async function() {
        const data = await api('/rdv/plages.php', { method:'DELETE', body: JSON.stringify({id}) });
        if (data.succes) { toast('Plage fermée'); chargerPlages(); } else toast(data.erreur||'Erreur','error');
    });
}

// ════════════════════════════════════
// CRÉNEAUX
// ════════════════════════════════════
async function chargerCreneaux() {
    const serviceId = document.getElementById('creneau-filtre-service')?.value;
    if (!serviceId) return;
    const data = await api(`/admin/creneaux.php?service_id=${serviceId}`);
    const container = document.getElementById('liste-creneaux');
    const jours = {'1':'Lundi','2':'Mardi','3':'Mercredi','4':'Jeudi','5':'Vendredi','6':'Samedi','7':'Dimanche'};
    if (!data.succes||!data.creneaux.length) { container.innerHTML='<p class="text-gray-400 text-center py-8">Aucun créneau configuré</p>'; return; }
    container.innerHTML = data.creneaux.map(function(c) { return `
        <div class="bg-white rounded-xl p-4 border border-gray-100 flex items-center justify-between">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-blue-50 flex items-center justify-center text-blue-600 font-bold">🕐</div>
                <div>
                    <p class="font-semibold text-gray-900 text-sm">${c.jour_label||jours[c.jour_semaine]||''}</p>
                    <p class="text-blue-600 font-bold">${formatHeure(c.heure_debut)} → ${formatHeure(c.heure_fin)}</p>
                </div>
            </div>
            <div class="flex items-center gap-2">
                <span class="px-2.5 py-1 rounded-full text-xs font-semibold ${c.disponible==1?'bg-green-100 text-green-700':'bg-red-100 text-red-600'}">${c.disponible==1?'Actif':'Bloqué'}</span>
                <button onclick="toggleCreneau(${c.id},${c.disponible==1?0:1})"
                    class="px-3 py-1.5 rounded-lg text-xs font-semibold ${c.disponible==1?'bg-red-50 text-red-500 hover:bg-red-100':'bg-green-50 text-green-600 hover:bg-green-100'}">
                    ${c.disponible==1?'🔒 Bloquer':'🔓 Activer'}
                </button>
            </div>
        </div>`; }).join('');
}
async function creerCreneau() {
    const serviceId = document.getElementById('creneau-filtre-service')?.value;
    if (!serviceId) { toast('Sélectionnez un service','error'); return; }
    const data = await api('/admin/creneaux.php', { method:'POST', body: JSON.stringify({ service_id:serviceId, jour_semaine:document.getElementById('creneau-jour').value, heure_debut:document.getElementById('creneau-debut').value, heure_fin:document.getElementById('creneau-fin').value }) });
    if (data.succes) { toast('✅ Créneau créé'); document.getElementById('form-creneau').classList.add('hidden'); chargerCreneaux(); }
    else toast(data.erreur||'Erreur','error');
}
async function toggleCreneau(id, disponible) {
    const data = await api('/admin/creneaux.php', { method:'PUT', body: JSON.stringify({id,disponible}) });
    if (data.succes) { toast(disponible?'🔓 Activé':'🔒 Bloqué'); chargerCreneaux(); }
}

// ════════════════════════════════════
// STATS
// ════════════════════════════════════
async function chargerStats() {
    const data = await api('/rdv/liste_gerant.php');
    if (!data.succes) return;
    const s = data.stats;
    document.getElementById('stats-cards').innerHTML = `
        <div class="bg-white rounded-2xl p-6 border border-gray-100 border-t-4 border-t-amber-400"><p class="text-sm text-gray-500 mb-1">En attente</p><p class="text-3xl font-black text-amber-500">${s.en_attente||0}</p></div>
        <div class="bg-white rounded-2xl p-6 border border-gray-100 border-t-4 border-t-blue-500"><p class="text-sm text-gray-500 mb-1">Confirmés</p><p class="text-3xl font-black text-blue-600">${s.confirme||0}</p></div>
        <div class="bg-white rounded-2xl p-6 border border-gray-100 border-t-4 border-t-green-500"><p class="text-sm text-gray-500 mb-1">Payés</p><p class="text-3xl font-black text-green-600">${s.paye||0}</p></div>
        <div class="bg-white rounded-2xl p-6 border border-gray-100 border-t-4 border-t-gray-400"><p class="text-sm text-gray-500 mb-1">Terminés</p><p class="text-3xl font-black text-gray-600">${s.consomme||0}</p></div>`;
    document.getElementById('stats-detail').innerHTML = `<p class="text-gray-600">Total RDVs : <strong>${data.total||0}</strong></p>`;
}

// ════════════════════════════════════
// NAVIGATION
// ════════════════════════════════════
function afficherSection(section) {
    ['rdvs','file','creer-rdv','plage','creneaux','stats','profil'].forEach(function(s) {
        document.getElementById(`section-${s}`)?.classList.add('hidden');
    });
    document.getElementById(`section-${section}`)?.classList.remove('hidden');
    const titres = { rdvs:'Rendez-vous du jour', file:'File d\'attente', 'creer-rdv':'Créer un rendez-vous', plage:'Ouvrir une plage horaire', creneaux:'Mes créneaux horaires', stats:'Mes statistiques', profil:'Mon profil' };
    document.getElementById('page-titre').textContent = titres[section]||'';
    if (section === 'profil') afficherProfilSection();
    if (section === 'stats')  chargerStats();
    if (section === 'plage')  chargerPlages();
    if (section === 'file')   chargerFile();
}

// ════════════════════════════════════
// PROFIL + IMPRESSION
// ════════════════════════════════════
function imprimerListe() {
    const date = document.getElementById('filtre-date').value || 'Toutes dates';
    document.getElementById('print-titre').textContent = `Liste RDVs — ${filtreActif==='tous'?'Tous statuts':filtreActif}`;
    document.getElementById('print-date').textContent  = `Date : ${date} · Généré le ${new Date().toLocaleString('fr-FR')}`;
    window.print();
}
async function afficherProfilSection() {
    const profil = await chargerProfil();
    document.getElementById('profil-content').innerHTML = profil ? htmlFormulaireProfil(profil) : '<p class="text-red-400">Erreur chargement profil</p>';
}
</script>
</body>
</html>