<!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É+ — Directeur Régional</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>tailwind.config = { theme: { extend: { colors: { primary: '#0066CC', dark: '#003F8A' } } } }</script>
    <style>
        @media print {
            aside, header, .no-print { display: none !important; }
            main { margin-left: 0 !important; }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">

<!-- ═══ SIDEBAR ═══ -->
<aside class="fixed left-0 top-0 h-full w-64 bg-[#003F8A] text-white flex flex-col z-30">
    <div class="p-6 border-b border-white/10">
        <div class="flex items-center gap-3">
            <div class="w-9 h-9 rounded-xl bg-white/10 border border-white/20 flex items-center justify-center">
                <span class="text-white text-lg font-light">+</span>
            </div>
            <div>
                <p class="font-black text-sm tracking-wide">SEN RDV SANTÉ+</p>
                <p class="text-white/50 text-xs">Directeur Régional</p>
            </div>
        </div>
    </div>
    <div class="p-4 border-b border-white/10">
        <div class="bg-white/10 rounded-xl p-3">
            <p id="user-nom" class="font-bold text-sm">Chargement...</p>
            <p id="user-region" class="text-white/60 text-xs mt-0.5">🌍 Région</p>
        </div>
    </div>
    <nav class="flex-1 p-4 space-y-1 overflow-y-auto">
        <button onclick="afficherSection('dashboard')" class="nav-btn w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-white/80 hover:text-white hover:bg-white/10 transition-all text-sm text-left"><span>📊</span> Dashboard</button>
        <button onclick="afficherSection('hopitaux')"  class="nav-btn w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-white/80 hover:text-white hover:bg-white/10 transition-all text-sm text-left"><span>🏥</span> Hôpitaux</button>
        <button onclick="afficherSection('services')"  class="nav-btn w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-white/80 hover:text-white hover:bg-white/10 transition-all text-sm text-left"><span>🩺</span> Services</button>
        <button onclick="afficherSection('staff')"     class="nav-btn w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-white/80 hover:text-white hover:bg-white/10 transition-all text-sm text-left"><span>👥</span> Staff</button>
        <button onclick="afficherSection('rdvs')"      class="nav-btn w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-white/80 hover:text-white hover:bg-white/10 transition-all text-sm text-left"><span>📋</span> Tous les RDVs</button>
        <button onclick="afficherSection('profil')"    class="nav-btn w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-white/80 hover:text-white hover:bg-white/10 transition-all text-sm text-left"><span>👤</span> Mon profil</button>
    </nav>
    <div class="p-4 border-t border-white/10">
        <button onclick="seDeconnecter()" class="w-full flex items-center gap-2 px-3 py-2.5 rounded-xl text-white/60 hover:text-white hover:bg-white/10 transition-all text-sm">
            <span>🚪</span> Se déconnecter
        </button>
    </div>
</aside>

<!-- ═══ CONTENU ═══ -->
<main class="ml-64 min-h-screen">
    <header class="bg-white border-b border-gray-100 px-8 py-4 flex items-center justify-between sticky top-0 z-20">
        <div>
            <h1 id="page-titre" class="text-lg font-bold text-gray-900">Dashboard régional</h1>
            <p class="text-sm text-gray-400" id="page-sous"></p>
        </div>
        <div class="flex gap-3 no-print">
            <button onclick="window.print()" class="flex items-center gap-2 px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl text-sm font-semibold text-gray-600 transition-all">🖨️ Imprimer</button>
            <button onclick="actualiser()" class="flex items-center gap-2 px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl text-sm font-semibold text-gray-600 transition-all">🔄 Actualiser</button>
        </div>
    </header>

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

    <!-- ─── DASHBOARD ─── -->
    <section id="section-dashboard" class="p-8">
        <!-- sélecteur hôpital + période -->
        <div class="flex flex-wrap items-center gap-3 mb-6 no-print">
            <select id="filtre-hopital-dash" onchange="chargerDashboardRegional()"
                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 mes hôpitaux</option>
            </select>
            <select id="filtre-service-dash" onchange="chargerDashboardRegional()"
                class="px-4 py-2 rounded-xl border-2 border-gray-100 bg-white text-sm font-semibold text-gray-600 focus:outline-none focus:border-blue-500">
                <option value="">Tous les services</option>
            </select>
            <div class="flex bg-white border border-gray-200 rounded-xl overflow-hidden">
                <button onclick="setPeriode('jour')"    id="btn-jour"    class="periode-btn px-4 py-2 text-sm font-semibold transition-all bg-blue-600 text-white">Jour</button>
                <button onclick="setPeriode('semaine')" id="btn-semaine" class="periode-btn px-4 py-2 text-sm font-semibold transition-all text-gray-500 hover:bg-gray-50">Semaine</button>
                <button onclick="setPeriode('mois')"    id="btn-mois"    class="periode-btn px-4 py-2 text-sm font-semibold transition-all text-gray-500 hover:bg-gray-50">Mois</button>
                <button onclick="setPeriode('annee')"   id="btn-annee"   class="periode-btn px-4 py-2 text-sm font-semibold transition-all text-gray-500 hover:bg-gray-50">Année</button>
            </div>
            <span id="periode-label" class="text-sm text-gray-400 ml-auto"></span>
        </div>

        <!-- KPIs -->
        <div class="grid grid-cols-5 gap-4 mb-6" id="kpi-cards">
            <div class="col-span-5 text-center py-8 text-gray-400">Chargement...</div>
        </div>

        <!-- graphiques -->
        <div class="grid grid-cols-2 gap-6 mb-6">
            <div class="bg-white rounded-2xl border border-gray-100 p-6">
                <h3 class="font-bold text-gray-900 mb-4">📈 RDVs par statut</h3>
                <canvas id="chart-statuts" height="200"></canvas>
            </div>
            <div class="bg-white rounded-2xl border border-gray-100 p-6">
                <h3 class="font-bold text-gray-900 mb-4">🏥 RDVs par hôpital</h3>
                <canvas id="chart-hopitaux" height="200"></canvas>
            </div>
        </div>

        <!-- tableau RDVs -->
        <div class="bg-white rounded-2xl border border-gray-100 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-50 flex items-center justify-between">
                <h3 class="font-bold text-gray-900">RDVs de la période</h3>
                <span id="rdvs-count" class="px-3 py-1 bg-blue-50 text-blue-600 rounded-full text-sm font-bold">0</span>
            </div>
            <table class="w-full">
                <thead><tr class="bg-gray-50 border-b border-gray-100">
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Patient</th>
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Hôpital</th>
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Service</th>
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Date / Heure</th>
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Statut</th>
                </tr></thead>
                <tbody id="tbody-dashboard">
                    <tr><td colspan="5" class="text-center py-8 text-gray-400">Chargement...</td></tr>
                </tbody>
            </table>
        </div>
    </section>

    <!-- ─── HÔPITAUX ─── -->
    <section id="section-hopitaux" class="p-8 hidden">
        <h2 class="text-lg font-bold text-gray-900 mb-6">🏥 Hôpitaux de ma région</h2>
        <div id="liste-hopitaux" class="grid grid-cols-2 gap-4">
            <p class="col-span-2 text-center text-gray-400 py-8">Chargement...</p>
        </div>
    </section>

    <!-- ─── SERVICES ─── -->
    <section id="section-services" class="p-8 hidden">
        <div class="flex items-center gap-4 mb-6">
            <h2 class="text-lg font-bold text-gray-900">🩺 Services</h2>
            <select id="filtre-hopital-services" onchange="chargerServicesDirecteur()"
                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 mes hôpitaux</option>
            </select>
        </div>
        <div id="liste-services-directeur" class="grid grid-cols-2 gap-4">
            <p class="col-span-2 text-center text-gray-400 py-8">Chargement...</p>
        </div>
    </section>

    <!-- ─── STAFF ─── -->
    <section id="section-staff" class="p-8 hidden">
        <div class="flex items-center gap-4 mb-6">
            <h2 class="text-lg font-bold text-gray-900">👥 Staff</h2>
            <select id="filtre-hopital-staff" onchange="chargerStaffDirecteur()"
                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 mes hôpitaux</option>
            </select>
        </div>
        <div class="bg-white rounded-2xl border border-gray-100 overflow-hidden">
            <table class="w-full">
                <thead><tr class="bg-gray-50 border-b border-gray-100">
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Nom</th>
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Hôpital</th>
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Téléphone</th>
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Service</th>
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Rôle</th>
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Statut</th>
                </tr></thead>
                <tbody id="tbody-staff-directeur"><tr><td colspan="6" class="text-center py-8 text-gray-400">Chargement...</td></tr></tbody>
            </table>
        </div>
    </section>

    <!-- ─── TOUS LES RDVs ─── -->
    <section id="section-rdvs" class="p-8 hidden">
        <div class="flex items-center gap-4 mb-6 flex-wrap">
            <h2 class="text-lg font-bold text-gray-900 mr-auto">📋 Tous les rendez-vous</h2>
            <select id="rdvs-hopital" onchange="chargerRdvsDirecteur()"
                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 mes hôpitaux</option>
            </select>
            <input type="date" id="rdvs-date" onchange="chargerRdvsDirecteur()"
                class="px-4 py-2 rounded-xl border-2 border-gray-100 bg-white text-sm font-semibold text-gray-600 focus:outline-none focus:border-blue-500" />
            <select id="rdvs-statut" onchange="chargerRdvsDirecteur()"
                class="px-4 py-2 rounded-xl border-2 border-gray-100 bg-white text-sm font-semibold text-gray-600 focus:outline-none focus:border-blue-500">
                <option value="">Tous les statuts</option>
                <option value="en_attente">En attente</option>
                <option value="confirme">Confirmés</option>
                <option value="paye">Payés</option>
                <option value="consomme">Terminés</option>
                <option value="annule">Annulés</option>
            </select>
        </div>
        <div class="bg-white rounded-2xl border border-gray-100 overflow-hidden">
            <table class="w-full">
                <thead><tr class="bg-gray-50 border-b border-gray-100">
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">#</th>
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Patient</th>
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Hôpital</th>
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Service</th>
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Date / Heure</th>
                    <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Statut</th>
                </tr></thead>
                <tbody id="tbody-rdvs-directeur"><tr><td colspan="6" class="text-center py-8 text-gray-400">Chargement...</td></tr></tbody>
            </table>
        </div>
    </section>

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

</main>

<script src="/web/assets/app.js"></script>
<script>
let tousMesHopitaux = [];
let periodeCourante = 'jour';
let chartsInstances = {};

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

    document.getElementById('user-nom').textContent = `${user.prenom} ${user.nom}`;
    document.getElementById('user-region').textContent = `🌍 ${user.region_nom || 'Région'}`;

    await chargerHopitauxDirecteur();
    await chargerDashboardRegional();
});

// ════════════════════════════════════
// HÔPITAUX
// ════════════════════════════════════
async function chargerHopitauxDirecteur() {
    const data = await api('/hopitaux/liste.php?mes_hopitaux=1');
    if (!data.succes) return;
    tousMesHopitaux = data.hopitaux || [];

    const opts = tousMesHopitaux.map(h => `<option value="${h.id}">${h.nom}</option>`).join('');
    const avecTous = '<option value="">Tous mes hôpitaux</option>' + opts;
    const avecChoisir = '<option value="">Tous mes hôpitaux</option>' + opts;

    ['filtre-hopital-dash', 'filtre-hopital-services', 'filtre-hopital-staff', 'rdvs-hopital'].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.innerHTML = avecTous;
    });

    // liste hôpitaux
    const container = document.getElementById('liste-hopitaux');
    if (!tousMesHopitaux.length) {
        container.innerHTML = '<p class="col-span-2 text-center text-gray-400 py-8">Aucun hôpital rattaché</p>';
        return;
    }
    container.innerHTML = tousMesHopitaux.map(h => `
        <div class="bg-white rounded-2xl p-5 border border-gray-100 shadow-sm">
            <div class="flex items-start gap-3 mb-3">
                <div class="w-10 h-10 rounded-xl bg-blue-50 flex items-center justify-center text-xl">🏥</div>
                <div>
                    <h3 class="font-bold text-gray-900">${h.nom}</h3>
                    <p class="text-xs text-gray-400">${h.ville_nom || ''}, ${h.region_nom || ''}</p>
                </div>
            </div>
            <div class="flex gap-4 text-sm">
                <span class="text-gray-500">🩺 <strong>${h.nb_services || 0}</strong> services</span>
                <span class="text-gray-500">👥 <strong>${h.nb_staff || 0}</strong> staff</span>
                <span class="text-gray-500">📋 <strong>${h.nb_rdvs_jour || 0}</strong> RDVs aujourd'hui</span>
            </div>
        </div>
    `).join('');
}

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

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

// ════════════════════════════════════
// DASHBOARD REGIONAL
// ════════════════════════════════════
async function chargerDashboardRegional() {
    const { debut, fin, label } = getPeriodeDates();
    document.getElementById('periode-label').textContent = label;

    const hopitalId = document.getElementById('filtre-hopital-dash').value;
    const serviceId = document.getElementById('filtre-service-dash').value;

    let url = `/admin/stats_directeur.php?date_debut=${debut}&date_fin=${fin}`;
    if (hopitalId) url += `&hopital_id=${hopitalId}`;
    if (serviceId) url += `&service_id=${serviceId}`;

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

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

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

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

    const parHopital = data.par_hopital || {};
    dessinerChart('chart-hopitaux', 'bar',
        Object.keys(parHopital), Object.values(parHopital),
        Object.keys(parHopital).map(() => '#3B82F6')
    );

    // tableau RDVs
    const rdvs = data.rdvs || [];
    const tbody = document.getElementById('tbody-dashboard');
    if (!rdvs.length) {
        tbody.innerHTML = '<tr><td colspan="5" class="text-center py-8 text-gray-400">Aucun RDV pour cette période</td></tr>';
    } else {
        tbody.innerHTML = rdvs.map(rdv => `
            <tr class="border-b border-gray-50 hover:bg-gray-50/50">
                <td class="px-6 py-3 text-sm font-semibold text-gray-900">${rdv.patient_prenom} ${rdv.patient_nom}</td>
                <td class="px-6 py-3 text-sm text-gray-500">${rdv.hopital_nom}</td>
                <td class="px-6 py-3 text-sm text-gray-500">${rdv.service_nom}</td>
                <td class="px-6 py-3"><p class="text-sm font-semibold text-gray-900">${rdv.date_rdv}</p><p class="text-blue-600 font-bold">${formatHeure(rdv.heure_rdv)}</p></td>
                <td class="px-6 py-3">${statutBadge(rdv.statut)}</td>
            </tr>`).join('');
    }
}

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

// ════════════════════════════════════
// SERVICES DIRECTEUR
// ════════════════════════════════════
async function chargerServicesDirecteur() {
    const hopitalId = document.getElementById('filtre-hopital-services').value;
    let url = '/admin/services.php';
    if (hopitalId) url += '?hopital_id=' + hopitalId;

    const data = await api(url);
    const container = document.getElementById('liste-services-directeur');

    if (!data.succes || !data.services.length) {
        container.innerHTML = '<p class="col-span-2 text-center text-gray-400 py-8">Aucun service</p>';
        return;
    }

    container.innerHTML = data.services.map(s => `
        <div class="bg-white rounded-2xl p-5 border border-gray-100 shadow-sm">
            <div class="flex items-start justify-between mb-3">
                <div class="w-10 h-10 rounded-xl bg-blue-50 flex items-center justify-center text-xl">🩺</div>
                <div class="flex items-center gap-2">
                    <span class="px-2.5 py-1 rounded-full text-xs font-semibold ${s.mode_rdv==='quota' ? 'bg-purple-100 text-purple-700' : 'bg-blue-100 text-blue-700'}">${s.mode_rdv==='quota' ? '🔢 Quota' : '🕐 Créneaux'}</span>
                    <span class="px-2.5 py-1 rounded-full text-xs font-semibold ${s.actif==1 ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-600'}">${s.actif==1 ? 'Actif' : 'Inactif'}</span>
                </div>
            </div>
            <h3 class="font-bold text-gray-900 mb-1">${s.nom}</h3>
            <p class="text-xs text-gray-400">🏥 ${s.hopital_nom || ''}</p>
            <p class="text-xs text-gray-400 mt-1">${s.nb_gerants || 0} gérant(s) · ${s.quota_rdv_jour || 0} RDV/jour</p>
        </div>
    `).join('');
}

// ════════════════════════════════════
// STAFF DIRECTEUR
// ════════════════════════════════════
async function chargerStaffDirecteur() {
    const hopitalId = document.getElementById('filtre-hopital-staff').value;
    let url = '/admin/staff.php';
    if (hopitalId) url += '?hopital_id=' + hopitalId;

    const data = await api(url);
    const tbody = document.getElementById('tbody-staff-directeur');

    if (!data.succes || !data.staff.length) {
        tbody.innerHTML = '<tr><td colspan="6" class="text-center py-8 text-gray-400">Aucun membre du staff</td></tr>';
        return;
    }

    tbody.innerHTML = data.staff.map(m => `
        <tr class="border-b border-gray-50 hover:bg-gray-50/50">
            <td class="px-6 py-4">
                <div class="flex items-center gap-3">
                    <div class="w-8 h-8 rounded-lg bg-blue-50 flex items-center justify-center text-sm font-bold text-blue-600">${m.prenom[0]}${m.nom[0]}</div>
                    <div><p class="font-semibold text-gray-900 text-sm">${m.prenom} ${m.nom}</p><p class="text-xs text-gray-400">${m.email||''}</p></div>
                </div>
            </td>
            <td class="px-6 py-4 text-sm text-gray-600">${m.hopital_nom || '—'}</td>
            <td class="px-6 py-4 text-sm text-gray-600">${m.telephone}</td>
            <td class="px-6 py-4 text-sm text-gray-600">${m.service_nom||'—'}</td>
            <td class="px-6 py-4"><span class="px-2.5 py-1 bg-blue-50 text-blue-700 rounded-full text-xs font-semibold">${m.role==='admin_hopital'?'👨‍💼 Admin':'👨‍⚕️ Gérant'}</span></td>
            <td class="px-6 py-4"><span class="px-2.5 py-1 rounded-full text-xs font-semibold ${m.actif==1?'bg-green-100 text-green-700':'bg-red-100 text-red-600'}">${m.actif==1?'Actif':'Inactif'}</span></td>
        </tr>
    `).join('');
}

// ════════════════════════════════════
// RDVs DIRECTEUR
// ════════════════════════════════════
async function chargerRdvsDirecteur() {
    const hopitalId = document.getElementById('rdvs-hopital').value;
    const date = document.getElementById('rdvs-date').value;
    const statut = document.getElementById('rdvs-statut').value;

    let url = '/rdv/liste_gerant.php?tous_hopitaux=1';
    if (hopitalId) url += '&hopital_id=' + hopitalId;
    if (date) url += '&date=' + date;
    if (statut) url += '&statut=' + statut;

    const data = await api(url);
    const tbody = document.getElementById('tbody-rdvs-directeur');

    if (!data.succes || !data.rdvs.length) {
        tbody.innerHTML = '<tr><td colspan="6" class="text-center py-8 text-gray-400">Aucun RDV trouvé</td></tr>';
        return;
    }

    tbody.innerHTML = data.rdvs.map((rdv, i) => `
        <tr class="border-b border-gray-50 hover:bg-gray-50/50">
            <td class="px-6 py-3 text-sm text-gray-400">${i+1}</td>
            <td class="px-6 py-3 text-sm font-semibold text-gray-900">${rdv.patient_prenom} ${rdv.patient_nom}</td>
            <td class="px-6 py-3 text-sm text-gray-500">${rdv.hopital_nom || '—'}</td>
            <td class="px-6 py-3 text-sm text-gray-500">${rdv.service_nom}</td>
            <td class="px-6 py-3"><p class="text-sm font-semibold">${rdv.date_rdv}</p><p class="text-blue-600 font-bold">${formatHeure(rdv.heure_rdv)}</p></td>
            <td class="px-6 py-3">${statutBadge(rdv.statut)}</td>
        </tr>
    `).join('');
}

// ════════════════════════════════════
// NAVIGATION
// ════════════════════════════════════
function afficherSection(section) {
    ['dashboard','hopitaux','services','staff','rdvs','profil'].forEach(s => {
        document.getElementById('section-' + s)?.classList.add('hidden');
    });
    document.getElementById('section-' + section)?.classList.remove('hidden');
    const titres = {
        dashboard: 'Dashboard régional',
        hopitaux: 'Hôpitaux de ma région',
        services: 'Services',
        staff: 'Staff',
        rdvs: 'Tous les rendez-vous',
        profil: 'Mon profil'
    };
    document.getElementById('page-titre').textContent = titres[section] || '';
    document.getElementById('page-sous').textContent = '';

    if (section === 'hopitaux') chargerHopitauxDirecteur();
    if (section === 'services') chargerServicesDirecteur();
    if (section === 'staff') chargerStaffDirecteur();
    if (section === 'rdvs') { document.getElementById('rdvs-date').value = new Date().toISOString().split('T')[0]; chargerRdvsDirecteur(); }
    if (section === 'profil') afficherProfilSection();
}

function actualiser() {
    const sections = ['dashboard','hopitaux','services','staff','rdvs'];
    const actif = sections.find(s => !document.getElementById('section-' + s)?.classList.contains('hidden'));
    if (actif === 'dashboard') chargerDashboardRegional();
    else if (actif === 'hopitaux') chargerHopitauxDirecteur();
    else if (actif === 'services') chargerServicesDirecteur();
    else if (actif === 'staff') chargerStaffDirecteur();
    else if (actif === 'rdvs') chargerRdvsDirecteur();
}

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