<!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É+ — Admin Hôpital</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>tailwind.config = { theme: { extend: { colors: { primary: '#0066CC', dark: '#003F8A' } } } }</script>
    <style>
        @media print {
            aside, header, .no-print { display: none !important; }
            main { margin-left: 0 !important; }
            .print-section { display: block !important; }
        }
        /* toggle mode_rdv */
        .mode-btn { padding: 8px 16px; border-radius: 10px; font-size: 13px; font-weight: 600; border: 2px solid #e5e7eb; background: #f9fafb; color: #6b7280; cursor: pointer; transition: all .15s; }
        .mode-btn.actif-creneaux { border-color: #2563eb; background: #2563eb; color: #fff; }
        .mode-btn.actif-quota    { border-color: #7c3aed; background: #7c3aed; color: #fff; }
        .mode-btn:hover:not(.actif-creneaux):not(.actif-quota) { background: #f3f4f6; border-color: #d1d5db; }
    </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">Admin Hôpital</p>
            </div>
        </div>
    </div>
    <div class="p-4 border-b border-white/10">
        <div class="bg-white/10 rounded-xl p-3">
            <p id="user-nom" class="font-bold text-sm">Chargement...</p>
            <p id="hopital-nom" class="text-white/60 text-xs mt-0.5">🏥 Hôpital</p>
        </div>
    </div>
    <nav class="flex-1 p-4 space-y-1 overflow-y-auto">
        <button onclick="afficherSection('dashboard')" 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> Dashboard</button>
        <button onclick="afficherSection('services')"  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> Services</button>
        <button onclick="afficherSection('staff')"     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> Staff</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> Créneaux</button>
        <button onclick="afficherSection('urgence')"   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> Urgences</button>
        <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> Tous les RDVs</button>
        <button onclick="afficherSection('revenus')"   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> Revenus</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">Dashboard</h1>
            <p class="text-sm text-gray-400" id="page-sous"></p>
        </div>
        <div class="flex gap-3 no-print">
            <button onclick="window.print()" 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 transition-all">🖨️ Imprimer</button>
            <button onclick="actualiser()" 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 transition-all">🔄 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 générique -->
    <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>

    <!-- ══ MODALE ÉDITION SERVICE ══ -->
    <div id="modal-service" 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-lg w-full shadow-2xl">
            <div class="flex items-center justify-between mb-5">
                <h3 class="font-black text-gray-900 text-lg">✏️ Modifier le service</h3>
                <button onclick="fermerModalService()" 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="edit-service-id" />
            <div class="space-y-4">
                <!-- nom -->
                <div>
                    <label class="block text-sm font-semibold text-gray-600 mb-1.5">Nom du service *</label>
                    <input id="edit-service-nom" type="text"
                        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>
                <!-- quota rdv jour + durée -->
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-semibold text-gray-600 mb-1.5">Quota RDV/jour</label>
                        <input id="edit-service-quota" type="number" min="1"
                            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">Durée consultation (min)</label>
                        <input id="edit-service-duree" type="number" min="5"
                            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>
                <!-- mode RDV -->
                <div>
                    <label class="block text-sm font-semibold text-gray-600 mb-2">Mode de rendez-vous *</label>
                    <div class="flex gap-3">
                        <button id="mode-btn-creneaux" onclick="setModeEdit('creneaux')"
                            class="mode-btn flex-1 text-center">
                            🕐 Créneaux horaires
                        </button>
                        <button id="mode-btn-quota" onclick="setModeEdit('quota')"
                            class="mode-btn flex-1 text-center">
                            🔢 Quota journalier
                        </button>
                    </div>
                    <div id="explication-mode" class="mt-2 text-xs text-gray-400 leading-relaxed"></div>
                </div>
                <!-- quota journalier (affiché seulement si mode quota) -->
                <div id="champ-quota-journalier" class="hidden">
                    <label class="block text-sm font-semibold text-gray-600 mb-1.5">
                        Quota journalier *
                        <span class="text-gray-400 font-normal">(nb max patients/jour en mode quota)</span>
                    </label>
                    <input id="edit-service-quota-journalier" type="number" min="1" placeholder="Ex: 30"
                        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-purple-500" />
                </div>
                <!-- description -->
                <div>
                    <label class="block text-sm font-semibold text-gray-600 mb-1.5">Description</label>
                    <input id="edit-service-description" type="text" placeholder="Optionnel"
                        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 class="flex gap-3 mt-6">
                <button onclick="fermerModalService()" class="flex-1 py-2.5 rounded-xl border-2 border-gray-200 text-gray-600 font-semibold">Annuler</button>
                <button onclick="sauvegarderService()" class="flex-1 py-2.5 rounded-xl bg-blue-600 text-white font-bold hover:bg-blue-700">💾 Enregistrer</button>
            </div>
        </div>
    </div>

<!-- ─── DASHBOARD ─── -->
<section id="section-dashboard" class="p-8">
    <div class="flex flex-wrap items-center gap-3 mb-6 no-print">
        <div class="flex bg-white border border-gray-200 rounded-xl overflow-hidden">
            <button onclick="setPeriode('jour')"    id="btn-jour"    class="periode-btn px-4 py-2 text-sm font-semibold transition-all bg-blue-600 text-white">Jour</button>
            <button onclick="setPeriode('semaine')" id="btn-semaine" class="periode-btn px-4 py-2 text-sm font-semibold transition-all text-gray-500 hover:bg-gray-50">Semaine</button>
            <button onclick="setPeriode('mois')"    id="btn-mois"    class="periode-btn px-4 py-2 text-sm font-semibold transition-all text-gray-500 hover:bg-gray-50">Mois</button>
            <button onclick="setPeriode('annee')"   id="btn-annee"   class="periode-btn px-4 py-2 text-sm font-semibold transition-all text-gray-500 hover:bg-gray-50">Année</button>
        </div>
        <select id="filtre-service-dash" onchange="chargerDashboard()" 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">
            <option value="">Tous les services</option>
        </select>
        <span id="periode-label" class="text-sm text-gray-400 ml-auto"></span>
    </div>
    <div class="grid grid-cols-4 gap-4 mb-6" id="kpi-cards">
        <div class="col-span-4 text-center py-8 text-gray-400">Chargement...</div>
    </div>
    <div class="grid grid-cols-2 gap-6 mb-6">
        <div class="bg-white rounded-2xl border border-gray-100 p-6">
            <h3 class="font-bold text-gray-900 mb-4">📈 RDVs par statut</h3>
            <canvas id="chart-statuts" height="200"></canvas>
        </div>
        <div class="bg-white rounded-2xl border border-gray-100 p-6">
            <h3 class="font-bold text-gray-900 mb-4">🏥 RDVs par service</h3>
            <canvas id="chart-services" height="200"></canvas>
        </div>
    </div>
    <div class="bg-white rounded-2xl border border-gray-100 overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-50 flex items-center justify-between">
            <h3 class="font-bold text-gray-900">RDVs de la période</h3>
            <span id="rdvs-count" class="px-3 py-1 bg-blue-50 text-blue-600 rounded-full text-sm font-bold">0</span>
        </div>
        <table class="w-full">
            <thead><tr class="bg-gray-50 border-b border-gray-100">
                <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Patient</th>
                <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Service</th>
                <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Date / Heure</th>
                <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Statut</th>
                <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Priorité</th>
            </tr></thead>
            <tbody id="tbody-dashboard">
                <tr><td colspan="5" class="text-center py-8 text-gray-400">Chargement...</td></tr>
            </tbody>
        </table>
    </div>
</section>

<!-- ─── SERVICES ─── -->
<section id="section-services" class="p-8 hidden">
    <div class="flex items-center justify-between mb-6">
        <h2 class="text-lg font-bold text-gray-900">Gestion des services</h2>
        <button onclick="toggleForm('form-service')" class="px-4 py-2 bg-blue-600 text-white rounded-xl text-sm font-semibold hover:bg-blue-700">+ Nouveau service</button>
    </div>

    <!-- formulaire création -->
    <div id="form-service" 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">Nouveau service</h3>
        <div class="grid grid-cols-3 gap-4">
            <div class="col-span-3">
                <label class="block text-sm font-semibold text-gray-600 mb-1.5">Nom *</label>
                <input id="service-nom" type="text" placeholder="Ex: Pédiatrie, Cardiologie..."
                    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">Quota RDV/jour</label>
                <input id="service-quota" type="number" value="15"
                    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">Durée consultation (min)</label>
                <input id="service-duree" type="number" value="30"
                    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">Description</label>
                <input id="service-description" type="text" placeholder="Optionnel"
                    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>
            <!-- mode RDV création -->
            <div class="col-span-3">
                <label class="block text-sm font-semibold text-gray-600 mb-2">Mode de rendez-vous *</label>
                <div class="flex gap-3">
                    <button id="create-mode-btn-creneaux" onclick="setModeCreate('creneaux')"
                        class="mode-btn actif-creneaux flex-1 text-center">🕐 Créneaux horaires</button>
                    <button id="create-mode-btn-quota" onclick="setModeCreate('quota')"
                        class="mode-btn flex-1 text-center">🔢 Quota journalier</button>
                </div>
                <div id="create-explication-mode" class="mt-2 text-xs text-gray-400 leading-relaxed">
                    Chaque patient reçoit un créneau horaire fixe (9h00, 9h15…). Idéal pour les cliniques privées.
                </div>
            </div>
            <!-- quota journalier création (caché par défaut) -->
            <div id="create-champ-quota-journalier" class="col-span-3 hidden">
                <label class="block text-sm font-semibold text-gray-600 mb-1.5">
                    Quota journalier *
                    <span class="text-gray-400 font-normal">(nb max patients/jour)</span>
                </label>
                <input id="service-quota-journalier" type="number" min="1" placeholder="Ex: 30"
                    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-purple-500" />
            </div>
        </div>
        <button onclick="creerService()" class="mt-4 px-6 py-2.5 bg-green-500 hover:bg-green-600 text-white font-bold rounded-xl text-sm">Créer →</button>
    </div>

    <!-- liste services -->
    <div id="liste-services" class="grid grid-cols-2 gap-4">
        <p class="col-span-2 text-center text-gray-400 py-8">Chargement...</p>
    </div>
</section>

<!-- ─── STAFF ─── -->
<section id="section-staff" class="p-8 hidden">
    <div class="flex items-center justify-between mb-6">
        <h2 class="text-lg font-bold text-gray-900">Gestion du staff</h2>
        <button onclick="toggleForm('form-staff')" class="px-4 py-2 bg-blue-600 text-white rounded-xl text-sm font-semibold hover:bg-blue-700">+ Nouveau gérant</button>
    </div>
    <div id="form-staff" 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">Créer un compte gérant</h3>
        <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="staff-prenom" type="text" 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="staff-nom" type="text" 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="staff-telephone" type="tel" 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">Mot de passe *</label><input id="staff-mdp" type="password" 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">Service *</label><select id="staff-service" 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...</option></select></div>
            <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Email</label><input id="staff-email" type="email" 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>
        <button onclick="creerStaff()" class="mt-4 px-6 py-2.5 bg-green-500 hover:bg-green-600 text-white font-bold rounded-xl text-sm">Créer →</button>
    </div>
    <div class="bg-white rounded-2xl 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-6 py-3 text-xs font-semibold text-gray-500 uppercase">Nom</th>
                <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Téléphone</th>
                <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Service</th>
                <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Rôle</th>
                <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Statut</th>
                <th class="text-right px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Actions</th>
            </tr></thead>
            <tbody id="tbody-staff"><tr><td colspan="6" class="text-center py-8 text-gray-400">Chargement...</td></tr></tbody>
        </table>
    </div>
</section>

<!-- ─── CRÉNEAUX ─── -->
<section id="section-creneaux" class="p-8 hidden">
    <div class="flex items-center gap-4 mb-6">
        <h2 class="text-lg font-bold text-gray-900">Créneaux horaires</h2>
        <select id="select-service-creneau" onchange="chargerCreneaux()" 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">
            <option value="">Sélectionner un service...</option>
        </select>
    </div>
    <div id="creneaux-content"><p class="text-gray-400 text-center py-16">Sélectionnez un service</p></div>
</section>

<!-- ─── URGENCES ─── -->
<section id="section-urgence" 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-red-50 bg-red-50"><h3 class="font-bold text-red-800">🔴 Fermeture exceptionnelle</h3></div>
            <div class="p-6 space-y-4">
                <select id="urgence-service" 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-red-500"><option value="">Choisir un service...</option></select>
                <textarea id="urgence-message" rows="3" placeholder="Motif envoyé aux patients..." 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-red-500 resize-none"></textarea>
                <button onclick="fermetureExceptionnelle()" class="w-full py-3 bg-red-500 hover:bg-red-600 text-white font-bold rounded-xl text-sm">🔴 Fermer et annuler tous les RDVs</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-amber-50 bg-amber-50"><h3 class="font-bold text-amber-800">📢 Communication de masse</h3></div>
            <div class="p-6 space-y-4">
                <select id="masse-service" 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-amber-500"><option value="">Choisir un service...</option></select>
                <textarea id="masse-message" rows="3" placeholder="Message pour tous les patients..." 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-amber-500 resize-none"></textarea>
                <button onclick="communicationMasse()" class="w-full py-3 bg-amber-500 hover:bg-amber-600 text-white font-bold rounded-xl text-sm">📢 Envoyer à tous</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"><h3 class="font-bold text-gray-900">🔍 Recherche patient</h3></div>
            <div class="p-6 space-y-4">
                <div class="flex gap-3">
                    <input type="text" id="recherche-patient-input" placeholder="Nom, téléphone ou code SENRDV-..."
                        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-blue-500"
                        onkeypress="if(event.key==='Enter') rechercherPatient()" />
                    <button onclick="rechercherPatient()" class="px-5 py-2.5 bg-blue-600 text-white font-bold rounded-xl text-sm">Chercher</button>
                </div>
                <div id="resultats-patient"></div>
            </div>
        </div>
    </div>
</section>

<!-- ─── TOUS LES RDVs ─── -->
<section id="section-rdvs" class="p-8 hidden">
    <div class="flex items-center gap-4 mb-6 flex-wrap">
        <h2 class="text-lg font-bold text-gray-900 mr-auto">Tous les rendez-vous</h2>
        <button onclick="purgerHistorique()"
    class="px-4 py-2 bg-red-50 hover:bg-red-100 text-red-600 rounded-xl text-sm font-semibold border border-red-200 no-print">
    🗑️ Purger l'historique (+6 mois)
</button>
        <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 no-print">🖨️ Imprimer la liste</button>
        <input type="date" id="rdvs-date" onchange="chargerTousRdvs()" 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" />
        <select id="rdvs-service" onchange="chargerTousRdvs()" 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">
            <option value="">Tous les services</option>
        </select>
        <select id="rdvs-statut" onchange="chargerTousRdvs()" 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">
            <option value="">Tous les statuts</option>
            <option value="en_attente">En attente</option>
            <option value="confirme">Confirmés</option>
            <option value="paye">Payés</option>
            <option value="consomme">Terminés</option>
            <option value="annule">Annulés</option>
        </select>
    </div>
    <div class="bg-white rounded-2xl border border-gray-100 overflow-hidden">
        <table class="w-full" id="table-rdvs-print">
            <thead><tr class="bg-gray-50 border-b border-gray-100">
                <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">#</th>
                <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Patient</th>
                <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Service</th>
                <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Date / Heure</th>
                <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Statut</th>
                <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Priorité</th>
            </tr></thead>
            <tbody id="tbody-rdvs"><tr><td colspan="6" class="text-center py-8 text-gray-400">Chargement...</td></tr></tbody>
        </table>
    </div>
</section>

<!-- ─── REVENUS ─── -->
<section id="section-revenus" class="p-8 hidden">
    <div class="flex flex-wrap items-center gap-3 mb-6 no-print">
        <div class="flex bg-white border border-gray-200 rounded-xl overflow-hidden">
            <button onclick="setAdminRevPeriode('jour')"    id="arev-btn-jour"    class="arev-btn px-4 py-2 text-sm font-semibold bg-blue-600 text-white">Jour</button>
            <button onclick="setAdminRevPeriode('semaine')" id="arev-btn-semaine" class="arev-btn px-4 py-2 text-sm font-semibold text-gray-500 hover:bg-gray-50">Semaine</button>
            <button onclick="setAdminRevPeriode('mois')"    id="arev-btn-mois"    class="arev-btn px-4 py-2 text-sm font-semibold text-gray-500 hover:bg-gray-50">Mois</button>
            <button onclick="setAdminRevPeriode('annee')"   id="arev-btn-annee"   class="arev-btn px-4 py-2 text-sm font-semibold text-gray-500 hover:bg-gray-50">Année</button>
        </div>
        <select id="arev-filtre-service" onchange="chargerAdminRevenus()" 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">
            <option value="">Tous les services</option>
        </select>
        <div class="flex items-center gap-2 ml-auto">
            <input type="date" id="arev-date-debut" class="px-3 py-2 rounded-xl border-2 border-gray-100 bg-white text-sm text-gray-600 focus:outline-none focus:border-blue-500" />
            <span class="text-gray-400 text-sm">→</span>
            <input type="date" id="arev-date-fin" class="px-3 py-2 rounded-xl border-2 border-gray-100 bg-white text-sm text-gray-600 focus:outline-none focus:border-blue-500" />
            <button onclick="chargerAdminRevenus()" class="px-4 py-2 bg-blue-600 text-white rounded-xl text-sm font-bold hover:bg-blue-700">Filtrer</button>
        </div>
    </div>
    <div class="grid grid-cols-4 gap-4 mb-6" id="arev-kpis">
        <div class="col-span-4 text-center py-8 text-gray-400">Chargement...</div>
    </div>
    <div class="bg-white rounded-2xl border border-gray-100 overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-50 flex items-center justify-between">
            <h3 class="font-bold text-gray-900">💰 Revenus par service</h3>
            <div class="flex items-center gap-3">
                <span id="arev-periode-badge" class="px-3 py-1 bg-green-50 text-green-600 rounded-full text-xs font-bold"></span>
                <button onclick="window.print()" class="px-3 py-1.5 bg-gray-100 hover:bg-gray-200 text-gray-600 rounded-lg text-xs font-semibold no-print">🖨️ Imprimer</button>
            </div>
        </div>
        <table class="w-full">
            <thead class="bg-gray-50 border-b border-gray-100"><tr>
                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase">Service</th>
                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase">RDVs payés</th>
                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase">Montant total</th>
                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase">Notre part (20%)</th>
                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase">Part hôpital (80%)</th>
            </tr></thead>
            <tbody id="arev-tbody"><tr><td colspan="5" class="text-center py-8 text-gray-400">Chargement...</td></tr></tbody>
        </table>
        <div class="px-6 py-4 bg-gray-50 border-t border-gray-100 flex items-center justify-between">
            <p class="font-bold text-gray-900">Total période</p>
            <div class="flex gap-8">
                <div class="text-right"><p class="text-xs text-gray-400">Montant total</p><p id="arev-total" class="font-black text-gray-900">— FCFA</p></div>
                <div class="text-right"><p class="text-xs text-gray-400">Notre part (20%)</p><p id="arev-notre-part" class="font-black text-[#003F8A]">— FCFA</p></div>
            </div>
        </div>
    </div>
</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 servicesData    = [];
let periodeCourante = 'jour';
let chartsInstances = {};
let modeCreateActif = 'creneaux'; // mode sélectionné dans le formulaire de création
let modeEditActif   = 'creneaux'; // mode sélectionné dans la modale d'édition

// ════════════════════════════════════
// INIT
// ════════════════════════════════════
window.addEventListener('DOMContentLoaded', async () => {
    const user = requireAuth(['admin_hopital', 'super_admin']);
    if (!user) return;
    const profil = await chargerProfil();
    if (profil) {
        document.getElementById('user-nom').textContent    = `${profil.prenom} ${profil.nom}`;
        document.getElementById('hopital-nom').textContent = profil.hopital_nom ? `🏥 ${profil.hopital_nom}` : 'Hôpital';
    }
    await Promise.all([chargerDashboard(), chargerServices(), chargerStaff()]);
});

// ════════════════════════════════════
// MODE RDV — helpers partagés
// ════════════════════════════════════
const EXPLICATIONS_MODE = {
    creneaux: 'Chaque patient reçoit un créneau horaire fixe (9h00, 9h15…). Idéal pour les cliniques privées.',
    quota:    'Le gérant ouvre une plage (ex: 8h-14h, 30 patients max). Pas d\'heure fixe — numéro de file N°1, N°2… Idéal pour les hôpitaux publics.',
};

function setModeCreate(mode) {
    modeCreateActif = mode;
    ['creneaux','quota'].forEach(function(m) {
        const btn = document.getElementById('create-mode-btn-' + m);
        btn.className = 'mode-btn flex-1 text-center' + (m === mode ? ' actif-' + m : '');
    });
    document.getElementById('create-explication-mode').textContent = EXPLICATIONS_MODE[mode];
    document.getElementById('create-champ-quota-journalier').classList.toggle('hidden', mode !== 'quota');
}

function setModeEdit(mode) {
    modeEditActif = mode;
    ['creneaux','quota'].forEach(function(m) {
        const btn = document.getElementById('mode-btn-' + m);
        btn.className = 'mode-btn flex-1 text-center' + (m === mode ? ' actif-' + m : '');
    });
    document.getElementById('explication-mode').textContent = EXPLICATIONS_MODE[mode];
    document.getElementById('champ-quota-journalier').classList.toggle('hidden', mode !== 'quota');
}

// ════════════════════════════════════
// MODALE ÉDITION SERVICE
// ════════════════════════════════════
function ouvrirModalService(s) {
    document.getElementById('edit-service-id').value          = s.id;
    document.getElementById('edit-service-nom').value         = s.nom;
    document.getElementById('edit-service-quota').value       = s.quota_rdv_jour;
    document.getElementById('edit-service-duree').value       = s.duree_consultation;
    document.getElementById('edit-service-description').value = s.description || '';
    document.getElementById('edit-service-quota-journalier').value = s.quota_journalier || '';
    setModeEdit(s.mode_rdv || 'creneaux');
    document.getElementById('modal-service').classList.remove('hidden');
}

function fermerModalService() {
    document.getElementById('modal-service').classList.add('hidden');
}

async function sauvegarderService() {
    const id   = document.getElementById('edit-service-id').value;
    const nom  = document.getElementById('edit-service-nom').value.trim();
    const quota = parseInt(document.getElementById('edit-service-quota').value);
    const duree = parseInt(document.getElementById('edit-service-duree').value);

    if (!nom) { toast('Nom obligatoire', 'error'); return; }

    const payload = {
        id,
        nom,
        quota_rdv_jour:     quota,
        duree_consultation: duree,
        description:        document.getElementById('edit-service-description').value,
        mode_rdv:           modeEditActif,
    };

    if (modeEditActif === 'quota') {
        const qj = parseInt(document.getElementById('edit-service-quota-journalier').value);
        if (!qj || qj <= 0) { toast('Quota journalier obligatoire en mode quota', 'error'); return; }
        payload.quota_journalier = qj;
    }

    const data = await api('/admin/services.php', {
        method: 'PUT',
        body:   JSON.stringify(payload),
    });

    if (data.succes) {
        toast('✅ Service mis à jour');
        fermerModalService();
        chargerServices();
    } else {
        toast(data.erreur || 'Erreur', 'error');
    }
}

// ════════════════════════════════════
// PÉRIODE
// ════════════════════════════════════
function setPeriode(p) {
    periodeCourante = p;
    ['jour','semaine','mois','annee'].forEach(function(x) {
        const btn = document.getElementById('btn-' + x);
        btn.className = x === p
            ? 'periode-btn px-4 py-2 text-sm font-semibold transition-all bg-blue-600 text-white'
            : 'periode-btn px-4 py-2 text-sm font-semibold transition-all text-gray-500 hover:bg-gray-50';
    });
    chargerDashboard();
}

function getPeriodeDates() {
    const now = new Date();
    const pad = function(n) { return String(n).padStart(2,'0'); };
    const fmt = function(d) { return d.getFullYear() + '-' + pad(d.getMonth()+1) + '-' + pad(d.getDate()); };
    let debut, fin, label;
    if (periodeCourante === 'jour') {
        debut = fin = fmt(now);
        label = 'Aujourd\'hui · ' + now.toLocaleDateString('fr-FR', { weekday:'long', day:'numeric', month:'long' });
    } else if (periodeCourante === 'semaine') {
        const lundi = new Date(now); lundi.setDate(now.getDate() - now.getDay() + 1);
        const dim   = new Date(lundi); dim.setDate(lundi.getDate() + 6);
        debut = fmt(lundi); fin = fmt(dim);
        label = 'Semaine du ' + lundi.toLocaleDateString('fr-FR', { day:'numeric', month:'long' });
    } else if (periodeCourante === 'mois') {
        debut = now.getFullYear() + '-' + pad(now.getMonth()+1) + '-01';
        fin   = fmt(new Date(now.getFullYear(), now.getMonth()+1, 0));
        label = now.toLocaleDateString('fr-FR', { month:'long', year:'numeric' });
    } else {
        debut = now.getFullYear() + '-01-01'; fin = now.getFullYear() + '-12-31';
        label = 'Année ' + now.getFullYear();
    }
    return { debut, fin, label };
}

// ════════════════════════════════════
// DASHBOARD
// ════════════════════════════════════
async function chargerDashboard() {
    const { debut, fin, label } = getPeriodeDates();
    document.getElementById('periode-label').textContent = label;
    const serviceId = document.getElementById('filtre-service-dash').value;
    let url = '/rdv/liste_gerant.php?date_debut=' + debut + '&date_fin=' + fin;
    if (serviceId) url += '&service_id=' + serviceId;

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

    const stats = data.stats || {};
    const total = Object.values(stats).reduce(function(a,b) { return a + Number(b); }, 0);
    document.getElementById('rdvs-count').textContent = data.total || 0;

    document.getElementById('kpi-cards').innerHTML = `
        <div class="bg-white rounded-2xl p-6 border border-gray-100 border-t-4 border-t-amber-400">
            <p class="text-xs text-gray-400 uppercase tracking-wide mb-1">En attente</p>
            <p class="text-3xl font-black text-amber-500">${stats.en_attente || 0}</p>
            <p class="text-xs text-gray-400 mt-1">${total ? Math.round((stats.en_attente||0)/total*100) : 0}% du total</p>
        </div>
        <div class="bg-white rounded-2xl p-6 border border-gray-100 border-t-4 border-t-blue-500">
            <p class="text-xs text-gray-400 uppercase tracking-wide mb-1">Confirmés</p>
            <p class="text-3xl font-black text-blue-600">${stats.confirme || 0}</p>
            <p class="text-xs text-gray-400 mt-1">${total ? Math.round((stats.confirme||0)/total*100) : 0}% du total</p>
        </div>
        <div class="bg-white rounded-2xl p-6 border border-gray-100 border-t-4 border-t-green-500">
            <p class="text-xs text-gray-400 uppercase tracking-wide mb-1">Payés / Terminés</p>
            <p class="text-3xl font-black text-green-600">${(stats.paye||0) + (stats.consomme||0)}</p>
            <p class="text-xs text-gray-400 mt-1">${total ? Math.round(((stats.paye||0)+(stats.consomme||0))/total*100) : 0}% du total</p>
        </div>
        <div class="bg-white rounded-2xl p-6 border border-gray-100 border-t-4 border-t-red-400">
            <p class="text-xs text-gray-400 uppercase tracking-wide mb-1">Annulés</p>
            <p class="text-3xl font-black text-red-500">${stats.annule || 0}</p>
            <p class="text-xs text-gray-400 mt-1">${total ? Math.round((stats.annule||0)/total*100) : 0}% du total</p>
        </div>`;

    dessinerChart('chart-statuts', 'doughnut',
        ['En attente','Confirmés','Payés','Terminés','Annulés'],
        [stats.en_attente||0, stats.confirme||0, stats.paye||0, stats.consomme||0, stats.annule||0],
        ['#F59E0B','#3B82F6','#10B981','#6B7280','#EF4444']
    );

    const rdvs = data.rdvs || [];
    const parService = {};
    rdvs.forEach(function(r) { parService[r.service_nom] = (parService[r.service_nom]||0)+1; });
    dessinerChart('chart-services', 'bar',
        Object.keys(parService), Object.values(parService),
        Object.keys(parService).map(function() { return '#3B82F6'; })
    );

    const tbody = document.getElementById('tbody-dashboard');
    if (!rdvs.length) {
        tbody.innerHTML = '<tr><td colspan="5" class="text-center py-8 text-gray-400">Aucun RDV pour cette période</td></tr>';
        return;
    }
    tbody.innerHTML = rdvs.map(function(rdv) { return `
        <tr class="border-b border-gray-50 hover:bg-gray-50/50">
            <td class="px-6 py-3 text-sm font-semibold text-gray-900">${rdv.patient_prenom} ${rdv.patient_nom}</td>
            <td class="px-6 py-3 text-sm text-gray-500">${rdv.service_nom}</td>
            <td class="px-6 py-3"><p class="text-sm font-semibold text-gray-900">${rdv.date_rdv}</p><p class="text-blue-600 font-bold">${formatHeure(rdv.heure_rdv)}</p></td>
            <td class="px-6 py-3">${statutBadge(rdv.statut)}</td>
            <td class="px-6 py-3">${rdv.prioritaire==1 ? '<span class="text-amber-500 font-bold">⭐</span>' : '<span class="text-gray-300">—</span>'}</td>
        </tr>`; }).join('');
}

function dessinerChart(id, type, labels, values, colors) {
    const ctx = document.getElementById(id)?.getContext('2d');
    if (!ctx) return;
    if (chartsInstances[id]) chartsInstances[id].destroy();
    chartsInstances[id] = new Chart(ctx, {
        type,
        data: { labels, datasets: [{ data: values, backgroundColor: colors, borderWidth: 0, borderRadius: type === 'bar' ? 6 : 0 }] },
        options: {
            responsive: true,
            plugins: { legend: { position: type === 'doughnut' ? 'right' : 'top' } },
            scales: type === 'bar' ? { y: { beginAtZero: true, ticks: { stepSize: 1 } } } : {},
        }
    });
}

// ════════════════════════════════════
// SERVICES
// ════════════════════════════════════
async function chargerServices() {
    const data = await api('/admin/services.php');
    if (!data.succes) return;
    servicesData = data.services;

    // peuple tous les selects de services
    const optHtml = servicesData.map(function(s) { return `<option value="${s.id}">${s.nom}</option>`; }).join('');
    ['staff-service','select-service-creneau','filtre-service-dash','rdvs-service',
     'urgence-service','masse-service','arev-filtre-service'].forEach(function(id) {
        const el = document.getElementById(id);
        if (!el) return;
        const avecTous = ['filtre-service-dash','rdvs-service','arev-filtre-service'].includes(id);
        el.innerHTML = (avecTous ? '<option value="">Tous les services</option>' : '<option value="">Choisir un service...</option>') + optHtml;
    });

    // affiche les cartes
    const container = document.getElementById('liste-services');
    if (!servicesData.length) {
        container.innerHTML = '<p class="col-span-2 text-center text-gray-400 py-8">Aucun service</p>';
        return;
    }

    container.innerHTML = servicesData.map(function(s) {
        const modeLabel = s.mode_rdv === 'quota'
            ? `<span class="px-2 py-0.5 bg-purple-100 text-purple-700 rounded-full text-xs font-bold">🔢 Quota</span>`
            : `<span class="px-2 py-0.5 bg-blue-100 text-blue-700 rounded-full text-xs font-bold">🕐 Créneaux</span>`;

        const quotaInfo = s.mode_rdv === 'quota' && s.quota_journalier
            ? `<p class="text-xs text-purple-600 font-semibold mt-0.5">👥 ${s.quota_journalier} patients/jour max</p>`
            : `<p class="text-xs text-gray-400 mt-0.5">${s.quota_rdv_jour} RDV/jour · ${s.duree_consultation} min</p>`;

        return `
        <div class="bg-white rounded-2xl p-5 border border-gray-100 shadow-sm">
            <div class="flex items-start justify-between mb-3">
                <div class="w-10 h-10 rounded-xl bg-blue-50 flex items-center justify-center text-xl">🩺</div>
                <div class="flex items-center gap-2">
                    ${modeLabel}
                    <span class="px-2.5 py-1 rounded-full text-xs font-semibold ${s.actif==1 ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-600'}">${s.actif==1 ? 'Actif' : 'Inactif'}</span>
                </div>
            </div>
            <h3 class="font-bold text-gray-900 mb-1">${s.nom}</h3>
            ${quotaInfo}
            <p class="text-xs text-gray-400 mt-1">${s.nb_gerants} gérant(s) · ${s.nb_creneaux} créneau(x)</p>
            <div class="flex gap-2 mt-3">
                <button onclick='ouvrirModalService(${JSON.stringify(s)})'
                    class="flex-1 py-2 rounded-xl text-xs font-semibold bg-blue-50 text-blue-600 hover:bg-blue-100">
                    ✏️ Modifier
                </button>
                <button onclick="desactiverService(${s.id},${s.actif})"
                    class="flex-1 py-2 rounded-xl text-xs font-semibold ${s.actif==1 ? 'bg-red-50 text-red-500 hover:bg-red-100' : 'bg-green-50 text-green-600 hover:bg-green-100'}">
                    ${s.actif==1 ? '🔒 Désactiver' : '🔓 Activer'}
                </button>
            </div>
        </div>`;
    }).join('');
}

async function creerService() {
    const nom = document.getElementById('service-nom').value.trim();
    if (!nom) { toast('Nom obligatoire', 'error'); return; }

    if (modeCreateActif === 'quota') {
        const qj = parseInt(document.getElementById('service-quota-journalier').value);
        if (!qj || qj <= 0) { toast('Quota journalier obligatoire en mode quota', 'error'); return; }
    }

    const payload = {
        nom,
        quota_rdv_jour:     parseInt(document.getElementById('service-quota').value),
        duree_consultation: parseInt(document.getElementById('service-duree').value),
        description:        document.getElementById('service-description').value,
        mode_rdv:           modeCreateActif,
    };
    if (modeCreateActif === 'quota') {
        payload.quota_journalier = parseInt(document.getElementById('service-quota-journalier').value);
    }

    const data = await api('/admin/services.php', { method: 'POST', body: JSON.stringify(payload) });
    if (data.succes) {
        toast('✅ Service créé');
        toggleForm('form-service');
        // reset mode création
        setModeCreate('creneaux');
        document.getElementById('service-nom').value = '';
        chargerServices();
    } else {
        toast(data.erreur || 'Erreur', 'error');
    }
}

async function desactiverService(id, actif) {
    confirmerAction((actif==1 ? 'Désactiver' : 'Activer') + ' ce service ?', async function() {
        const data = await api('/admin/services.php?id=' + id, { method: 'DELETE' });
        if (data.succes) { toast('Service mis à jour'); chargerServices(); }
        else toast(data.erreur || 'Erreur', 'error');
    });
}

// ════════════════════════════════════
// STAFF
// ════════════════════════════════════
async function chargerStaff() {
    const data = await api('/admin/staff.php');
    if (!data.succes) return;
    const tbody = document.getElementById('tbody-staff');
    if (!data.staff.length) { tbody.innerHTML = '<tr><td colspan="6" class="text-center py-8 text-gray-400">Aucun membre</td></tr>'; return; }
    tbody.innerHTML = data.staff.map(function(m) { return `
        <tr class="border-b border-gray-50 hover:bg-gray-50/50">
            <td class="px-6 py-4"><div class="flex items-center gap-3">
                <div class="w-8 h-8 rounded-lg bg-blue-50 flex items-center justify-center text-sm font-bold text-blue-600">${m.prenom[0]}${m.nom[0]}</div>
                <div><p class="font-semibold text-gray-900 text-sm">${m.prenom} ${m.nom}</p><p class="text-xs text-gray-400">${m.email||''}</p></div>
            </div></td>
            <td class="px-6 py-4 text-sm text-gray-600">${m.telephone}</td>
            <td class="px-6 py-4 text-sm text-gray-600">${m.service_nom||'—'}</td>
            <td class="px-6 py-4"><span class="px-2.5 py-1 bg-blue-50 text-blue-700 rounded-full text-xs font-semibold">${m.role==='admin_hopital'?'👨‍💼 Admin':'👨‍⚕️ Gérant'}</span></td>
            <td class="px-6 py-4"><span class="px-2.5 py-1 rounded-full text-xs font-semibold ${m.actif==1?'bg-green-100 text-green-700':'bg-red-100 text-red-600'}">${m.actif==1?'Actif':'Inactif'}</span></td>
            <td class="px-6 py-4 text-right"><button onclick="toggleStaff(${m.id},${m.actif})" class="px-3 py-1.5 rounded-lg text-xs font-semibold ${m.actif==1?'bg-red-50 text-red-500 hover:bg-red-100':'bg-green-50 text-green-600 hover:bg-green-100'}">${m.actif==1?'Désactiver':'Activer'}</button></td>
        </tr>`; }).join('');
}

async function creerStaff() {
    const prenom=document.getElementById('staff-prenom').value.trim(),
          nom=document.getElementById('staff-nom').value.trim(),
          tel=document.getElementById('staff-telephone').value.trim(),
          mdp=document.getElementById('staff-mdp').value,
          sid=document.getElementById('staff-service').value;
    if (!prenom||!nom||!tel||!mdp||!sid) { toast('Tous les champs obligatoires', 'error'); return; }
    const data = await api('/admin/staff.php', { method:'POST', body: JSON.stringify({ prenom,nom,telephone:tel,mot_de_passe:mdp,role:'gerant',service_id:parseInt(sid),email:document.getElementById('staff-email').value }) });
    if (data.succes) { toast('✅ Compte créé'); toggleForm('form-staff'); chargerStaff(); }
    else toast(data.erreur||'Erreur','error');
}

async function toggleStaff(id, actif) {
    const data = await api('/admin/staff.php', { method:'PUT', body: JSON.stringify({id, actif: actif==1?0:1}) });
    if (data.succes) { toast(actif==1?'Désactivé':'Activé'); chargerStaff(); }
}

// ════════════════════════════════════
// CRÉNEAUX
// ════════════════════════════════════
async function chargerCreneaux() {
    const sid = document.getElementById('select-service-creneau').value;
    if (!sid) return;
    const data = await api('/admin/creneaux.php?service_id=' + sid);
    const container = document.getElementById('creneaux-content');
    if (!data.succes || !data.creneaux.length) {
        container.innerHTML = `<div class="text-center py-16 text-gray-400"><p class="text-4xl mb-2">🕐</p><p>Aucun créneau</p><button onclick="toggleForm('form-creneau-admin')" class="mt-4 px-4 py-2 bg-blue-600 text-white rounded-xl text-sm font-semibold">+ Ajouter</button></div>`;
        return;
    }
    const jours = {'1':'Lundi','2':'Mardi','3':'Mercredi','4':'Jeudi','5':'Vendredi','6':'Samedi','7':'Dimanche'};
    container.innerHTML = `
        <div class="flex justify-end mb-4 no-print">
            <button onclick="toggleForm('form-creneau-admin')" 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 id="form-creneau-admin" class="hidden bg-white rounded-2xl p-6 border border-gray-100 mb-4">
            <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-admin-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-admin-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-admin-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="creerCreneauAdmin(${sid})" class="mt-3 px-5 py-2.5 bg-green-500 text-white rounded-xl text-sm font-bold">Créer →</button>
        </div>
        <div class="bg-white rounded-2xl 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-6 py-3 text-xs font-semibold text-gray-500 uppercase">Jour</th>
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Horaire</th>
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Statut</th>
                    <th class="text-right px-6 py-3 text-xs font-semibold text-gray-500 uppercase no-print">Actions</th>
                </tr></thead>
                <tbody>${data.creneaux.map(function(c) { return `
                    <tr class="border-b border-gray-50">
                        <td class="px-6 py-3 text-sm font-semibold text-gray-900">${c.jour_label || jours[c.jour_semaine] || c.jour_semaine}</td>
                        <td class="px-6 py-3 text-sm font-bold text-blue-600">${formatHeure(c.heure_debut)} → ${formatHeure(c.heure_fin)}</td>
                        <td class="px-6 py-3"><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></td>
                        <td class="px-6 py-3 text-right no-print"><button onclick="toggleCreneauAdmin(${c.id},${c.disponible==1?0:1},${sid})" class="px-3 py-1.5 rounded-lg text-xs font-semibold ${c.disponible==1?'bg-red-50 text-red-500':'bg-green-50 text-green-600'}">${c.disponible==1?'🔒 Bloquer':'🔓 Activer'}</button></td>
                    </tr>`; }).join('')}
                </tbody>
            </table>
        </div>`;
}

async function creerCreneauAdmin(sid) {
    const data = await api('/admin/creneaux.php', { method:'POST', body: JSON.stringify({ service_id:sid, jour_semaine:document.getElementById('creneau-admin-jour').value, heure_debut:document.getElementById('creneau-admin-debut').value, heure_fin:document.getElementById('creneau-admin-fin').value }) });
    if (data.succes) { toast('✅ Créneau créé'); chargerCreneaux(); } else toast(data.erreur||'Erreur','error');
}

async function toggleCreneauAdmin(id, disponible, sid) {
    await api('/admin/creneaux.php', { method:'PUT', body: JSON.stringify({id,disponible}) });
    chargerCreneaux();
}

// ════════════════════════════════════
// TOUS LES RDVs
// ════════════════════════════════════
async function chargerTousRdvs() {
    const date=document.getElementById('rdvs-date').value,
          statut=document.getElementById('rdvs-statut').value,
          sid=document.getElementById('rdvs-service').value;
    let url='/rdv/liste_gerant.php?';
    if (date) url+='date='+date+'&';
    if (statut) url+='statut='+statut+'&';
    if (sid) url+='service_id='+sid;
    const data = await api(url);
    const tbody = document.getElementById('tbody-rdvs');
    if (!data.succes||!data.rdvs.length) { tbody.innerHTML='<tr><td colspan="6" class="text-center py-8 text-gray-400">Aucun RDV trouvé</td></tr>'; return; }
    tbody.innerHTML = data.rdvs.map(function(rdv,i) { return `
        <tr class="border-b border-gray-50 hover:bg-gray-50/50">
            <td class="px-6 py-3 text-sm text-gray-400">${i+1}</td>
            <td class="px-6 py-3 text-sm font-semibold text-gray-900">${rdv.patient_prenom} ${rdv.patient_nom}</td>
            <td class="px-6 py-3 text-sm text-gray-500">${rdv.service_nom}</td>
            <td class="px-6 py-3"><p class="text-sm font-semibold">${rdv.date_rdv}</p><p class="text-blue-600 font-bold">${formatHeure(rdv.heure_rdv)}</p></td>
            <td class="px-6 py-3">${statutBadge(rdv.statut)}</td>
            <td class="px-6 py-3">${rdv.prioritaire==1?'<span class="text-amber-500 font-bold">⭐ Prioritaire</span>':'<span class="text-gray-300">—</span>'}</td>
        </tr>`; }).join('');
}

async function purgerHistorique() {
    confirmerAction(
        '🗑️ Supprimer définitivement tous les RDV terminés, annulés ou expirés datant de plus de 6 mois ? Cette action est irréversible.',
        async function() {
            const data = await api('/admin/purger_historique.php', {
                method: 'POST',
                body: JSON.stringify({ mois: 6 })
            });
            if (data.succes) {
                toast('✅ ' + data.message);
                chargerTousRdvs();
            } else {
                toast(data.erreur || 'Erreur', 'error');
            }
        }
    );
}

function imprimerListe() {
    const date = document.getElementById('rdvs-date').value || 'Toutes dates';
    const before = document.title;
    document.title = 'Liste RDVs — ' + date + ' — SEN RDV SANTÉ+';
    window.print();
    document.title = before;
}

// ════════════════════════════════════
// URGENCES
// ════════════════════════════════════
function peuplerSelectsUrgence() {
    const opts = '<option value="">Choisir...</option>' + servicesData.map(function(s) { return `<option value="${s.id}">${s.nom}</option>`; }).join('');
    document.getElementById('urgence-service').innerHTML = opts;
    document.getElementById('masse-service').innerHTML   = opts;
}

async function fermetureExceptionnelle() {
    const sid=document.getElementById('urgence-service').value, msg=document.getElementById('urgence-message').value.trim();
    if (!sid||!msg) { toast('Service et motif obligatoires','error'); return; }
    confirmerAction('⚠️ Annuler TOUS les RDVs actifs et rembourser ?', async function() {
        const data = await api('/admin/urgence.php', { method:'POST', body: JSON.stringify({action:'fermeture_service',service_id:sid,message:msg}) });
        if (data.succes) { toast('✅ ' + data.message); document.getElementById('urgence-message').value=''; }
        else toast(data.erreur||'Erreur','error');
    });
}

async function communicationMasse() {
    const sid=document.getElementById('masse-service').value, msg=document.getElementById('masse-message').value.trim();
    if (!sid||!msg) { toast('Service et message obligatoires','error'); return; }
    const data = await api('/admin/urgence.php', { method:'POST', body: JSON.stringify({action:'communication_masse',service_id:sid,message:msg}) });
    if (data.succes) { toast('📢 ' + data.message); document.getElementById('masse-message').value=''; }
    else toast(data.erreur||'Erreur','error');
}

async function rechercherPatient() {
    const q=document.getElementById('recherche-patient-input').value.trim();
    if (!q) return;
    const data=await api('/rdv/liste_gerant.php?recherche='+encodeURIComponent(q));
    const el=document.getElementById('resultats-patient');
    if (!data.succes||!data.rdvs.length) { el.innerHTML='<p class="text-gray-400 text-sm text-center py-4">Aucun résultat</p>'; return; }
    el.innerHTML=data.rdvs.map(function(rdv) { return `
        <div class="flex items-center gap-3 p-3 bg-gray-50 rounded-xl mb-2">
            <div class="w-9 h-9 rounded-lg bg-blue-50 flex items-center justify-center text-sm font-bold text-blue-600">${rdv.patient_prenom[0]}${rdv.patient_nom[0]}</div>
            <div class="flex-1"><p class="font-semibold text-gray-900 text-sm">${rdv.patient_prenom} ${rdv.patient_nom}</p><p class="text-xs text-gray-500">${rdv.service_nom} · ${rdv.date_rdv} à ${formatHeure(rdv.heure_rdv)}</p>${rdv.code_qr?`<p class="text-xs font-mono text-blue-600">${rdv.code_qr}</p>`:''}</div>
            ${statutBadge(rdv.statut)}
        </div>`; }).join('');
}

// ════════════════════════════════════
// NAVIGATION
// ════════════════════════════════════
function actualiser() {
    const sections=['dashboard','services','staff','creneaux','urgence','rdvs','revenus'];
    const actif=sections.find(function(s) { return !document.getElementById('section-'+s)?.classList.contains('hidden'); });
    if (actif==='dashboard') chargerDashboard();
    else if (actif==='services') chargerServices();
    else if (actif==='staff') chargerStaff();
    else if (actif==='creneaux') chargerCreneaux();
    else if (actif==='rdvs') chargerTousRdvs();
}

function toggleForm(id) { document.getElementById(id)?.classList.toggle('hidden'); }

function afficherSection(section) {
    ['dashboard','services','staff','creneaux','urgence','rdvs','revenus','profil'].forEach(function(s) {
        document.getElementById('section-'+s)?.classList.add('hidden');
    });
    document.getElementById('section-'+section)?.classList.remove('hidden');
    const titres = { dashboard:'Dashboard', services:'Gestion des services', staff:'Gestion du staff', creneaux:'Créneaux horaires', urgence:'Urgences & Communications', rdvs:'Tous les rendez-vous', revenus:'Revenus', profil:'Mon profil' };
    document.getElementById('page-titre').textContent = titres[section]||'';
    if (section==='profil')  afficherProfilSection();
    if (section==='urgence') peuplerSelectsUrgence();
    if (section==='rdvs')    { document.getElementById('rdvs-date').value=new Date().toISOString().split('T')[0]; chargerTousRdvs(); }
}

async function afficherProfilSection() {
    const profil = await chargerProfil();
    document.getElementById('profil-content').innerHTML = profil ? htmlFormulaireProfil(profil) : '<p class="text-red-400">Erreur</p>';
}
</script>
</body>
</html>