<!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É+ — Super Admin</title>
    <script src="/web/assets/app.js"></script>
    <script src="https://cdn.tailwindcss.com"></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; }
        }
        #user-services-input option:checked { background: #0066CC; color: white; }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">

<!-- ═══ SIDEBAR ═══ -->
<aside class="fixed left-0 top-0 h-full w-64 bg-[#1a1a2e] 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/40 text-xs uppercase tracking-widest">Ministère</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 class="text-white/50 text-xs mt-0.5">Super Administrateur</p>
        </div>
    </div>
    <nav class="flex-1 p-4 space-y-1 overflow-y-auto">
        <button onclick="afficherSection('national')"     class="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> Vue nationale</button>
        <button onclick="afficherSection('hopitaux')"     class="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> Annuaire hôpitaux</button>
        <button onclick="afficherSection('utilisateurs')" class="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> Utilisateurs</button>
        <button onclick="afficherSection('directeurs')"  class="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> Directeurs régionaux</button>
        <button onclick="afficherSection('stats')"        class="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('revenus')"      class="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('pub')"          class="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> Publicités</button>
        <button onclick="afficherSection('parametres')"   class="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> Paramètres</button>
        <button onclick="afficherSection('profil')"       class="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-red-300 hover:bg-red-500/10 transition-all text-sm"><span>🚪</span> Déconnexion</button>
    </div>
</aside>

<!-- ═══ CONTENU ═══ -->
<div class="ml-64 min-h-screen flex flex-col">
    <header class="bg-white border-b border-gray-100 px-8 py-4 flex items-center justify-between sticky top-0 z-20 shadow-sm">
        <h1 id="page-titre" class="text-xl font-black text-gray-900">Vue nationale</h1>
        <div class="flex items-center gap-3 no-print">
            <span class="px-3 py-1.5 bg-purple-100 text-purple-700 rounded-lg text-xs font-bold">Super Admin</span>
            <button onclick="window.print()" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl text-sm font-semibold text-gray-600">🖨️ Imprimer</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="fixed inset-0 bg-black/50 z-50 hidden 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-msg" class="text-gray-800 font-semibold mb-5 text-center"></p>
            <div class="flex gap-3">
                <button onclick="document.getElementById('modal-confirm').classList.add('hidden')" class="flex-1 py-2.5 rounded-xl border-2 border-gray-200 text-gray-600 font-semibold text-sm">Annuler</button>
                <button id="modal-ok" class="flex-1 py-2.5 rounded-xl bg-red-500 text-white font-bold text-sm">Confirmer</button>
            </div>
        </div>
    </div>

    <main class="flex-1">

<!-- ─── VUE NATIONALE ─── -->
<section id="section-national" class="p-8">
    <div class="grid grid-cols-4 gap-5 mb-8">
        <div class="bg-white rounded-2xl p-5 border border-gray-100 shadow-sm"><p class="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-1">Hôpitaux</p><p id="stat-hopitaux" class="text-3xl font-black text-gray-900">—</p></div>
        <div class="bg-white rounded-2xl p-5 border border-gray-100 shadow-sm"><p class="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-1">Patients</p><p id="stat-patients" class="text-3xl font-black text-gray-900">—</p></div>
        <div class="bg-white rounded-2xl p-5 border border-gray-100 shadow-sm"><p class="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-1">RDV ce mois</p><p id="stat-rdvs" class="text-3xl font-black text-gray-900">—</p></div>
        <div class="bg-white rounded-2xl p-5 border border-gray-100 shadow-sm"><p class="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-1">Revenus (FCFA)</p><p id="stat-revenus" class="text-3xl font-black text-gray-900">—</p></div>
    </div>
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
        <h3 class="font-bold text-gray-900 mb-4">🏥 Activité par hôpital</h3>
        <div id="tableau-national" class="text-center text-gray-400 py-8">Chargement...</div>
    </div>
</section>

<!-- ─── HÔPITAUX ─── -->
<section id="section-hopitaux" class="p-8 hidden">
    <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">🏥 Annuaire des établissements</h3>
            <button onclick="ouvrirModalHopital()" class="px-4 py-2 bg-blue-600 text-white rounded-xl text-sm font-bold hover:bg-blue-700">+ Ajouter un hôpital</button>
        </div>
        <div class="px-6 py-4 flex gap-3 flex-wrap">
            <input id="search-hopital" type="text" placeholder="Rechercher..." oninput="filtrerHopitaux()" class="flex-1 min-w-40 px-4 py-2 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-400" />
            <select id="filter-type" onchange="filtrerHopitaux()" class="px-4 py-2 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-400">
                <option value="">Tous types</option><option value="public">Public</option><option value="prive">Privé</option>
            </select>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 border-y border-gray-100">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Établissement</th>
                        <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Localisation</th>
                        <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Type</th>
                        <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Services</th>
                        <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Téléphone</th>
                        <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Actions</th>
                    </tr>
                </thead>
                <tbody id="tbody-hopitaux"><tr><td colspan="6" class="text-center py-8 text-gray-400">Chargement...</td></tr></tbody>
            </table>
        </div>
    </div>

    <!-- modal hôpital -->
    <div id="modal-hopital" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl w-full max-w-lg shadow-2xl overflow-y-auto max-h-[90vh]">
            <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
                <h3 id="modal-hopital-titre" class="font-bold text-gray-900">Ajouter un hôpital</h3>
                <button onclick="fermerModalHopital()" class="text-gray-400 hover:text-gray-600 text-xl">✕</button>
            </div>
            <div class="p-6 space-y-4">
                <input type="hidden" id="hopital-id" />
                <div class="grid grid-cols-2 gap-4">
                    <div class="col-span-2"><label class="block text-sm font-semibold text-gray-600 mb-1.5">Nom *</label><input id="hopital-nom-input" 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">Type *</label><select id="hopital-type" 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="public">Public</option><option value="prive">Privé</option></select></div>
                    <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Téléphone</label><input id="hopital-telephone" 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">Ville *</label><input id="hopital-ville" 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">Région *</label>
                        <select id="hopital-region" 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>Dakar</option><option>Thiès</option><option>Diourbel</option><option>Fatick</option><option>Kaolack</option><option>Kaffrine</option><option>Kolda</option><option>Louga</option><option>Matam</option><option>Saint-Louis</option><option>Sédhiou</option><option>Tambacounda</option><option>Ziguinchor</option><option>Kédougou</option>
                        </select>
                    </div>
                    <div class="col-span-2"><label class="block text-sm font-semibold text-gray-600 mb-1.5">Adresse</label><input id="hopital-adresse" 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 class="col-span-2"><label class="block text-sm font-semibold text-gray-600 mb-1.5">Email</label><input id="hopital-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>
                <div class="flex gap-3 pt-2">
                    <button onclick="fermerModalHopital()" class="flex-1 py-3 rounded-xl border-2 border-gray-200 text-gray-600 font-semibold text-sm">Annuler</button>
                    <button onclick="sauvegarderHopital()" class="flex-1 py-3 rounded-xl bg-blue-600 text-white font-bold text-sm hover:bg-blue-700">Sauvegarder</button>
                </div>
            </div>
        </div>
    </div>

    <!-- modal services -->
    <div id="modal-services" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl w-full max-w-2xl shadow-2xl flex flex-col max-h-[90vh]">
            <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between flex-shrink-0">
                <div>
                    <h3 class="font-bold text-gray-900">🩺 Services de <span id="services-hopital-nom" class="text-blue-600"></span></h3>
                    <p class="text-xs text-gray-400 mt-0.5">Gérez les services médicaux de cet établissement</p>
                </div>
                <button onclick="fermerModalServices()" class="text-gray-400 hover:text-gray-600 text-xl">✕</button>
            </div>
            <!-- liste -->
            <div class="flex-1 overflow-y-auto p-6 space-y-3" id="services-liste">
                <p class="text-gray-400 text-center py-8">Chargement...</p>
            </div>
            <!-- formulaire -->
            <div class="border-t border-gray-100 p-6 flex-shrink-0 bg-gray-50/50">
                <input type="hidden" id="service-edit-id" />
                <p id="form-service-titre" class="text-sm font-bold text-gray-700 mb-3">➕ Ajouter un service</p>
                <div class="grid grid-cols-2 gap-3">
                    <div class="col-span-2">
                        <label class="block text-xs font-semibold text-gray-500 mb-1">Nom du service *</label>
                        <input id="service-nom" type="text" placeholder="Ex: Pédiatrie, Cardiologie..."
                            class="w-full px-3 py-2.5 rounded-xl border-2 border-gray-100 bg-white text-sm focus:outline-none focus:border-blue-500" />
                    </div>
                    <div class="col-span-2">
                        <label class="block text-xs font-semibold text-gray-500 mb-1">Description</label>
                        <input id="service-description" type="text" placeholder="Description courte (optionnel)"
                            class="w-full px-3 py-2.5 rounded-xl border-2 border-gray-100 bg-white text-sm focus:outline-none focus:border-blue-500" />
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-gray-500 mb-1">Quota RDV / jour *</label>
                        <input id="service-quota" type="number" min="1" value="20"
                            class="w-full px-3 py-2.5 rounded-xl border-2 border-gray-100 bg-white text-sm focus:outline-none focus:border-blue-500" />
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-gray-500 mb-1">Durée consultation (min) *</label>
                        <input id="service-duree" type="number" min="5" value="30"
                            class="w-full px-3 py-2.5 rounded-xl border-2 border-gray-100 bg-white text-sm focus:outline-none focus:border-blue-500" />
                    </div>
                </div>
                <div class="flex gap-3 mt-3">
                    <button onclick="resetFormService()" id="btn-annuler-service"
                        class="hidden px-4 py-2.5 rounded-xl border-2 border-gray-200 text-gray-600 font-semibold text-sm">
                        Annuler
                    </button>
                    <button onclick="sauvegarderService()"
                        class="flex-1 py-2.5 rounded-xl bg-blue-600 text-white font-bold text-sm hover:bg-blue-700">
                        💾 <span id="btn-service-label">Ajouter le service</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- ─── UTILISATEURS ─── -->
<section id="section-utilisateurs" class="p-8 hidden">
    <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">👥 Gestion des utilisateurs</h3>
            <button onclick="ouvrirModalUtilisateur()" class="px-4 py-2 bg-blue-600 text-white rounded-xl text-sm font-bold hover:bg-blue-700">+ Créer un utilisateur</button>
        </div>
        <div class="px-6 py-4 flex gap-3 flex-wrap">
            <input id="search-user" type="text" placeholder="Rechercher..." oninput="filtrerUtilisateurs()" class="flex-1 min-w-40 px-4 py-2 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-400" />
            <select id="filter-role" onchange="filtrerUtilisateurs()" class="px-4 py-2 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-400">
                <option value="">Tous les rôles</option>
                <option value="admin_hopital">Admin hôpital</option>
                <option value="gerant">Gérant service</option>
                <option value="patient">Patient</option>
            </select>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 border-y border-gray-100">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Utilisateur</th>
                        <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Rôle</th>
                        <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Hôpital</th>
                        <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Services</th>
                        <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Statut</th>
                        <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Actions</th>
                    </tr>
                </thead>
                <tbody id="tbody-utilisateurs"><tr><td colspan="6" class="text-center py-8 text-gray-400">Chargement...</td></tr></tbody>
            </table>
        </div>
    </div>
    <!-- modal utilisateur -->
    <div id="modal-utilisateur" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl w-full max-w-lg shadow-2xl overflow-y-auto max-h-[90vh]">
            <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
                <h3 id="modal-user-titre" class="font-bold text-gray-900">Créer un utilisateur</h3>
                <button onclick="fermerModalUtilisateur()" class="text-gray-400 hover:text-gray-600 text-xl">✕</button>
            </div>
            <div class="p-6 space-y-4">
                <input type="hidden" id="user-edit-id" />
                <div class="grid grid-cols-2 gap-4">
                    <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Nom *</label><input id="user-nom-input" 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">Prénom *</label><input id="user-prenom-input" 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="user-telephone-input" 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">Email</label><input id="user-email-input" 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><label class="block text-sm font-semibold text-gray-600 mb-1.5">Rôle *</label><select id="user-role-input" onchange="toggleChampsRole()" 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="admin_hopital">Admin hôpital</option><option value="gerant">Gérant service</option><option value="patient">Patient</option></select></div>
                    <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Statut</label><select id="user-actif-input" 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="1">Actif</option><option value="0">Inactif</option></select></div>
                    <div id="champ-hopital" class="col-span-2">
                        <label class="block text-sm font-semibold text-gray-600 mb-1.5">Hôpital *</label>
                        <select id="user-hopital-input" onchange="chargerServicesSelect()" 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 hôpital --</option>
                        </select>
                    </div>
                    <div id="champ-services" class="col-span-2 hidden">
                        <label class="block text-sm font-semibold text-gray-600 mb-1.5">
                            Services gérés *
                            <span class="text-xs font-normal text-gray-400 ml-1">(Ctrl+clic pour sélection multiple)</span>
                        </label>
                        <select id="user-services-input" multiple
                            class="w-full px-3 py-2 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500"
                            style="min-height:120px" onchange="majCompteurServices()">
                            <option disabled>-- Choisir d'abord un hôpital --</option>
                        </select>
                        <p id="services-hint" class="text-xs text-blue-600 mt-1 hidden">✅ <span id="services-count">0</span> service(s) sélectionné(s)</p>
                    </div>
                    <div id="champ-mot-de-passe" class="col-span-2">
                        <label class="block text-sm font-semibold text-gray-600 mb-1.5">Mot de passe *</label>
                        <input id="user-mdp-input" 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>
                <div class="flex gap-3 pt-2">
                    <button onclick="fermerModalUtilisateur()" class="flex-1 py-3 rounded-xl border-2 border-gray-200 text-gray-600 font-semibold text-sm">Annuler</button>
                    <button onclick="sauvegarderUtilisateur()" class="flex-1 py-3 rounded-xl bg-blue-600 text-white font-bold text-sm hover:bg-blue-700">Sauvegarder</button>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- ─── STATISTIQUES ─── -->
<section id="section-stats" 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="setStatsPeriode('jour')"    id="stats-btn-jour"    class="stats-p-btn px-4 py-2 text-sm font-semibold bg-blue-600 text-white">Jour</button>
            <button onclick="setStatsPeriode('semaine')" id="stats-btn-semaine" class="stats-p-btn px-4 py-2 text-sm font-semibold text-gray-500 hover:bg-gray-50">Semaine</button>
            <button onclick="setStatsPeriode('mois')"    id="stats-btn-mois"    class="stats-p-btn px-4 py-2 text-sm font-semibold text-gray-500 hover:bg-gray-50">Mois</button>
            <button onclick="setStatsPeriode('annee')"   id="stats-btn-annee"   class="stats-p-btn px-4 py-2 text-sm font-semibold text-gray-500 hover:bg-gray-50">Année</button>
        </div>
        <select id="stats-filtre-hopital" onchange="chargerStats()" 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 hôpitaux</option></select>
        <select id="stats-filtre-type"    onchange="chargerStats()" 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="">Public & Privé</option><option value="public">Publics</option><option value="prive">Privés</option></select>
        <span id="stats-periode-label" class="text-sm text-gray-400 ml-auto"></span>
    </div>
    <div class="grid grid-cols-4 gap-4 mb-6" id="stats-kpis"><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 p-6 border border-gray-100"><h3 class="font-bold text-gray-900 mb-4">📈 Taux d'absentéisme</h3><div id="taux-absenteisme" class="text-5xl font-black text-amber-500">—%</div><div class="mt-4 h-3 bg-gray-100 rounded-full overflow-hidden"><div id="barre-absenteisme" class="h-3 bg-amber-400 rounded-full transition-all duration-1000" style="width:0%"></div></div></div>
        <div class="bg-white rounded-2xl p-6 border border-gray-100"><h3 class="font-bold text-gray-900 mb-4">💳 Taux de paiement</h3><div id="taux-paiement" class="text-5xl font-black text-green-500">—%</div><div class="mt-4 h-3 bg-gray-100 rounded-full overflow-hidden"><div id="barre-paiement" class="h-3 bg-green-400 rounded-full transition-all duration-1000" style="width:0%"></div></div></div>
        <div class="bg-white rounded-2xl p-6 border border-gray-100"><h3 class="font-bold text-gray-900 mb-4">⏱ Temps d'attente moyen</h3><div class="text-5xl font-black text-blue-600" id="temps-attente">— min</div></div>
        <div class="bg-white rounded-2xl p-6 border border-gray-100"><h3 class="font-bold text-gray-900 mb-4">🏆 Top spécialités</h3><div id="stats-specialites"><p class="text-gray-400 text-center py-4">Chargement...</p></div></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">📊 Détail par hôpital</h3><span id="stats-periode-badge" class="px-3 py-1 bg-blue-50 text-blue-600 rounded-full text-xs font-bold"></span></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-bold text-gray-500 uppercase">Hôpital</th>
                <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Type</th>
                <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">RDVs</th>
                <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Confirmés</th>
                <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Payés</th>
                <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Annulés</th>
                <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Taux</th>
            </tr></thead>
            <tbody id="tbody-stats-hopitaux"><tr><td colspan="7" 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="setRevenusPeriode('jour')"    id="rev-btn-jour"    class="rev-p-btn px-4 py-2 text-sm font-semibold bg-blue-600 text-white">Jour</button>
            <button onclick="setRevenusPeriode('semaine')" id="rev-btn-semaine" class="rev-p-btn px-4 py-2 text-sm font-semibold text-gray-500 hover:bg-gray-50">Semaine</button>
            <button onclick="setRevenusPeriode('mois')"    id="rev-btn-mois"    class="rev-p-btn px-4 py-2 text-sm font-semibold text-gray-500 hover:bg-gray-50">Mois</button>
            <button onclick="setRevenusPeriode('annee')"   id="rev-btn-annee"   class="rev-p-btn px-4 py-2 text-sm font-semibold text-gray-500 hover:bg-gray-50">Année</button>
        </div>
        <select id="rev-filtre-hopital" onchange="chargerRevenus()" 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 hôpitaux</option></select>
        <select id="rev-filtre-type"    onchange="chargerRevenus()" 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="">Public & Privé</option><option value="public">Publics</option><option value="prive">Privés</option></select>
        <div class="flex items-center gap-2 ml-auto">
            <input type="date" id="rev-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="rev-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="chargerRevenus()" 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-3 gap-4 mb-6">
        <div class="bg-[#1a1a2e] text-white rounded-2xl p-6"><p class="text-white/60 text-xs uppercase tracking-wide mb-1" id="rev-kpi-label-1">Aujourd'hui</p><p id="rev-kpi-1" class="text-3xl font-black">— FCFA</p><p id="rev-kpi-nb-1" class="text-white/50 text-xs mt-1">0 paiement(s)</p></div>
        <div class="bg-white rounded-2xl p-6 border border-gray-100"><p class="text-gray-400 text-xs uppercase tracking-wide mb-1" id="rev-kpi-label-2">Cette semaine</p><p id="rev-kpi-2" class="text-3xl font-black text-gray-900">— FCFA</p><p id="rev-kpi-nb-2" class="text-gray-400 text-xs mt-1">0 paiement(s)</p></div>
        <div class="bg-white rounded-2xl p-6 border border-gray-100"><p class="text-gray-400 text-xs uppercase tracking-wide mb-1" id="rev-kpi-label-3">Ce mois</p><p id="rev-kpi-3" class="text-3xl font-black text-gray-900">— FCFA</p><p id="rev-kpi-nb-3" class="text-gray-400 text-xs mt-1">0 paiement(s)</p></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 hôpital</h3><span id="rev-periode-badge" class="px-3 py-1 bg-green-50 text-green-600 rounded-full text-xs font-bold"></span></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-bold text-gray-500 uppercase">Hôpital</th>
                <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Type</th>
                <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">RDVs payés</th>
                <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Frais réservation (200 FCFA/RDV)</th>
            </tr></thead>
            <tbody id="tbody-revenus"><tr><td colspan="4" 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="text-right"><p class="text-xs text-gray-400">Frais de réservation collectés</p><p id="rev-total" class="font-black text-[#1a1a2e]">— FCFA</p></div>
        </div>
    </div>
</section>

<!-- ─── PUBLICITÉS ─── -->
<section id="section-pub" 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-gray-50 flex items-center justify-between">
                <h3 class="font-bold text-gray-900">📢 Publicité actuellement diffusée</h3>
                <button onclick="chargerPubActuelle()" class="px-3 py-1.5 bg-gray-100 text-gray-600 rounded-lg text-xs font-semibold hover:bg-gray-200">🔄 Actualiser</button>
            </div>
            <div id="pub-actuelle" class="p-6"><p class="text-gray-400 text-center py-4">Chargement...</p></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 id="form-pub-titre" class="font-bold text-gray-900">➕ Ajouter une publicité</h3>
                <p class="text-xs text-gray-400 mt-0.5">Les slides s'affichent dans l'ordre défini</p>
            </div>
            <div class="p-6 space-y-5">
                <input type="hidden" id="pub-edit-id" />
                <div><label class="block text-sm font-semibold text-gray-600 mb-2">Format</label>
                    <div class="grid grid-cols-4 gap-2">
                        <button id="fmt-texte"       onclick="setFormat('texte')"       class="fmt-btn py-3 rounded-xl border-2 border-[#1a1a2e] bg-blue-50 text-[#1a1a2e] text-xs font-bold flex flex-col items-center gap-1"><span class="text-xl">📝</span>Texte</button>
                        <button id="fmt-image"       onclick="setFormat('image')"       class="fmt-btn py-3 rounded-xl border-2 border-gray-200 bg-gray-50 text-gray-500 text-xs font-bold flex flex-col items-center gap-1"><span class="text-xl">🖼️</span>Image</button>
                        <button id="fmt-cta_hopital" onclick="setFormat('cta_hopital')" class="fmt-btn py-3 rounded-xl border-2 border-gray-200 bg-gray-50 text-gray-500 text-xs font-bold flex flex-col items-center gap-1"><span class="text-xl">🏥</span>CTA RDV</button>
                        <button id="fmt-promo"       onclick="setFormat('promo')"       class="fmt-btn py-3 rounded-xl border-2 border-gray-200 bg-gray-50 text-gray-500 text-xs font-bold flex flex-col items-center gap-1"><span class="text-xl">🎯</span>Promo</button>
                    </div>
                </div>
                <div id="zone-image" class="hidden space-y-3">
                    <label class="block text-sm font-semibold text-gray-600">Image</label>
                    <input id="pub-image-url" type="url" placeholder="https://exemple.com/image.jpg" oninput="previewImageUrl(this.value)" 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 class="text-center text-xs text-gray-400">— ou —</div>
                    <input id="pub-image-fichier" type="file" accept="image/*" onchange="previewFichier(this)" class="w-full px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm" />
                    <div id="image-apercu-zone" class="hidden"><img id="image-apercu-img" src="" class="w-full max-h-44 object-cover rounded-xl border border-gray-100" /></div>
                </div>
                <div id="zone-emoji" class="hidden"><label class="block text-sm font-semibold text-gray-600 mb-1.5">Emoji</label><input id="pub-emoji" type="text" value="📢" maxlength="2" class="w-24 px-4 py-2.5 rounded-xl border-2 border-gray-100 bg-gray-50 text-2xl text-center focus:outline-none focus:border-blue-500" /></div>
                <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Titre <span class="text-red-400">*</span></label><input id="pub-titre" type="text" placeholder="Ex: Campagne vaccination gratuite" 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">Message</label><textarea id="pub-message" rows="2" 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 resize-none"></textarea></div>
                <div class="grid grid-cols-2 gap-4">
                    <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Texte bouton CTA</label><input id="pub-cta-texte" type="text" placeholder="Ex: Prendre un RDV" 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">Action CTA</label><select id="pub-cta-action" 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="">Aucune</option><option value="hopitaux">→ Liste hôpitaux</option><option value="rdv">→ Prendre RDV</option><option value="url">→ URL externe</option></select></div>
                </div>
                <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Lien URL</label><input id="pub-lien" type="url" placeholder="https://..." 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 id="zone-couleurs" class="hidden grid grid-cols-2 gap-4">
                    <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Couleur fond</label><div class="flex gap-2 items-center"><input type="color" id="pub-couleur-fond" value="#0055AA" class="w-10 h-10 rounded-lg border-2 border-gray-200 cursor-pointer p-0.5" oninput="document.getElementById('pub-couleur-fond-txt').value=this.value" /><input type="text" id="pub-couleur-fond-txt" value="#0055AA" maxlength="7" class="flex-1 px-3 py-2 rounded-xl border-2 border-gray-100 bg-gray-50 text-xs font-mono focus:outline-none" oninput="document.getElementById('pub-couleur-fond').value=this.value" /></div></div>
                    <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Couleur texte</label><div class="flex gap-2 items-center"><input type="color" id="pub-couleur-texte" value="#FFFFFF" class="w-10 h-10 rounded-lg border-2 border-gray-200 cursor-pointer p-0.5" oninput="document.getElementById('pub-couleur-texte-txt').value=this.value" /><input type="text" id="pub-couleur-texte-txt" value="#FFFFFF" maxlength="7" class="flex-1 px-3 py-2 rounded-xl border-2 border-gray-100 bg-gray-50 text-xs font-mono focus:outline-none" oninput="document.getElementById('pub-couleur-texte').value=this.value" /></div></div>
                </div>
                <div class="grid grid-cols-3 gap-4">
                    <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Ordre</label><input id="pub-ordre" type="number" value="0" min="0" 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">Date début</label><input id="pub-date-debut" 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">Date fin</label><input id="pub-date-fin" 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>
                <div class="flex gap-3 pt-2">
                    <button onclick="sauvegarderPub()" class="flex-1 py-3 bg-[#1a1a2e] text-white rounded-xl font-bold text-sm hover:bg-gray-900">💾 Sauvegarder</button>
                    <button onclick="desactiverPub()" class="px-5 py-3 bg-red-50 text-red-600 rounded-xl font-bold text-sm hover:bg-red-100 border border-red-100">🚫 Tout désactiver</button>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- ─── PARAMÈTRES ─── -->
<section id="section-parametres" class="p-8 hidden">
    <div class="max-w-lg">
        <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">⚙️ Paramètres globaux</h3>
                <p class="text-xs text-gray-400 mt-0.5">Ces paramètres s'appliquent à toute la plateforme</p>
            </div>
            <div id="parametres-liste" class="p-6 space-y-4">
                <p class="text-gray-400 text-center py-4">Chargement...</p>
            </div>
        </div>
    </div>
</section>

<!-- ─── DIRECTEURS RÉGIONAUX ─── -->
<section id="section-directeurs" class="p-8 hidden">
    <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">🌍 Directeurs régionaux</h3>
            <button onclick="ouvrirModalDirecteur()" class="px-4 py-2 bg-blue-600 text-white rounded-xl text-sm font-bold hover:bg-blue-700">+ Nouveau directeur</button>
        </div>
        <div id="liste-directeurs" class="p-6 space-y-3">
            <p class="text-gray-400 text-center py-8">Chargement...</p>
        </div>
    </div>

    <!-- modal directeur -->
    <div id="modal-directeur" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl w-full max-w-lg shadow-2xl overflow-y-auto max-h-[90vh]">
            <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
                <h3 id="modal-directeur-titre" class="font-bold text-gray-900">Nouveau directeur régional</h3>
                <button onclick="fermerModalDirecteur()" class="text-gray-400 hover:text-gray-600 text-xl">✕</button>
            </div>
            <div class="p-6 space-y-4">
                <input type="hidden" id="directeur-edit-id" />
                <div class="grid grid-cols-2 gap-4">
                    <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Nom *</label><input id="directeur-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">Prénom *</label><input id="directeur-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">Téléphone *</label><input id="directeur-telephone" 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">Mot de passe *</label><input id="directeur-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>
                <div>
                    <label class="block text-sm font-semibold text-gray-600 mb-2">
                        Hôpitaux assignés *
                        <span class="text-xs font-normal text-gray-400 ml-1">(Ctrl+clic pour sélection multiple)</span>
                    </label>
                    <select id="directeur-hopitaux" multiple
                        class="w-full px-3 py-2 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm focus:outline-none focus:border-blue-500"
                        style="min-height:150px">
                    </select>
                </div>
                <div class="flex gap-3 pt-2">
                    <button onclick="fermerModalDirecteur()" class="flex-1 py-3 rounded-xl border-2 border-gray-200 text-gray-600 font-semibold text-sm">Annuler</button>
                    <button onclick="sauvegarderDirecteur()" class="flex-1 py-3 rounded-xl bg-blue-600 text-white font-bold text-sm hover:bg-blue-700">Sauvegarder</button>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- ─── PROFIL ─── -->
<section id="section-profil" class="p-8 hidden">
    <div class="max-w-lg"><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">👤 Mon profil</h3></div>
        <div class="p-6 space-y-4">
            <div class="grid grid-cols-2 gap-4">
                <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Nom</label><input id="profil-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">Prénom</label><input id="profil-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>
            <div><label class="block text-sm font-semibold text-gray-600 mb-1.5">Téléphone</label><input id="profil-telephone" 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">Email</label><input id="profil-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><label class="block text-sm font-semibold text-gray-600 mb-1.5">Nouveau mot de passe</label><input id="profil-mdp" type="password" placeholder="Laisser vide pour ne pas changer" 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>
            <button onclick="sauvegarderProfil()" class="w-full py-3 bg-blue-600 text-white rounded-xl font-bold text-sm hover:bg-blue-700">💾 Sauvegarder</button>
        </div>
    </div></div>
</section>

    </main>
</div>

<script>
const API_BASE = 'https://senrdv.sendigital.org/api';
let hopitauxData     = [];
let utilisateursData = [];
let formatPub        = 'texte';
let statsPeriode     = 'jour';
let revenusPeriode   = 'jour';
let servicesHopitalId = null;

// ── INIT ──
window.addEventListener('DOMContentLoaded', () => {
    const user = getUser();
    if (!user || user.role !== 'super_admin') { window.location.href = '/web/index.php'; return; }
    document.getElementById('user-nom').textContent = `${user.prenom} ${user.nom}`;
    afficherSection('national');
    setFormat('texte');
});

function seDeconnecter() { localStorage.removeItem('token'); localStorage.removeItem('user'); window.location.href = '/web/index.php'; }

// ── NAVIGATION ──
function afficherSection(section) {
    ['national','hopitaux','utilisateurs','directeurs','stats','revenus','pub','parametres','profil'].forEach(s => {
        const el = document.getElementById('section-' + s);
        if (el) el.classList.add('hidden');
    });
    const sectionEl = document.getElementById('section-' + section);
    if (sectionEl) sectionEl.classList.remove('hidden');
    
    const titres = {
        national:'Vue Nationale',
        hopitaux:'Annuaire des Hôpitaux',
        utilisateurs:'Gestion des Utilisateurs',
        directeurs:'Directeurs Régionaux',
        stats:'Statistiques Nationales',
        revenus:'Suivi des Revenus',
        pub:'Gestion des Publicités',
        parametres:'Paramètres',
        profil:'Mon Profil'
    };
    document.getElementById('page-titre').textContent = titres[section] || '';
    
    if (section === 'national')     chargerNational();
    if (section === 'hopitaux')     chargerHopitaux();
    if (section === 'utilisateurs') chargerUtilisateurs();
    if (section === 'directeurs')   chargerDirecteurs();
    if (section === 'stats')        { peuplerFiltresHopitaux(); chargerStats(); }
    if (section === 'revenus')      { peuplerFiltresHopitaux(); chargerRevenus(); }
    if (section === 'pub')          chargerPubActuelle();
    if (section === 'parametres')   chargerParametres();
    if (section === 'profil')       afficherProfilSection();
}

// ── TOAST + CONFIRM ──
function toast(msg, type='success') {
    const el=document.getElementById('toast'), inner=document.getElementById('toast-inner');
    inner.textContent=msg; inner.className=`px-5 py-3 rounded-2xl shadow-xl text-sm font-semibold text-white ${type==='error'?'bg-red-500':'bg-green-500'}`;
    el.classList.remove('hidden'); setTimeout(()=>el.classList.add('hidden'),3500);
}
function confirmerAction(msg, cb) {
    document.getElementById('modal-msg').textContent=msg;
    document.getElementById('modal-confirm').classList.remove('hidden');
    document.getElementById('modal-ok').onclick=()=>{ document.getElementById('modal-confirm').classList.add('hidden'); cb(); };
}

// ── HELPERS PÉRIODE ──
function getPeriodeDates(periode) {
    const now=new Date(), pad=n=>String(n).padStart(2,'0'), fmt=d=>`${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`;
    if (periode==='jour')    return { debut:fmt(now), fin:fmt(now), label:'Aujourd\'hui · '+now.toLocaleDateString('fr-FR',{weekday:'long',day:'numeric',month:'long'}) };
    if (periode==='semaine') { const l=new Date(now); l.setDate(now.getDate()-now.getDay()+1); const d=new Date(l); d.setDate(l.getDate()+6); return { debut:fmt(l), fin:fmt(d), label:`Semaine du ${l.toLocaleDateString('fr-FR',{day:'numeric',month:'long'})}` }; }
    if (periode==='mois') return { 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'}) };
    return { debut:`${now.getFullYear()}-01-01`, fin:`${now.getFullYear()}-12-31`, label:`Année ${now.getFullYear()}` };
}
function setPeriodeBtns(prefix, active) {
    ['jour','semaine','mois','annee'].forEach(x => {
        const btn=document.getElementById(`${prefix}-btn-${x}`); if(!btn)return;
        btn.className=x===active?`${prefix.includes('rev')?'rev':'stats'}-p-btn px-4 py-2 text-sm font-semibold bg-blue-600 text-white`:`${prefix.includes('rev')?'rev':'stats'}-p-btn px-4 py-2 text-sm font-semibold text-gray-500 hover:bg-gray-50`;
    });
}
function peuplerFiltresHopitaux() {
    const opts='<option value="">Tous les hôpitaux</option>'+hopitauxData.map(h=>`<option value="${h.id}">${h.nom}</option>`).join('');
    ['stats-filtre-hopital','rev-filtre-hopital'].forEach(id=>{ const el=document.getElementById(id); if(el)el.innerHTML=opts; });
}

// ── NATIONAL ──
async function chargerNational() {
    try {
        const [resStats,resH]=await Promise.all([api('/admin/stats.php'),api('/hopitaux/liste.php')]);
        if (resH.succes) hopitauxData=resH.hopitaux;
        if (resStats.succes) {
            document.getElementById('stat-hopitaux').textContent=hopitauxData.length;
            document.getElementById('stat-patients').textContent=resStats.stats?.patients??'—';
            document.getElementById('stat-rdvs').textContent=resStats.stats?.rdvs_mois??'—';
            document.getElementById('stat-revenus').textContent=resStats.stats?.revenus_mois?Number(resStats.stats.revenus_mois).toLocaleString('fr-FR'):'—';
        }
        document.getElementById('tableau-national').innerHTML=hopitauxData.length===0?'<p class="text-gray-400">Aucun hôpital.</p>':`<table class="w-full text-sm"><thead class="bg-gray-50 border-y border-gray-100"><tr><th class="px-4 py-2 text-left text-xs font-bold text-gray-500 uppercase">Hôpital</th><th class="px-4 py-2 text-left text-xs font-bold text-gray-500 uppercase">RDVs</th><th class="px-4 py-2 text-left text-xs font-bold text-gray-500 uppercase">Services</th><th class="px-4 py-2 text-left text-xs font-bold text-gray-500 uppercase">Type</th></tr></thead><tbody class="divide-y divide-gray-50">${hopitauxData.map(h=>`<tr><td class="px-4 py-3 font-semibold text-gray-800">${h.type==='public'?'🏥':'🏪'} ${h.nom}</td><td class="px-4 py-3 text-gray-500">${h.nb_rdvs??0}</td><td class="px-4 py-3 text-gray-500">${h.nb_services??0}</td><td class="px-4 py-3"><span class="px-2 py-1 rounded-full text-xs font-semibold ${h.type==='public'?'bg-blue-50 text-blue-700':'bg-orange-50 text-orange-700'}">${h.type==='public'?'Public':'Privé'}</span></td></tr>`).join('')}</tbody></table>`;
    } catch(e) { console.log(e); }
}

// ── HÔPITAUX CRUD ──
async function chargerHopitaux() {
    const data=await api('/admin/hopitaux.php');
    if (data.succes) { hopitauxData=data.hopitaux; afficherHopitaux(hopitauxData); }
}
function afficherHopitaux(liste) {
    document.getElementById('tbody-hopitaux').innerHTML=!liste.length?'<tr><td colspan="6" class="text-center py-8 text-gray-400">Aucun hôpital</td></tr>':
    liste.map(h=>`<tr class="hover:bg-gray-50 border-b border-gray-50">
        <td class="px-6 py-4"><div class="flex items-center gap-2"><span class="text-xl">${h.type==='public'?'🏥':'🏪'}</span><p class="font-semibold text-gray-900 text-sm">${h.nom}</p></div></td>
        <td class="px-6 py-4 text-sm text-gray-500">📍 ${h.ville||''}, ${h.region||''}</td>
        <td class="px-6 py-4"><span class="px-2.5 py-1 rounded-full text-xs font-semibold ${h.type==='public'?'bg-blue-50 text-blue-700':'bg-orange-50 text-orange-700'}">${h.type==='public'?'Public':'Privé'}</span></td>
        <td class="px-6 py-4">
            <button onclick="ouvrirServices(${h.id},'${h.nom.replace(/'/g,"\\'")}') "
                class="flex items-center gap-1.5 px-3 py-1.5 bg-green-50 text-green-700 rounded-lg text-xs font-bold hover:bg-green-100">
                🩺 <span>${h.nb_services??0} service(s)</span>
            </button>
        </td>
        <td class="px-6 py-4 text-sm text-gray-400">${h.telephone||'—'}</td>
        <td class="px-6 py-4"><div class="flex gap-2">
            <button onclick='modifierHopital(${JSON.stringify(h)})' class="px-3 py-1.5 bg-blue-50 text-blue-700 rounded-lg text-xs font-bold hover:bg-blue-100">✏️</button>
            <button onclick="supprimerHopital(${h.id},'${h.nom.replace(/'/g,"\\'")}') " class="px-3 py-1.5 bg-red-50 text-red-600 rounded-lg text-xs font-bold hover:bg-red-100">🗑️</button>
        </div></td>
    </tr>`).join('');
}
function filtrerHopitaux() {
    const r=document.getElementById('search-hopital').value.toLowerCase(), t=document.getElementById('filter-type').value;
    afficherHopitaux(hopitauxData.filter(h=>(!r||h.nom.toLowerCase().includes(r)||(h.ville||'').toLowerCase().includes(r))&&(!t||h.type===t)));
}
function ouvrirModalHopital() {
    ['hopital-id','hopital-nom-input','hopital-telephone','hopital-ville','hopital-adresse','hopital-email'].forEach(id=>document.getElementById(id).value='');
    document.getElementById('hopital-type').value='public'; document.getElementById('hopital-region').value='Dakar';
    document.getElementById('modal-hopital-titre').textContent='Ajouter un hôpital';
    document.getElementById('modal-hopital').classList.remove('hidden');
}
function modifierHopital(h) {
    document.getElementById('hopital-id').value=h.id; document.getElementById('hopital-nom-input').value=h.nom;
    document.getElementById('hopital-type').value=h.type; document.getElementById('hopital-telephone').value=h.telephone||'';
    document.getElementById('hopital-ville').value=h.ville||''; document.getElementById('hopital-region').value=h.region||'Dakar';
    document.getElementById('hopital-adresse').value=h.adresse||''; document.getElementById('hopital-email').value=h.email||'';
    document.getElementById('modal-hopital-titre').textContent='Modifier l\'hôpital';
    document.getElementById('modal-hopital').classList.remove('hidden');
}
function fermerModalHopital() { document.getElementById('modal-hopital').classList.add('hidden'); }
async function sauvegarderHopital() {
    const id=document.getElementById('hopital-id').value, nom=document.getElementById('hopital-nom-input').value.trim();
    if (!nom) { toast('Nom obligatoire','error'); return; }
    const body={nom,type:document.getElementById('hopital-type').value,telephone:document.getElementById('hopital-telephone').value,ville:document.getElementById('hopital-ville').value,region:document.getElementById('hopital-region').value,adresse:document.getElementById('hopital-adresse').value,email:document.getElementById('hopital-email').value};
    if (id) body.id=id;
    const data=await api('/admin/hopitaux.php',{method:id?'PUT':'POST',body:JSON.stringify(body)});
    if (data.succes) { toast(id?'Hôpital modifié ✅':'Hôpital ajouté ✅'); fermerModalHopital(); chargerHopitaux(); } else toast(data.erreur||'Erreur','error');
}
async function supprimerHopital(id,nom) {
    confirmerAction(`Supprimer "${nom}" ?`, async()=>{
        const data=await api(`/admin/hopitaux.php?id=${id}`,{method:'DELETE'});
        if (data.succes) { toast('Hôpital supprimé'); chargerHopitaux(); } else toast(data.erreur||'Erreur','error');
    });
}

// ── SERVICES CRUD ──
async function ouvrirServices(hopitalId, hopitalNom) {
    servicesHopitalId = hopitalId;
    document.getElementById('services-hopital-nom').textContent = hopitalNom;
    document.getElementById('modal-services').classList.remove('hidden');
    resetFormService();
    await chargerServices();
}
function fermerModalServices() {
    document.getElementById('modal-services').classList.add('hidden');
    servicesHopitalId = null;
    resetFormService();
}
async function chargerServices() {
    if (!servicesHopitalId) return;
    const data = await api(`/admin/services.php?hopital_id=${servicesHopitalId}`);
    const el   = document.getElementById('services-liste');
    if (!data.succes || !data.services.length) {
        el.innerHTML=`<div class="text-center py-8 text-gray-400"><span class="text-3xl">🩺</span><p class="font-semibold mt-2">Aucun service créé</p><p class="text-xs mt-1">Ajoutez le premier service ci-dessous</p></div>`;
        return;
    }
    el.innerHTML = data.services.map(s=>`
        <div class="bg-gray-50 rounded-xl p-4 border border-gray-100 flex items-center gap-4">
            <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 min-w-0">
                <div class="flex items-center gap-2 flex-wrap">
                    <p class="font-bold text-gray-900 text-sm">${s.nom}</p>
                    <span class="px-2 py-0.5 rounded-full text-xs font-semibold ${s.actif==1?'bg-green-100 text-green-700':'bg-red-100 text-red-500'}">${s.actif==1?'Actif':'Inactif'}</span>
                </div>
                ${s.description?`<p class="text-xs text-gray-400 mt-0.5 truncate">${s.description}</p>`:''}
                <div class="flex items-center gap-3 mt-1 flex-wrap">
                    <span class="text-xs text-gray-500">📅 ${s.quota_rdv_jour} RDV/jour</span>
                    <span class="text-xs text-gray-500">⏱ ${s.duree_consultation} min</span>
                    <span class="text-xs text-gray-500">👤 ${s.nb_gerants} gérant(s)</span>
                    <span class="text-xs text-gray-500">🕐 ${s.nb_creneaux} créneau(x)</span>
                </div>
            </div>
            <div class="flex gap-2 flex-shrink-0">
                <button onclick='modifierService(${JSON.stringify(s).replace(/'/g,"&#39;")})' class="px-3 py-1.5 bg-blue-50 text-blue-700 rounded-lg text-xs font-bold hover:bg-blue-100">✏️</button>
                <button onclick="toggleService(${s.id},${s.actif})"
                    class="px-3 py-1.5 rounded-lg text-xs font-bold ${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('');
}
function modifierService(s) {
    document.getElementById('service-edit-id').value      = s.id;
    document.getElementById('service-nom').value          = s.nom;
    document.getElementById('service-description').value  = s.description||'';
    document.getElementById('service-quota').value        = s.quota_rdv_jour;
    document.getElementById('service-duree').value        = s.duree_consultation;
    document.getElementById('form-service-titre').textContent  = '✏️ Modifier le service';
    document.getElementById('btn-service-label').textContent   = 'Enregistrer les modifications';
    document.getElementById('btn-annuler-service').classList.remove('hidden');
    document.getElementById('form-service-titre').scrollIntoView({ behavior:'smooth', block:'nearest' });
}
function resetFormService() {
    document.getElementById('service-edit-id').value      = '';
    document.getElementById('service-nom').value          = '';
    document.getElementById('service-description').value  = '';
    document.getElementById('service-quota').value        = '20';
    document.getElementById('service-duree').value        = '30';
    document.getElementById('form-service-titre').textContent = '➕ Ajouter un service';
    document.getElementById('btn-service-label').textContent  = 'Ajouter le service';
    document.getElementById('btn-annuler-service').classList.add('hidden');
}
async function sauvegarderService() {
    const nom   = document.getElementById('service-nom').value.trim();
    const quota = document.getElementById('service-quota').value;
    const duree = document.getElementById('service-duree').value;
    const id    = document.getElementById('service-edit-id').value;
    if (!nom)   { toast('Nom du service obligatoire','error'); return; }
    if (!quota) { toast('Quota RDV/jour obligatoire','error'); return; }
    if (!duree) { toast('Durée de consultation obligatoire','error'); return; }
    const body = {
        hopital_id: servicesHopitalId,
        nom, quota_rdv_jour: parseInt(quota), duree_consultation: parseInt(duree),
        description: document.getElementById('service-description').value.trim()||null,
    };
    if (id) body.id = id;
    const data = await api('/admin/services.php', { method: id?'PUT':'POST', body: JSON.stringify(body) });
    if (data.succes) {
        toast(id?'✅ Service modifié !':'✅ Service créé !');
        resetFormService();
        await chargerServices();
        chargerHopitaux(); // màj compteur nb_services dans le tableau
    } else toast(data.erreur||'Erreur','error');
}
async function toggleService(id, actif) {
    if (actif == 1) {
        confirmerAction('Désactiver ce service ? Les futurs RDVs ne pourront plus être pris.', async () => {
            const data = await api(`/admin/services.php?id=${id}&hopital_id=${servicesHopitalId}`, { method:'DELETE' });
            if (data.succes) { toast('Service désactivé'); chargerServices(); chargerHopitaux(); }
            else toast(data.erreur||'Erreur','error');
        });
    } else {
        const data = await api('/admin/services.php', { method:'PUT', body: JSON.stringify({ id, hopital_id: servicesHopitalId, actif:1 }) });
        if (data.succes) { toast('✅ Service réactivé'); chargerServices(); chargerHopitaux(); }
        else toast(data.erreur||'Erreur','error');
    }
}

// ── UTILISATEURS CRUD ──
async function chargerUtilisateurs() {
    const data=await api('/admin/staff.php');
    if (data.succes) { utilisateursData=data.staff; afficherUtilisateurs(utilisateursData); }
}
function afficherUtilisateurs(liste) {
    const roles={admin_hopital:'Admin hôpital',gerant:'Gérant',patient:'Patient',super_admin:'Super Admin'};
    document.getElementById('tbody-utilisateurs').innerHTML=!liste.length?'<tr><td colspan="6" class="text-center py-8 text-gray-400">Aucun utilisateur</td></tr>':
    liste.map(u=>{
        const servicesHtml=u.role==='gerant'&&u.services?.length?u.services.map(s=>`<span class="px-2 py-0.5 bg-blue-50 text-blue-700 rounded-full text-xs font-semibold">${s.service_nom}</span>`).join(' '):'<span class="text-gray-400 text-xs">—</span>';
        return `<tr class="hover:bg-gray-50 border-b border-gray-50">
            <td class="px-6 py-4"><p class="font-semibold text-gray-900 text-sm">${u.prenom} ${u.nom}</p><p class="text-xs text-gray-400">${u.telephone}</p></td>
            <td class="px-6 py-4"><span class="px-2.5 py-1 rounded-full text-xs font-bold ${u.role==='admin_hopital'?'bg-purple-50 text-purple-700':u.role==='gerant'?'bg-blue-50 text-blue-700':'bg-gray-100 text-gray-600'}">${roles[u.role]||u.role}</span></td>
            <td class="px-6 py-4 text-sm text-gray-500">${u.hopital_nom||'—'}</td>
            <td class="px-6 py-4"><div class="flex flex-wrap gap-1">${servicesHtml}</div></td>
            <td class="px-6 py-4"><span class="px-2.5 py-1 rounded-full text-xs font-semibold ${u.actif==1?'bg-green-50 text-green-700':'bg-red-50 text-red-500'}">${u.actif==1?'Actif':'Inactif'}</span></td>
            <td class="px-6 py-4"><div class="flex gap-2">
                <button onclick='modifierUtilisateur(${JSON.stringify(u).replace(/'/g,"&#39;")})' class="px-3 py-1.5 bg-blue-50 text-blue-700 rounded-lg text-xs font-bold hover:bg-blue-100">✏️</button>
                <button onclick="toggleUser(${u.id},${u.actif})" class="px-3 py-1.5 rounded-lg text-xs font-bold ${u.actif==1?'bg-red-50 text-red-500 hover:bg-red-100':'bg-green-50 text-green-600 hover:bg-green-100'}">${u.actif==1?'Désactiver':'Activer'}</button>
            </div></td>
        </tr>`;
    }).join('');
}
function filtrerUtilisateurs() {
    const r=document.getElementById('search-user').value.toLowerCase(), role=document.getElementById('filter-role').value;
    afficherUtilisateurs(utilisateursData.filter(u=>(!r||`${u.nom} ${u.prenom} ${u.telephone}`.toLowerCase().includes(r))&&(!role||u.role===role)));
}
async function ouvrirModalUtilisateur() {
    document.getElementById('user-edit-id').value='';
    ['user-nom-input','user-prenom-input','user-telephone-input','user-email-input','user-mdp-input'].forEach(id=>document.getElementById(id).value='');
    document.getElementById('user-role-input').value='admin_hopital'; document.getElementById('user-actif-input').value='1';
    document.getElementById('modal-user-titre').textContent='Créer un utilisateur';
    document.getElementById('champ-mot-de-passe').classList.remove('hidden');
    await chargerHopitauxSelect(); toggleChampsRole();
    document.getElementById('modal-utilisateur').classList.remove('hidden');
}
async function modifierUtilisateur(u) {
    document.getElementById('user-edit-id').value=u.id; document.getElementById('user-nom-input').value=u.nom;
    document.getElementById('user-prenom-input').value=u.prenom; document.getElementById('user-telephone-input').value=u.telephone;
    document.getElementById('user-email-input').value=u.email||''; document.getElementById('user-role-input').value=u.role;
    document.getElementById('user-actif-input').value=u.actif; document.getElementById('user-mdp-input').value='';
    document.getElementById('modal-user-titre').textContent='Modifier l\'utilisateur';
    await chargerHopitauxSelect(u.hopital_id); toggleChampsRole();
    if (u.role==='gerant'&&u.services?.length) {
        await chargerServicesSelect();
        const ids=u.services.map(s=>String(s.service_id));
        Array.from(document.getElementById('user-services-input').options).forEach(opt=>{ opt.selected=ids.includes(opt.value); });
        majCompteurServices();
    }
    document.getElementById('modal-utilisateur').classList.remove('hidden');
}
function fermerModalUtilisateur() { document.getElementById('modal-utilisateur').classList.add('hidden'); }
function toggleChampsRole() {
    const role=document.getElementById('user-role-input').value;
    document.getElementById('champ-hopital').classList.toggle('hidden', role==='patient');
    document.getElementById('champ-services').classList.toggle('hidden', role!=='gerant');
    if (role!=='gerant') { document.getElementById('user-services-input').innerHTML='<option disabled>-- Choisir d\'abord un hôpital --</option>'; document.getElementById('services-hint').classList.add('hidden'); }
}
async function chargerHopitauxSelect(selectedId=null) {
    if (!hopitauxData.length) { const d=await api('/admin/hopitaux.php'); if(d.succes)hopitauxData=d.hopitaux; }
    document.getElementById('user-hopital-input').innerHTML='<option value="">-- Choisir un hôpital --</option>'+hopitauxData.map(h=>`<option value="${h.id}"${selectedId==h.id?' selected':''}>${h.nom}</option>`).join('');
}
async function chargerServicesSelect() {
    const hopId=document.getElementById('user-hopital-input').value;
    const select=document.getElementById('user-services-input'), hint=document.getElementById('services-hint');
    if (!hopId) { select.innerHTML='<option disabled>-- Choisir d\'abord un hôpital --</option>'; hint.classList.add('hidden'); return; }
    select.innerHTML='<option disabled>Chargement...</option>';
    const data=await api(`/admin/services.php?hopital_id=${hopId}`);
    if (!data.succes||!data.services?.length) { select.innerHTML='<option disabled>Aucun service dans cet hôpital</option>'; return; }
    select.innerHTML=data.services.map(s=>`<option value="${s.id}">${s.nom}</option>`).join('');
    hint.classList.remove('hidden'); majCompteurServices();
}
function majCompteurServices() {
    document.getElementById('services-count').textContent=Array.from(document.getElementById('user-services-input').options).filter(o=>o.selected).length;
}
async function sauvegarderUtilisateur() {
    const id=document.getElementById('user-edit-id').value, role=document.getElementById('user-role-input').value;
    const body={nom:document.getElementById('user-nom-input').value.trim(),prenom:document.getElementById('user-prenom-input').value.trim(),telephone:document.getElementById('user-telephone-input').value.trim(),email:document.getElementById('user-email-input').value.trim()||null,role,hopital_id:document.getElementById('user-hopital-input').value||null,actif:document.getElementById('user-actif-input').value};
    if (!body.nom||!body.prenom||!body.telephone) { toast('Champs obligatoires manquants','error'); return; }
    if (role==='gerant') {
        body.service_ids=Array.from(document.getElementById('user-services-input').options).filter(o=>o.selected).map(o=>parseInt(o.value));
        if (!body.service_ids.length) { toast('Sélectionnez au moins un service pour le gérant','error'); return; }
    }
    const mdp=document.getElementById('user-mdp-input').value; if(mdp)body.mot_de_passe=mdp;
    if (id) body.id=id;
    const data=await api('/admin/staff.php',{method:id?'PUT':'POST',body:JSON.stringify(body)});
    if (data.succes) { toast(id?'Modifié ✅':'Créé ✅'); fermerModalUtilisateur(); chargerUtilisateurs(); } else toast(data.erreur||'Erreur','error');
}
async function toggleUser(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é');chargerUtilisateurs();}
}

// ── STATISTIQUES ──
function setStatsPeriode(p){statsPeriode=p;setPeriodeBtns('stats',p);chargerStats();}
async function chargerStats(){
    const {debut,fin,label}=getPeriodeDates(statsPeriode),hopId=document.getElementById('stats-filtre-hopital')?.value||'',type=document.getElementById('stats-filtre-type')?.value||'';
    document.getElementById('stats-periode-label').textContent=label; document.getElementById('stats-periode-badge').textContent=label;
    let url=`/admin/stats.php?debut=${debut}&fin=${fin}`; if(hopId)url+=`&hopital_id=${hopId}`; if(type)url+=`&type=${type}`;
    const data=await api(url); if(!data.succes)return;
    const s=data.stats||{},total=s.rdvs_total||0;
    document.getElementById('stats-kpis').innerHTML=`<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 mb-1">Total RDVs</p><p class="text-3xl font-black text-blue-600">${total}</p><p class="text-xs text-gray-400 mt-1">${label}</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 mb-1">Tickets payés</p><p class="text-3xl font-black text-green-600">${s.tickets_payes||0}</p><p class="text-xs text-gray-400 mt-1">${total?Math.round((s.tickets_payes||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-amber-500"><p class="text-xs text-gray-400 uppercase mb-1">Taux absentéisme</p><p class="text-3xl font-black text-amber-500">${s.taux_absenteisme||0}%</p></div><div class="bg-white rounded-2xl p-6 border border-gray-100 border-t-4 border-t-purple-500"><p class="text-xs text-gray-400 uppercase mb-1">Hôpitaux actifs</p><p class="text-3xl font-black text-purple-600">${hopitauxData.length}</p></div>`;
    document.getElementById('taux-absenteisme').textContent=(s.taux_absenteisme||0)+'%'; document.getElementById('taux-paiement').textContent=(s.taux_paiement||0)+'%'; document.getElementById('temps-attente').textContent=(s.temps_attente_moyen||'—')+' min';
    setTimeout(()=>{document.getElementById('barre-absenteisme').style.width=(s.taux_absenteisme||0)+'%';document.getElementById('barre-paiement').style.width=(s.taux_paiement||0)+'%';},100);
    const sp=s.top_specialites||[],el=document.getElementById('stats-specialites');
    if(!sp.length)el.innerHTML='<p class="text-gray-400 text-center">Aucune donnée</p>';
    else{const max=sp[0]?.count||1;el.innerHTML=sp.slice(0,5).map((s,i)=>`<div class="flex items-center gap-3 mb-2"><span class="text-xs font-black text-gray-400 w-4">#${i+1}</span><div class="flex-1"><div class="flex justify-between mb-0.5"><span class="text-sm text-gray-700">${s.nom}</span><span class="text-xs font-bold text-blue-600">${s.count}</span></div><div class="h-1 bg-gray-100 rounded-full"><div class="h-1 bg-blue-400 rounded-full" style="width:${s.count/max*100}%"></div></div></div></div>`).join('');}
    const ph=data.par_hopital||[];
    document.getElementById('tbody-stats-hopitaux').innerHTML=!ph.length?hopitauxData.filter(h=>(!hopId||h.id==hopId)&&(!type||h.type===type)).map(h=>`<tr class="border-b border-gray-50"><td class="px-6 py-3 font-semibold text-gray-900 text-sm">${h.type==='public'?'🏥':'🏪'} ${h.nom}</td><td class="px-6 py-3"><span class="px-2 py-1 rounded-full text-xs font-semibold ${h.type==='public'?'bg-blue-50 text-blue-700':'bg-orange-50 text-orange-700'}">${h.type==='public'?'Public':'Privé'}</span></td><td colspan="5" class="px-6 py-3 text-sm text-gray-400">—</td></tr>`).join(''):ph.map(h=>{const taux=h.total>0?Math.round(h.confirmes/h.total*100):0;return`<tr class="border-b border-gray-50 hover:bg-gray-50/50"><td class="px-6 py-3 font-semibold text-gray-900 text-sm">${h.type==='public'?'🏥':'🏪'} ${h.nom}</td><td class="px-6 py-3"><span class="px-2 py-1 rounded-full text-xs font-semibold ${h.type==='public'?'bg-blue-50 text-blue-700':'bg-orange-50 text-orange-700'}">${h.type==='public'?'Public':'Privé'}</span></td><td class="px-6 py-3 text-sm font-bold text-gray-900">${h.total||0}</td><td class="px-6 py-3 text-sm text-blue-600 font-semibold">${h.confirmes||0}</td><td class="px-6 py-3 text-sm text-green-600 font-semibold">${h.payes||0}</td><td class="px-6 py-3 text-sm text-red-500">${h.annules||0}</td><td class="px-6 py-3"><div class="flex items-center gap-2"><div class="flex-1 h-2 bg-gray-100 rounded-full"><div class="h-2 bg-blue-500 rounded-full" style="width:${taux}%"></div></div><span class="text-xs font-bold text-gray-600 w-8">${taux}%</span></div></td></tr>`;}).join('');
}

// ── REVENUS ──
function setRevenusPeriode(p){revenusPeriode=p;setPeriodeBtns('rev',p);document.getElementById('rev-date-debut').value='';document.getElementById('rev-date-fin').value='';chargerRevenus();}
async function chargerRevenus(){
    const dc=document.getElementById('rev-date-debut').value,df=document.getElementById('rev-date-fin').value,hopId=document.getElementById('rev-filtre-hopital')?.value||'',type=document.getElementById('rev-filtre-type')?.value||'';
    let debut,fin,label; if(dc&&df){debut=dc;fin=df;label=`${dc} → ${df}`;}else{const p=getPeriodeDates(revenusPeriode);debut=p.debut;fin=p.fin;label=p.label;}
    document.getElementById('rev-periode-badge').textContent=label;
    const now=new Date(),pad=n=>String(n).padStart(2,'0'),fmt=d=>`${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`;
    const today=fmt(now),lundi=new Date(now),mois1=`${now.getFullYear()}-${pad(now.getMonth()+1)}-01`,moisFin=fmt(new Date(now.getFullYear(),now.getMonth()+1,0));
    lundi.setDate(now.getDate()-now.getDay()+1); const dim=new Date(lundi);dim.setDate(lundi.getDate()+6);
    const [rJ,rS,rM,rP]=await Promise.all([api(`/admin/stats.php?type=revenus&debut=${today}&fin=${today}`),api(`/admin/stats.php?type=revenus&debut=${fmt(lundi)}&fin=${fmt(dim)}`),api(`/admin/stats.php?type=revenus&debut=${mois1}&fin=${moisFin}`),api(`/admin/stats.php?type=revenus&debut=${debut}&fin=${fin}${hopId?'&hopital_id='+hopId:''}${type?'&type='+type:''}`),]);
    [[rJ,'Aujourd\'hui','1'],[rS,'Cette semaine','2'],[rM,'Ce mois','3']].forEach(([res,lbl,id])=>{const m=res.succes?(res.stats?.revenus_total||0):0,nb=res.succes?(res.stats?.nb_paiements||0):0;document.getElementById(`rev-kpi-label-${id}`).textContent=lbl;document.getElementById(`rev-kpi-${id}`).textContent=Number(m).toLocaleString('fr-FR')+' FCFA';document.getElementById(`rev-kpi-nb-${id}`).textContent=`${nb} paiement(s)`;});
    const ph=rP.succes?(rP.par_hopital||[]):[]; let tot=0,totNP=0;
    document.getElementById('tbody-revenus').innerHTML=!ph.length?hopitauxData.filter(h=>(!hopId||h.id==hopId)&&(!type||h.type===type)).map(h=>`<tr class="border-b border-gray-50"><td class="px-6 py-3 font-semibold text-gray-900 text-sm">${h.type==='public'?'🏥':'🏪'} ${h.nom}</td><td class="px-6 py-3"><span class="px-2 py-1 rounded-full text-xs font-semibold ${h.type==='public'?'bg-blue-50 text-blue-700':'bg-orange-50 text-orange-700'}">${h.type==='public'?'Public':'Privé'}</span></td><td colspan="4" class="px-6 py-3 text-sm text-gray-400">0 FCFA</td></tr>`).join(''):ph.map(h=>{const m=Number(h.montant_total||0),np=Math.round(m*.20),ph2=Math.round(m*.80);tot+=m;totNP+=np;return`<tr class="border-b border-gray-50 hover:bg-gray-50/50"><td class="px-6 py-3 font-semibold text-gray-900 text-sm">${h.type==='public'?'🏥':'🏪'} ${h.nom}</td><td class="px-6 py-3"><span class="px-2 py-1 rounded-full text-xs font-semibold ${h.type==='public'?'bg-blue-50 text-blue-700':'bg-orange-50 text-orange-700'}">${h.type==='public'?'Public':'Privé'}</span></td><td class="px-6 py-3 text-sm font-semibold text-gray-900">${h.nb_paiements||0}</td><td class="px-6 py-3 text-sm font-bold text-gray-900">${m.toLocaleString('fr-FR')} FCFA</td><td class="px-6 py-3 text-sm font-bold text-[#1a1a2e]">${np.toLocaleString('fr-FR')} FCFA</td><td class="px-6 py-3 text-sm text-gray-500">${ph2.toLocaleString('fr-FR')} FCFA</td></tr>`;}).join('');
    document.getElementById('rev-total').textContent=tot.toLocaleString('fr-FR')+' FCFA'; document.getElementById('rev-notre-part').textContent=totNP.toLocaleString('fr-FR')+' FCFA';
}

// ── PUBLICITÉS ──
function setFormat(fmt){formatPub=fmt;['texte','image','cta_hopital','promo'].forEach(f=>{document.getElementById(`fmt-${f}`).className=f===fmt?'fmt-btn py-3 rounded-xl border-2 border-[#1a1a2e] bg-blue-50 text-[#1a1a2e] text-xs font-bold flex flex-col items-center gap-1':'fmt-btn py-3 rounded-xl border-2 border-gray-200 bg-gray-50 text-gray-500 text-xs font-bold flex flex-col items-center gap-1';});document.getElementById('zone-image').classList.toggle('hidden',fmt!=='image');document.getElementById('zone-emoji').classList.toggle('hidden',fmt==='image');document.getElementById('zone-couleurs').classList.toggle('hidden',fmt==='image');}
function previewImageUrl(url){const z=document.getElementById('image-apercu-zone'),i=document.getElementById('image-apercu-img');if(url.startsWith('http')){i.src=url;z.classList.remove('hidden');}else z.classList.add('hidden');}
function previewFichier(input){const f=input.files[0];if(!f)return;const r=new FileReader();r.onload=e=>{document.getElementById('pub-image-url').value='';document.getElementById('image-apercu-img').src=e.target.result;document.getElementById('image-apercu-zone').classList.remove('hidden');};r.readAsDataURL(f);}
function resetFormPub(){['pub-edit-id','pub-titre','pub-message','pub-lien','pub-cta-texte','pub-image-url'].forEach(id=>document.getElementById(id).value='');document.getElementById('pub-emoji').value='📢';document.getElementById('pub-cta-action').value='';document.getElementById('pub-couleur-fond').value='#0055AA';document.getElementById('pub-couleur-fond-txt').value='#0055AA';document.getElementById('pub-couleur-texte').value='#FFFFFF';document.getElementById('pub-couleur-texte-txt').value='#FFFFFF';document.getElementById('pub-ordre').value='0';document.getElementById('pub-date-debut').value='';document.getElementById('pub-date-fin').value='';document.getElementById('image-apercu-zone').classList.add('hidden');document.getElementById('form-pub-titre').textContent='➕ Ajouter une publicité';setFormat('texte');}
async function chargerPubActuelle(){const data=await api('/admin/pub.php'),el=document.getElementById('pub-actuelle');if(!data.succes||!data.pubs?.length){el.innerHTML=`<div class="flex items-center gap-3 bg-gray-50 rounded-xl p-4"><span class="text-2xl">📭</span><div><p class="font-semibold text-gray-600">Aucune publicité active</p><p class="text-xs text-gray-400 mt-0.5">Ajoutez une publicité ci-dessous</p></div></div>`;return;}const fmts={texte:'📝 Texte',image:'🖼️ Image',cta_hopital:'🏥 CTA RDV',promo:'🎯 Promo'};el.innerHTML=data.pubs.map(p=>`<div class="flex items-center gap-4 p-4 bg-gray-50 rounded-xl mb-3 last:mb-0"><div class="w-14 h-14 rounded-xl overflow-hidden flex-shrink-0 flex items-center justify-center" style="background:${p.image_url?'#000':(p.couleur_fond||'#0055AA')}">${p.image_url?`<img src="${p.image_url}" class="w-full h-full object-cover" />`:`<span class="text-2xl">${p.emoji||'📢'}</span>`}</div><div class="flex-1 min-w-0"><div class="flex items-center gap-2 mb-1"><span class="text-xs font-bold px-2 py-0.5 bg-blue-100 text-blue-700 rounded-full">${fmts[p.format]||'📝 Texte'}</span><span class="text-xs text-gray-400">Ordre: ${p.ordre}</span></div><p class="font-bold text-sm text-gray-900 truncate">${p.titre}</p>${p.message?`<p class="text-xs text-gray-500 truncate">${p.message}</p>`:''}</div><div class="flex gap-2 flex-shrink-0"><button onclick='modifierPub(${JSON.stringify(p).replace(/'/g,"&#39;")})' class="px-3 py-1.5 bg-blue-50 text-blue-700 rounded-lg text-xs font-bold hover:bg-blue-100">✏️</button><button onclick="desactiverUnePub(${p.id})" class="px-3 py-1.5 bg-red-50 text-red-500 rounded-lg text-xs font-bold hover:bg-red-100">🗑️</button></div></div>`).join('')+`<p class="text-xs text-green-600 font-semibold text-center mt-3">✅ ${data.pubs.length} pub(s) en slides dans l'app</p>`;}
function modifierPub(p){document.getElementById('pub-edit-id').value=p.id;document.getElementById('pub-titre').value=p.titre;document.getElementById('pub-message').value=p.message||'';document.getElementById('pub-lien').value=p.lien||'';document.getElementById('pub-cta-texte').value=p.cta_texte||'';document.getElementById('pub-cta-action').value=p.cta_action||'';document.getElementById('pub-ordre').value=p.ordre||0;document.getElementById('pub-date-debut').value=p.date_debut||'';document.getElementById('pub-date-fin').value=p.date_fin||'';if(p.image_url){document.getElementById('pub-image-url').value=p.image_url;previewImageUrl(p.image_url);}else{document.getElementById('pub-emoji').value=p.emoji||'📢';document.getElementById('pub-couleur-fond').value=p.couleur_fond;document.getElementById('pub-couleur-fond-txt').value=p.couleur_fond;document.getElementById('pub-couleur-texte').value=p.couleur_texte;document.getElementById('pub-couleur-texte-txt').value=p.couleur_texte;}setFormat(p.format||'texte');document.getElementById('form-pub-titre').textContent='✏️ Modifier la publicité';document.getElementById('form-pub-titre').scrollIntoView({behavior:'smooth'});}
async function sauvegarderPub(){const titre=document.getElementById('pub-titre').value.trim();if(!titre){toast('Titre obligatoire','error');return;}const editId=document.getElementById('pub-edit-id').value,fichier=formatPub==='image'?document.getElementById('pub-image-fichier')?.files[0]:null,token=localStorage.getItem('token');let reponse;if(fichier){const fd=new FormData();fd.append('titre',titre);fd.append('message',document.getElementById('pub-message').value.trim());fd.append('lien',document.getElementById('pub-lien').value.trim());fd.append('emoji',document.getElementById('pub-emoji').value||'📢');fd.append('format',formatPub);fd.append('cta_texte',document.getElementById('pub-cta-texte').value.trim());fd.append('cta_action',document.getElementById('pub-cta-action').value);fd.append('couleur_fond',document.getElementById('pub-couleur-fond').value);fd.append('couleur_texte',document.getElementById('pub-couleur-texte').value);fd.append('ordre',document.getElementById('pub-ordre').value);fd.append('date_debut',document.getElementById('pub-date-debut').value);fd.append('date_fin',document.getElementById('pub-date-fin').value);fd.append('image',fichier);if(editId)fd.append('id',editId);reponse=await fetch(`${API_BASE}/admin/pub.php`,{method:editId?'PUT':'POST',headers:{'Authorization':`Bearer ${token}`},body:fd});}else{const payload={titre,message:document.getElementById('pub-message').value.trim(),lien:document.getElementById('pub-lien').value.trim()||null,image_url:formatPub==='image'?(document.getElementById('pub-image-url').value.trim()||null):null,emoji:document.getElementById('pub-emoji').value||null,format:formatPub,cta_texte:document.getElementById('pub-cta-texte').value.trim()||null,cta_action:document.getElementById('pub-cta-action').value||null,couleur_fond:document.getElementById('pub-couleur-fond').value,couleur_texte:document.getElementById('pub-couleur-texte').value,ordre:parseInt(document.getElementById('pub-ordre').value)||0,date_debut:document.getElementById('pub-date-debut').value||null,date_fin:document.getElementById('pub-date-fin').value||null};if(editId)payload.id=editId;reponse=await fetch(`${API_BASE}/admin/pub.php`,{method:editId?'PUT':'POST',headers:{'Authorization':`Bearer ${token}`,'Content-Type':'application/json'},body:JSON.stringify(payload)});}const data=await reponse.json();if(data.succes){toast(editId?'✅ Pub modifiée !':'✅ Pub ajoutée !');resetFormPub();chargerPubActuelle();}else toast(data.erreur||'Erreur','error');}
async function desactiverUnePub(id){confirmerAction('Supprimer cette pub ?',async()=>{const d=await api('/admin/pub.php',{method:'DELETE',body:JSON.stringify({id})});if(d.succes){toast('Supprimée');chargerPubActuelle();}});}
async function desactiverPub(){confirmerAction('Désactiver TOUTES les publicités ?',async()=>{const d=await api('/admin/pub.php',{method:'DELETE'});if(d.succes){toast('Toutes désactivées');chargerPubActuelle();}});}

// ── PARAMÈTRES ──
async function chargerParametres() {
    const data = await api('/admin/parametres.php');
    const el   = document.getElementById('parametres-liste');
    if (!data.succes) { el.innerHTML = '<p class="text-red-400">Erreur chargement</p>'; return; }
    el.innerHTML = data.parametres.map(p => `
        <div class="flex items-center gap-4 p-4 bg-gray-50 rounded-xl border border-gray-100">
            <div class="flex-1">
                <p class="text-sm font-bold text-gray-900">${p.label}</p>
                <p class="text-xs text-gray-400 mt-0.5">Clé : <span class="font-mono">${p.cle}</span></p>
            </div>
            <div class="flex items-center gap-2">
                <input type="number" id="param-${p.cle}" value="${p.valeur}" min="0"
                    class="w-28 px-3 py-2 rounded-xl border-2 border-gray-200 text-sm font-bold text-gray-900 focus:outline-none focus:border-blue-500 text-right" />
                <span class="text-sm text-gray-400 font-semibold">FCFA</span>
                <button onclick="sauvegarderParametre('${p.cle}')"
                    class="px-3 py-2 bg-blue-600 text-white rounded-xl text-xs font-bold hover:bg-blue-700">
                    💾
                </button>
            </div>
        </div>`).join('');
}

async function sauvegarderParametre(cle) {
    const valeur = document.getElementById(`param-${cle}`)?.value;
    if (!valeur || isNaN(valeur) || Number(valeur) < 0) { toast('Valeur invalide', 'error'); return; }
    const data = await api('/admin/parametres.php', { method: 'PUT', body: JSON.stringify({ cle, valeur }) });
    if (data.succes) toast('✅ Paramètre mis à jour !');
    else toast(data.erreur || 'Erreur', 'error');
}


let directeursData = [];
let hopitauxPourDirecteur = [];

// ── DIRECTEURS ──
async function chargerDirecteurs() {
    const data = await api('/admin/directeurs.php');
    if (!data.succes) return;
    directeursData = data.directeurs || [];
    hopitauxPourDirecteur = data.hopitaux || [];

    const el = document.getElementById('liste-directeurs');
    if (!directeursData.length) {
        el.innerHTML = '<p class="text-gray-400 text-center py-4">Aucun directeur régional</p>';
        return;
    }

    el.innerHTML = directeursData.map(d => `
        <div class="flex items-center gap-4 p-4 bg-gray-50 rounded-xl border border-gray-100">
            <div class="w-10 h-10 rounded-xl bg-purple-50 flex items-center justify-center text-lg">🌍</div>
            <div class="flex-1 min-w-0">
                <div class="flex items-center gap-2">
                    <p class="font-bold text-gray-900 text-sm">${d.prenom} ${d.nom}</p>
                    <span class="px-2 py-0.5 rounded-full text-xs font-semibold ${d.actif==1 ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-500'}">${d.actif==1 ? 'Actif' : 'Inactif'}</span>
                </div>
                <p class="text-xs text-gray-400">📞 ${d.telephone}</p>
                <p class="text-xs text-gray-500 mt-1">🏥 ${d.nb_hopitaux || 0} hôpital(s) : ${d.hopitaux_noms || 'Aucun'}</p>
            </div>
            <div class="flex gap-2 flex-shrink-0">
                <button onclick='modifierDirecteur(${JSON.stringify(d).replace(/'/g,"&#39;")})' class="px-3 py-1.5 bg-blue-50 text-blue-700 rounded-lg text-xs font-bold hover:bg-blue-100">✏️</button>
                <button onclick="desactiverDirecteur(${d.id})" class="px-3 py-1.5 bg-red-50 text-red-500 rounded-lg text-xs font-bold hover:bg-red-100">🗑️</button>
            </div>
        </div>
    `).join('');
}

function ouvrirModalDirecteur() {
    document.getElementById('directeur-edit-id').value = '';
    ['directeur-nom','directeur-prenom','directeur-telephone','directeur-mdp'].forEach(id => document.getElementById(id).value = '');
    document.getElementById('modal-directeur-titre').textContent = 'Nouveau directeur régional';
    document.getElementById('directeur-mdp').parentElement.classList.remove('hidden');

    // Remplir le select des hôpitaux
    const select = document.getElementById('directeur-hopitaux');
    select.innerHTML = hopitauxPourDirecteur.map(h => `<option value="${h.id}">${h.nom} (${h.ville || ''})</option>`).join('');
    Array.from(select.options).forEach(o => o.selected = false);

    document.getElementById('modal-directeur').classList.remove('hidden');
}

function modifierDirecteur(d) {
    document.getElementById('directeur-edit-id').value = d.id;
    document.getElementById('directeur-nom').value = d.nom;
    document.getElementById('directeur-prenom').value = d.prenom;
    document.getElementById('directeur-telephone').value = d.telephone;
    document.getElementById('directeur-mdp').value = '';
    document.getElementById('modal-directeur-titre').textContent = 'Modifier le directeur régional';

    const select = document.getElementById('directeur-hopitaux');
    select.innerHTML = hopitauxPourDirecteur.map(h => `<option value="${h.id}">${h.nom} (${h.ville || ''})</option>`).join('');
    const ids = d.hopitaux_ids ? d.hopitaux_ids.map(String) : [];
    Array.from(select.options).forEach(o => { o.selected = ids.includes(o.value); });

    document.getElementById('modal-directeur').classList.remove('hidden');
}

function fermerModalDirecteur() {
    document.getElementById('modal-directeur').classList.add('hidden');
}

async function sauvegarderDirecteur() {
    const id = document.getElementById('directeur-edit-id').value;
    const nom = document.getElementById('directeur-nom').value.trim();
    const prenom = document.getElementById('directeur-prenom').value.trim();
    const telephone = document.getElementById('directeur-telephone').value.trim();
    const mdp = document.getElementById('directeur-mdp').value;

    if (!nom || !prenom || !telephone) { toast('Champs obligatoires manquants', 'error'); return; }
    if (!id && !mdp) { toast('Mot de passe obligatoire', 'error'); return; }

    const hopitauxIds = Array.from(document.getElementById('directeur-hopitaux').selectedOptions).map(o => parseInt(o.value));
    if (!hopitauxIds.length) { toast('Sélectionnez au moins un hôpital', 'error'); return; }

    const body = { nom, prenom, telephone, hopitaux_ids: hopitauxIds };
    if (id) body.id = id;
    if (mdp) body.mot_de_passe = mdp;

    const data = await api('/admin/directeurs.php', {
        method: id ? 'PUT' : 'POST',
        body: JSON.stringify(body)
    });

    if (data.succes) {
        toast(id ? '✅ Directeur modifié' : '✅ Directeur créé');
        fermerModalDirecteur();
        chargerDirecteurs();
    } else {
        toast(data.erreur || 'Erreur', 'error');
    }
}

async function desactiverDirecteur(id) {
    confirmerAction('Désactiver ce directeur régional ?', async () => {
        const data = await api('/admin/directeurs.php?id=' + id, { method: 'DELETE' });
        if (data.succes) { toast('Directeur désactivé'); chargerDirecteurs(); }
        else toast(data.erreur || 'Erreur', 'error');
    });
}

// ── PROFIL ──
function afficherProfilSection(){const u=getUser();if(!u)return;document.getElementById('profil-nom').value=u.nom||'';document.getElementById('profil-prenom').value=u.prenom||'';document.getElementById('profil-telephone').value=u.telephone||'';document.getElementById('profil-email').value=u.email||'';document.getElementById('profil-mdp').value='';}
async function sauvegarderProfil(){const body={nom:document.getElementById('profil-nom').value.trim(),prenom:document.getElementById('profil-prenom').value.trim(),telephone:document.getElementById('profil-telephone').value.trim(),email:document.getElementById('profil-email').value.trim()};const mdp=document.getElementById('profil-mdp').value;if(mdp)body.mot_de_passe=mdp;const data=await api('/auth/profil.php',{method:'PUT',body:JSON.stringify(body)});if(data.succes){const u=getUser();localStorage.setItem('user',JSON.stringify({...u,...body}));document.getElementById('user-nom').textContent=`${body.prenom} ${body.nom}`;toast('Profil mis à jour ✅');}else toast(data.erreur||'Erreur','error');}
</script>
</body>
</html>