<!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É+ — Prise de RDV Web</title>
    <link rel="icon" type="image/x-icon" href="LOGO SENRDVSANTE.png">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: { extend: { colors: { primary: '#0066CC', dark: '#003F8A' } } }
        };
    </script>
    <style>
        .no-scrollbar::-webkit-scrollbar { display: none; }
        .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
    </style>
</head>
<body class="min-h-screen bg-slate-100 text-slate-800 flex flex-col justify-between font-sans">

<header class="bg-gradient-to-r from-[#000000] to-[#0066CC] text-white py-6 shadow-md">
    <div class="max-w-4xl mx-auto px-4 text-center">
        <img src="LOGO SENRDVSANTE.png" alt="SENRDVSANTE+" class="responsive-img">
<style>
 .responsive-img {
   width: 20%; /* 50% of parent width */
   height: auto; /* Adjust height automatically */
   display: block;
margin-left: auto;
margin-right: auto;
 }
</style>
        
        <p class="text-white/80 text-sm mt-1">Prise de rendez-vous directe sans compte</p>
    </div>
</header>

<main class="max-w-3xl w-full mx-auto my-6 px-4">
    <div id="erreur" class="hidden bg-red-50 border border-red-200 text-red-700 rounded-2xl p-4 mb-6 text-sm font-medium"></div>

    <div class="bg-white rounded-3xl p-6 sm:p-8 shadow-xl border border-slate-200/60">
        <div id="etape-1" class="space-y-6">
            <h2 class="text-xl font-bold text-slate-900 border-b pb-3">1. Choisissez un établissement</h2>

            <div>
                <label class="block text-xs uppercase tracking-wider font-bold text-slate-500 mb-3">Type d'établissement</label>
                <div class="grid grid-cols-2 gap-3">
                    <button type="button" id="btn-public" onclick="choisirType('public')" class="type-btn border-2 border-blue-600 bg-blue-600 text-white rounded-2xl p-4 font-black transition">
                        🏥 Public
                    </button>
                    <button type="button" id="btn-prive" onclick="choisirType('prive')" class="type-btn border-2 border-slate-200 bg-white text-slate-700 rounded-2xl p-4 font-black transition hover:border-blue-300">
                        🏢 Privé
                    </button>
                </div>
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs uppercase tracking-wider font-bold text-slate-500 mb-2">Région</label>
                    <select id="filtre-region" onchange="mettreAJourVilles(); afficherHopitaux()" class="w-full px-4 py-3.5 rounded-xl border border-slate-300 bg-slate-50 focus:bg-white focus:border-blue-600 outline-none transition font-medium">
                        <option value="">Toutes les régions</option>
                    </select>
                </div>
                <div>
                    <label class="block text-xs uppercase tracking-wider font-bold text-slate-500 mb-2">Ville</label>
                    <select id="filtre-ville" onchange="afficherHopitaux()" class="w-full px-4 py-3.5 rounded-xl border border-slate-300 bg-slate-50 focus:bg-white focus:border-blue-600 outline-none transition font-medium">
                        <option value="">Toutes les villes</option>
                    </select>
                </div>
            </div>

            <div>
                <label class="block text-xs uppercase tracking-wider font-bold text-slate-500 mb-2">Rechercher</label>
                <input id="recherche-hopital" type="search" oninput="afficherHopitaux()" placeholder="Nom, ville, région..." class="w-full px-4 py-3.5 rounded-xl border border-slate-300 bg-slate-50 focus:bg-white focus:border-blue-600 outline-none transition font-medium">
            </div>

            <input type="hidden" id="hopital_id" value="">

            <div>
                <div class="flex items-center justify-between gap-3 mb-3">
                    <h3 class="text-sm font-black text-slate-700 uppercase tracking-wide">Établissements</h3>
                    <span id="compteur-hopitaux" class="text-xs font-bold text-slate-400"></span>
                </div>
                <div id="liste-hopitaux" class="grid grid-cols-1 sm:grid-cols-2 gap-3"></div>
            </div>

            <div id="zone-creneaux" class="hidden space-y-6 border-t border-slate-100 pt-6">
                <div class="rounded-2xl bg-blue-50 border border-blue-100 p-4">
                    <div class="text-xs font-black uppercase tracking-wider text-blue-500">Établissement sélectionné</div>
                    <div id="hopital-selectionne-nom" class="mt-1 font-black text-blue-950"></div>
                </div>

                <div>
                    <div class="flex justify-between items-center mb-2">
                        <label class="block text-xs uppercase tracking-wider font-bold text-slate-500">📅 Sélectionnez une date ouverte</label>
                        <span class="text-[11px] text-emerald-600 font-bold bg-emerald-50 px-2 py-0.5 rounded-full border border-emerald-200">● Jours disponibles</span>
                    </div>
                    <div id="calendrier-dates" class="flex gap-3 overflow-x-auto no-scrollbar py-2 px-1"></div>
                </div>

                <div id="zone-services-date" class="space-y-4 pt-2">
                    <div class="border-t border-slate-100 pt-4">
                        <h3 id="titre-date-selectionnee" class="text-sm font-black text-slate-700 uppercase tracking-wide mb-3">Services disponibles</h3>
                        <div id="conteneur-services" class="space-y-4"></div>
                    </div>
                </div>
            </div>

            <button onclick="validerEtape1()" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-4 rounded-xl transition shadow-lg shadow-blue-600/25 mt-4">Suivant : Vos Coordonnées →</button>
        </div>

        <div id="etape-2" class="hidden space-y-5">
            <h2 class="text-xl font-bold text-slate-900 border-b pb-3">2. Vos informations</h2>
            <div class="bg-blue-50 border border-blue-200 rounded-xl p-3.5 text-xs text-blue-800 font-medium">📍 <strong>Créneau sélectionné :</strong> <span id="recap-rdv"></span></div>

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs uppercase tracking-wider font-bold text-slate-500 mb-2">Prénom</label>
                    <input type="text" id="prenom" placeholder="Ex: Moussa" class="w-full px-4 py-3.5 rounded-xl border border-slate-300 bg-slate-50 focus:bg-white focus:border-blue-600 outline-none transition font-medium">
                </div>
                <div>
                    <label class="block text-xs uppercase tracking-wider font-bold text-slate-500 mb-2">Nom</label>
                    <input type="text" id="nom" placeholder="Ex: Ndiaye" class="w-full px-4 py-3.5 rounded-xl border border-slate-300 bg-slate-50 focus:bg-white focus:border-blue-600 outline-none transition font-medium">
                </div>
            </div>

            <div>
                <label class="block text-xs uppercase tracking-wider font-bold text-slate-500 mb-2">Numéro Téléphone</label>
                <input type="tel" id="telephone" placeholder="77 123 45 67" class="w-full px-4 py-3.5 rounded-xl border border-slate-300 bg-slate-50 focus:bg-white focus:border-blue-600 outline-none transition font-medium">
            </div>

            <div>
                <label class="block text-xs uppercase tracking-wider font-bold text-slate-500 mb-2">Raison de visite</label>
                <input type="text" id="motif" placeholder="Ex: Visite générale" class="w-full px-4 py-3.5 rounded-xl border border-slate-300 bg-slate-50 focus:bg-white focus:border-blue-600 outline-none transition font-medium">
            </div>

            <div class="flex gap-3 mt-4">
                <button onclick="retourEtape1()" class="w-1/3 bg-slate-200 hover:bg-slate-300 text-slate-700 font-bold py-4 rounded-xl transition">← Retour</button>
                <button onclick="confirmerRDV()" id="btn-valider" class="w-2/3 bg-blue-600 hover:bg-blue-700 text-white font-bold py-4 rounded-xl transition shadow-lg shadow-blue-600/25 flex justify-center items-center gap-2">
                    <span id="btn-txt">Confirmer</span>
                    <span id="btn-spinner" class="hidden w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"></span>
                </button>
            </div>
        </div>
    </div>
</main>

<footer class="text-center py-4 text-xs text-slate-400">SEN RDV SANTÉ+ — Plateforme de gestion des visites</footer>

<script>
const API_BASE = '/api';
let hopitaux = [];
let typeActif = 'public';
let hopitalSelectionne = null;
let structureDonnees = {};
let dateActive = null;
let plageSelectionnee = null;

window.addEventListener('DOMContentLoaded', chargerHopitaux);

function normaliserTexte(v) {
    return String(v || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().trim();
}

async function chargerHopitaux() {
    try {
        const res = await fetch(`${API_BASE}/public/disponibilites.php?action=hopitaux`);
        const data = await res.json();
        if (!data.succes || !Array.isArray(data.hopitaux)) throw new Error(data.erreur || 'Réponse invalide');
        hopitaux = data.hopitaux;
        construireRegions();
        mettreAJourVilles();
        afficherHopitaux();
    } catch (e) {
        console.error(e);
        afficherErreur("Erreur lors de la récupération des établissements.");
    }
}

function choisirType(type) {
    typeActif = type;
    hopitalSelectionne = null;
    plageSelectionnee = null;
    document.getElementById('hopital_id').value = '';
    document.getElementById('zone-creneaux').classList.add('hidden');

    const publicBtn = document.getElementById('btn-public');
    const priveBtn = document.getElementById('btn-prive');
    [publicBtn, priveBtn].forEach(btn => {
        btn.classList.remove('border-blue-600', 'bg-blue-600', 'text-white');
        btn.classList.add('border-slate-200', 'bg-white', 'text-slate-700');
    });
    const actif = type === 'public' ? publicBtn : priveBtn;
    actif.classList.remove('border-slate-200', 'bg-white', 'text-slate-700');
    actif.classList.add('border-blue-600', 'bg-blue-600', 'text-white');

    construireRegions();
    mettreAJourVilles();
    afficherHopitaux();
}

function hopitauxDuType() {
    return hopitaux.filter(h => normaliserTexte(h.type) === normaliserTexte(typeActif));
}

function construireRegions() {
    const select = document.getElementById('filtre-region');
    const ancienne = select.value;
    const regions = [...new Set(hopitauxDuType().map(h => h.region).filter(Boolean))]
        .sort((a, b) => a.localeCompare(b, 'fr', { sensitivity: 'base' }));
    select.innerHTML = '<option value="">Toutes les régions</option>';
    regions.forEach(region => {
        const opt = document.createElement('option');
        opt.value = region;
        opt.textContent = region;
        select.appendChild(opt);
    });
    if (regions.includes(ancienne)) select.value = ancienne;
}

function mettreAJourVilles() {
    const region = document.getElementById('filtre-region').value;
    const select = document.getElementById('filtre-ville');
    const ancienne = select.value;
    const villes = [...new Set(hopitauxDuType()
        .filter(h => !region || h.region === region)
        .map(h => h.ville).filter(Boolean))]
        .sort((a, b) => a.localeCompare(b, 'fr', { sensitivity: 'base' }));
    select.innerHTML = '<option value="">Toutes les villes</option>';
    villes.forEach(ville => {
        const opt = document.createElement('option');
        opt.value = ville;
        opt.textContent = ville;
        select.appendChild(opt);
    });
    if (villes.includes(ancienne)) select.value = ancienne;
}

function afficherHopitaux() {
    const region = document.getElementById('filtre-region').value;
    const ville = document.getElementById('filtre-ville').value;
    const recherche = normaliserTexte(document.getElementById('recherche-hopital').value);
    const liste = document.getElementById('liste-hopitaux');

    const resultats = hopitauxDuType().filter(h => {
        if (region && h.region !== region) return false;
        if (ville && h.ville !== ville) return false;
        if (recherche) {
            const texte = normaliserTexte(`${h.nom} ${h.ville} ${h.region} ${h.adresse}`);
            if (!texte.includes(recherche)) return false;
        }
        return true;
    });

    document.getElementById('compteur-hopitaux').textContent = `${resultats.length} résultat${resultats.length > 1 ? 's' : ''}`;
    liste.innerHTML = '';

    if (!resultats.length) {
        liste.innerHTML = '<div class="sm:col-span-2 text-center rounded-2xl border border-dashed border-slate-300 bg-slate-50 p-8 text-sm text-slate-500">Aucun établissement ne correspond à votre recherche.</div>';
        return;
    }

    resultats.forEach(h => {
        const selectionne = hopitalSelectionne && String(hopitalSelectionne.id) === String(h.id);
        const card = document.createElement('button');
        card.type = 'button';
        card.className = `text-left rounded-2xl border-2 p-4 transition ${selectionne ? 'border-blue-600 bg-blue-50 shadow-md' : 'border-slate-200 bg-white hover:border-blue-300 hover:bg-blue-50/40'}`;
        const typeLabel = normaliserTexte(h.type) === 'public' ? 'PUBLIC' : 'PRIVÉ';
        const icon = normaliserTexte(h.type) === 'public' ? '🏥' : '🏢';
        card.innerHTML = `
            <div class="flex items-start gap-3">
                <div class="w-11 h-11 rounded-xl bg-slate-100 flex items-center justify-center text-xl shrink-0">${icon}</div>
                <div class="min-w-0 flex-1">
                    <div class="font-black text-slate-900 leading-snug">${h.nom}</div>
                    <div class="text-xs text-slate-500 mt-1">📍 ${h.ville || '-'}${h.region ? ' · ' + h.region : ''}</div>
                    <div class="mt-2 inline-flex rounded-full px-2.5 py-1 text-[10px] font-black tracking-wide ${normaliserTexte(h.type) === 'public' ? 'bg-blue-100 text-blue-700' : 'bg-violet-100 text-violet-700'}">${typeLabel}</div>
                </div>
            </div>`;
        card.onclick = () => selectionnerHopital(h);
        liste.appendChild(card);
    });
}

async function selectionnerHopital(hopital) {
    hopitalSelectionne = hopital;
    document.getElementById('hopital_id').value = hopital.id;
    document.getElementById('hopital-selectionne-nom').textContent = `${hopital.nom} — ${hopital.ville || ''}`;
    plageSelectionnee = null;
    afficherHopitaux();
    await chargerCreneauxDepuisBDD();
    document.getElementById('zone-creneaux').scrollIntoView({ behavior: 'smooth', block: 'start' });
}

async function chargerCreneauxDepuisBDD() {
    const hopitalId = document.getElementById('hopital_id').value;
    if (!hopitalId) { masquerCreneaux(); return; }
    try {
        const res = await fetch(`${API_BASE}/public/disponibilites.php?action=creneaux&hopital_id=${encodeURIComponent(hopitalId)}`);
        const data = await res.json();
        structureDonnees = {};
        dateActive = null;
        plageSelectionnee = null;

        if (data.succes && Array.isArray(data.creneaux) && data.creneaux.length > 0) {
            cacherErreur();
            data.creneaux.forEach(plage => {
                const date = plage.date_plage;
                const service = plage.service_nom || 'Service Général';
                if (!structureDonnees[date]) structureDonnees[date] = {};
                if (!structureDonnees[date][service]) structureDonnees[date][service] = [];
                structureDonnees[date][service].push(plage);
            });
            construireCalendrier();
            document.getElementById('zone-creneaux').classList.remove('hidden');
        } else {
            masquerCreneaux(false);
            afficherErreur(data.message || "Aucun créneau disponible pour cet établissement actuellement.");
        }
    } catch (e) {
        console.error(e);
        afficherErreur("Erreur réseau lors du chargement des plages.");
    }
}

function construireCalendrier() {
    const containerDates = document.getElementById('calendrier-dates');
    containerDates.innerHTML = '';
    Object.keys(structureDonnees).sort().forEach((dateStr, index) => {
        const d = new Date(dateStr + 'T12:00:00');
        const nomJour = d.toLocaleDateString('fr-FR', { weekday: 'short' }).replace('.', '');
        const numJour = d.getDate();
        const nomMois = d.toLocaleDateString('fr-FR', { month: 'short' }).replace('.', '');
        const card = document.createElement('button');
        card.type = 'button';
        card.dataset.date = dateStr;
        card.className = 'date-card flex-shrink-0 w-20 p-3 rounded-2xl border text-center transition flex flex-col items-center justify-center cursor-pointer border-emerald-300 bg-emerald-50/50 hover:bg-emerald-100/80 text-slate-800';
        card.innerHTML = `<span class="text-[10px] font-black uppercase text-emerald-700 tracking-wider">${nomJour}</span><span class="text-xl font-black text-slate-900 my-0.5">${numJour}</span><span class="text-[10px] font-bold text-slate-500 uppercase">${nomMois}</span>`;
        card.onclick = () => selectionnerDate(dateStr, card);
        containerDates.appendChild(card);
        if (index === 0) selectionnerDate(dateStr, card);
    });
}

function selectionnerDate(dateStr, cardElement) {
    dateActive = dateStr;
    plageSelectionnee = null;
    document.querySelectorAll('.date-card').forEach(c => {
        c.classList.remove('bg-blue-600', 'text-white', 'border-blue-600', 'shadow-md');
        c.classList.add('border-emerald-300', 'bg-emerald-50/50', 'text-slate-800');
        const spans = c.querySelectorAll('span');
        if (spans[0]) spans[0].className = 'text-[10px] font-black uppercase text-emerald-700 tracking-wider';
        if (spans[1]) spans[1].className = 'text-xl font-black text-slate-900 my-0.5';
    });
    cardElement.classList.remove('border-emerald-300', 'bg-emerald-50/50', 'text-slate-800');
    cardElement.classList.add('bg-blue-600', 'text-white', 'border-blue-600', 'shadow-md');
    const spans = cardElement.querySelectorAll('span');
    if (spans[0]) spans[0].className = 'text-[10px] font-black uppercase text-blue-100 tracking-wider';
    if (spans[1]) spans[1].className = 'text-xl font-black text-white my-0.5';

    const dateFormatee = new Date(dateStr + 'T12:00:00').toLocaleDateString('fr-FR', { weekday: 'long', day: 'numeric', month: 'long' });
    document.getElementById('titre-date-selectionnee').textContent = `Services disponibles le ${dateFormatee}`;
    afficherServicesPourDate(dateStr);
}

function afficherServicesPourDate(dateStr) {
    const conteneur = document.getElementById('conteneur-services');
    conteneur.innerHTML = '';
    const servicesObj = structureDonnees[dateStr] || {};

    Object.keys(servicesObj).forEach(serviceNom => {
        const cardService = document.createElement('div');
        cardService.className = 'bg-slate-50 border border-slate-200 rounded-2xl p-4 space-y-3';
        const header = document.createElement('div');
        header.className = 'flex items-center gap-2 border-b border-slate-200/80 pb-2';
        header.innerHTML = `<span class="w-2.5 h-2.5 rounded-full bg-blue-600"></span><h4 class="text-sm font-bold text-slate-900">${serviceNom}</h4>`;
        cardService.appendChild(header);

        const gridHeures = document.createElement('div');
        gridHeures.className = 'grid grid-cols-2 sm:grid-cols-3 gap-2';

        servicesObj[serviceNom].forEach(plage => {
            const heureDebut = plage.heure_debut ? plage.heure_debut.substring(0, 5) : '--:--';
            const btnHeure = document.createElement('button');
            btnHeure.type = 'button';
            btnHeure.className = 'heure-btn p-2.5 rounded-xl border border-slate-300 bg-white font-bold text-slate-800 hover:border-blue-500 hover:bg-blue-50 transition text-sm flex items-center justify-center gap-1.5';
            btnHeure.innerHTML = `<span>🕒</span><span>${heureDebut}</span>`;
            const payload = { id: plage.id, service_id: plage.service_id, service_nom: serviceNom, date: dateStr, heure: heureDebut };
            btnHeure.onclick = () => {
                document.querySelectorAll('.heure-btn').forEach(b => {
                    b.classList.remove('bg-blue-600', 'text-white', 'border-blue-600');
                    b.classList.add('bg-white', 'text-slate-800', 'border-slate-300');
                });
                btnHeure.classList.remove('bg-white', 'text-slate-800', 'border-slate-300');
                btnHeure.classList.add('bg-blue-600', 'text-white', 'border-blue-600');
                plageSelectionnee = payload;
                cacherErreur();
            };
            gridHeures.appendChild(btnHeure);
        });

        cardService.appendChild(gridHeures);
        conteneur.appendChild(cardService);
    });
}

function masquerCreneaux(effacerSelection = true) {
    document.getElementById('zone-creneaux').classList.add('hidden');
    plageSelectionnee = null;
    if (effacerSelection) {
        hopitalSelectionne = null;
        document.getElementById('hopital_id').value = '';
    }
}

function validerEtape1() {
    const hopitalId = document.getElementById('hopital_id').value;
    if (!hopitalId || !hopitalSelectionne) { afficherErreur('Veuillez choisir un établissement.'); return; }
    if (!plageSelectionnee) { afficherErreur('Veuillez cliquer sur une heure de rendez-vous.'); return; }

    cacherErreur();
    const dateFormatee = new Date(plageSelectionnee.date + 'T12:00:00').toLocaleDateString('fr-FR', { weekday: 'short', day: 'numeric', month: 'short' });
    document.getElementById('recap-rdv').textContent = `${hopitalSelectionne.nom} (${plageSelectionnee.service_nom}) — Le ${dateFormatee} à ${plageSelectionnee.heure}`;
    document.getElementById('etape-1').classList.add('hidden');
    document.getElementById('etape-2').classList.remove('hidden');
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function retourEtape1() {
    document.getElementById('etape-2').classList.add('hidden');
    document.getElementById('etape-1').classList.remove('hidden');
}

async function confirmerRDV() {
    const prenom = document.getElementById('prenom').value.trim();
    const nom = document.getElementById('nom').value.trim();
    const telephone = document.getElementById('telephone').value.trim();
    const motif = document.getElementById('motif').value.trim() || 'Visite';
    const hopitalId = document.getElementById('hopital_id').value;

    if (!prenom || !nom || !telephone) {
        afficherErreur('Veuillez renseigner votre prénom, votre nom et votre numéro de téléphone.');
        return;
    }
    if (!plageSelectionnee || !hopitalId) {
        afficherErreur('Le rendez-vous sélectionné est invalide. Veuillez recommencer.');
        return;
    }

    document.getElementById('btn-txt').classList.add('hidden');
    document.getElementById('btn-spinner').classList.remove('hidden');
    document.getElementById('btn-valider').disabled = true;

    try {
        const bodyData = {
            nom,
            prenom,
            telephone,
            hopital_id: hopitalId,
            service_id: plageSelectionnee.service_id,
            creneau_id: plageSelectionnee.id,
            date_rdv: plageSelectionnee.date,
            heure_rdv: plageSelectionnee.heure,
            motif
        };

        const res = await fetch(`${API_BASE}/public/prise_rdv.php`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
            body: JSON.stringify(bodyData)
        });

        const raw = await res.text();
        let data;
        try { data = JSON.parse(raw); }
        catch (e) {
            console.error('Réponse non JSON :', raw);
            throw new Error('Réponse serveur invalide.');
        }

        if (!res.ok || data.succes === false || data.erreur) {
            afficherErreur(data.erreur || data.message || 'Réservation impossible.');
            return;
        }

        if (data.payment_url) {
            sessionStorage.setItem('senrdv_rdv_id', String(data.rdv_id || ''));
            window.location.href = data.payment_url;
            return;
        }

        afficherErreur("Le rendez-vous a été créé mais aucun lien de paiement Wave n'a été retourné.");
    } catch (e) {
        console.error(e);
        afficherErreur(e.message || 'Erreur réseau lors de la réservation.');
    } finally {
        document.getElementById('btn-txt').classList.remove('hidden');
        document.getElementById('btn-spinner').classList.add('hidden');
        document.getElementById('btn-valider').disabled = false;
    }
}

function afficherErreur(msg) {
    const el = document.getElementById('erreur');
    el.textContent = msg;
    el.classList.remove('hidden');
    el.scrollIntoView({ behavior: 'smooth', block: 'center' });
}

function cacherErreur() {
    document.getElementById('erreur').classList.add('hidden');
}
</script>
</body>
</html>
