<!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É+ — Scan QR</title>
    <script src="/web/assets/app.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html5-qrcode/2.3.8/html5-qrcode.min.js"></script>
    <script>tailwind.config = { theme: { extend: { colors: { primary: '#0066CC', dark: '#003F8A' } } } }</script>
</head>
<body class="bg-gray-50 min-h-screen">

    <!-- header -->
    <div class="bg-[#003F8A] px-6 py-4 flex items-center justify-between">
        <div class="flex items-center gap-3">
            <div class="w-8 h-8 rounded-lg bg-white/10 border border-white/20 flex items-center justify-center">
                <span class="text-white text-sm font-light">+</span>
            </div>
            <div>
                <p class="text-white font-black text-sm">SEN RDV SANTÉ+</p>
                <p class="text-white/50 text-xs">Agent d'accueil — Scan QR</p>
            </div>
        </div>
        <div class="flex items-center gap-3">
            <span id="user-info" class="text-white/70 text-sm"></span>
            <button onclick="seDeconnecter()" class="px-3 py-1.5 bg-white/10 hover:bg-white/20 text-white text-xs font-semibold rounded-lg transition-all">
                Déco
            </button>
        </div>
    </div>

    <div class="max-w-lg mx-auto p-6">

        <!-- onglets mode scan -->
        <div class="flex bg-white rounded-2xl p-1 border border-gray-100 shadow-sm mb-6">
            <button onclick="setMode('camera')" id="btn-camera"
                class="flex-1 py-2.5 rounded-xl text-sm font-semibold transition-all bg-[#003F8A] text-white">
                📷 Caméra
            </button>
            <button onclick="setMode('manuel')" id="btn-manuel"
                class="flex-1 py-2.5 rounded-xl text-sm font-semibold transition-all text-gray-500">
                ⌨️ Saisie manuelle
            </button>
        </div>

        <!-- mode caméra -->
        <div id="mode-camera">
            <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden mb-4">
                <div class="px-5 py-4 border-b border-gray-50">
                    <p class="font-bold text-gray-900 text-sm">Scanner le QR Code du patient</p>
                    <p class="text-xs text-gray-400 mt-0.5">Pointez la caméra vers le QR Code affiché sur le téléphone du patient</p>
                </div>
                <!-- zone de scan -->
                <div id="reader" class="w-full"></div>
                <div class="px-5 py-3 flex items-center justify-between">
                    <button onclick="toggleScan()" id="btn-scan"
                        class="flex-1 py-3 bg-[#003F8A] hover:bg-blue-900 text-white font-bold rounded-xl transition-all text-sm">
                        ▶ Démarrer le scan
                    </button>
                </div>
            </div>
        </div>

        <!-- mode saisie manuelle -->
        <div id="mode-manuel" class="hidden">
            <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 mb-4">
                <p class="font-bold text-gray-900 text-sm mb-4">Saisir le code manuellement</p>
                <div class="flex gap-3">
                    <input
                        type="text"
                        id="code-manuel"
                        placeholder="Ex: SENRDV-050BD957D155F31B"
                        class="flex-1 px-4 py-3 rounded-xl border-2 border-gray-100 bg-gray-50 text-sm font-mono focus:outline-none focus:border-blue-500 uppercase"
                        oninput="this.value = this.value.toUpperCase()"
                        onkeypress="if(event.key==='Enter') validerCodeManuel()"
                    />
                    <button onclick="validerCodeManuel()"
                        class="px-5 py-3 bg-[#003F8A] text-white font-bold rounded-xl hover:bg-blue-900 transition-all text-sm">
                        Valider →
                    </button>
                </div>
            </div>
        </div>

        <!-- résultat du scan -->
        <div id="resultat" class="hidden"></div>

        <!-- historique des scans du jour -->
        <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
            <div class="px-5 py-4 border-b border-gray-50 flex items-center justify-between">
                <p class="font-bold text-gray-900 text-sm">Scans du jour</p>
                <span id="scan-count" class="px-2.5 py-1 bg-blue-50 text-blue-600 rounded-full text-xs font-bold">0</span>
            </div>
            <div id="historique-scans" class="divide-y divide-gray-50">
                <p class="text-center text-gray-400 text-sm py-6">Aucun scan pour l'instant</p>
            </div>
        </div>
    </div>

    <script>
        let html5QrCode = null;
        let scanActif   = false;
        let historiqueScans = [];

        window.addEventListener('DOMContentLoaded', () => {
            const user = requireAuth(['gerant', 'admin_hopital', 'super_admin']);
            if (!user) return;
            document.getElementById('user-info').textContent = `${user.prenom} ${user.nom}`;
        });

        function setMode(mode) {
            // j'arrête le scan caméra si on change de mode
            if (scanActif) toggleScan();

            document.getElementById('mode-camera').classList.toggle('hidden', mode !== 'camera');
            document.getElementById('mode-manuel').classList.toggle('hidden', mode !== 'manuel');

            document.getElementById('btn-camera').className = `flex-1 py-2.5 rounded-xl text-sm font-semibold transition-all ${mode === 'camera' ? 'bg-[#003F8A] text-white' : 'text-gray-500'}`;
            document.getElementById('btn-manuel').className = `flex-1 py-2.5 rounded-xl text-sm font-semibold transition-all ${mode === 'manuel' ? 'bg-[#003F8A] text-white' : 'text-gray-500'}`;
        }

        async function toggleScan() {
            const btn = document.getElementById('btn-scan');

            if (!scanActif) {
                // je démarre la caméra
                html5QrCode = new Html5Qrcode("reader");
                try {
                    await html5QrCode.start(
                        { facingMode: "environment" },
                        { fps: 10, qrbox: { width: 250, height: 250 } },
                        async (codeQR) => {
                            // je stoppe le scan dès qu'un code est détecté
                            await toggleScan();
                            await traiterCode(codeQR);
                        },
                        (err) => {}
                    );
                    scanActif = true;
                    btn.textContent = '⏹ Arrêter le scan';
                    btn.className = 'flex-1 py-3 bg-red-500 hover:bg-red-600 text-white font-bold rounded-xl transition-all text-sm';
                } catch(e) {
                    toast('Impossible d\'accéder à la caméra. Utilisez la saisie manuelle.', 'error');
                }
            } else {
                // j'arrête la caméra
                if (html5QrCode) {
                    await html5QrCode.stop();
                    html5QrCode = null;
                }
                scanActif = false;
                btn.textContent = '▶ Démarrer le scan';
                btn.className = 'flex-1 py-3 bg-[#003F8A] hover:bg-blue-900 text-white font-bold rounded-xl transition-all text-sm';
            }
        }

        function validerCodeManuel() {
            const code = document.getElementById('code-manuel').value.trim();
            if (!code) { toast('Entrez un code QR', 'error'); return; }
            traiterCode(code);
        }

        async function traiterCode(codeQR) {
            // j'affiche un état de chargement
            afficherResultat('loading', { code: codeQR });

            const data = await api('/tickets/scanner.php', {
                method: 'POST',
                body: JSON.stringify({ code_qr: codeQR })
            });

            if (data.succes) {
                afficherResultat('succes', { ...data, code: codeQR });
                ajouterHistorique(data, codeQR, true);
                toast(data.prioritaire ? '⭐ Patient prioritaire enregistré !' : '✅ Patient enregistré', 'success');
            } else {
                afficherResultat('erreur', { erreur: data.erreur, code: codeQR });
                ajouterHistorique(data, codeQR, false);
                toast(data.erreur || 'Code invalide', 'error');
            }

            // je vide le champ manuel après traitement
            document.getElementById('code-manuel').value = '';
        }

        function afficherResultat(type, data) {
            const el = document.getElementById('resultat');
            el.classList.remove('hidden');

            if (type === 'loading') {
                el.innerHTML = `
                    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 mb-4 flex items-center gap-4">
                        <div class="w-10 h-10 border-4 border-blue-200 border-t-blue-600 rounded-full animate-spin"></div>
                        <div>
                            <p class="font-bold text-gray-900">Vérification en cours...</p>
                            <p class="text-xs text-gray-400 font-mono mt-0.5">${data.code}</p>
                        </div>
                    </div>`;
                return;
            }

            if (type === 'succes') {
                const prioritaire = data.prioritaire;
                el.innerHTML = `
                    <div class="rounded-2xl border-2 shadow-sm p-6 mb-4 ${prioritaire ? 'bg-green-50 border-green-200' : 'bg-blue-50 border-blue-200'}">
                        <div class="flex items-center gap-3 mb-4">
                            <div class="w-12 h-12 rounded-xl ${prioritaire ? 'bg-green-500' : 'bg-blue-500'} flex items-center justify-center text-2xl">
                                ${prioritaire ? '⭐' : '✅'}
                            </div>
                            <div>
                                <p class="font-black text-gray-900 text-lg">${data.patient?.prenom} ${data.patient?.nom}</p>
                                <p class="text-sm ${prioritaire ? 'text-green-700' : 'text-blue-700'} font-semibold">
                                    ${prioritaire ? 'TICKET PRIORITAIRE' : 'Ticket standard'}
                                </p>
                            </div>
                        </div>
                        <div class="grid grid-cols-2 gap-3">
                            <div class="bg-white rounded-xl p-3">
                                <p class="text-xs text-gray-400 uppercase tracking-wide">Service</p>
                                <p class="font-semibold text-gray-900 text-sm mt-0.5">${data.patient?.service}</p>
                            </div>
                            <div class="bg-white rounded-xl p-3">
                                <p class="text-xs text-gray-400 uppercase tracking-wide">RDV prévu</p>
                                <p class="font-bold ${prioritaire ? 'text-green-600' : 'text-blue-600'} text-base mt-0.5">${formatHeure(data.patient?.heure_rdv)}</p>
                            </div>
                        </div>
                        ${data.alerte ? `
                        <div class="mt-3 p-3 bg-amber-50 border border-amber-200 rounded-xl">
                            <p class="text-xs font-bold text-amber-700">⚠️ ${data.alerte}</p>
                        </div>` : ''}
                        ${data.message && !data.alerte ? `
                        <p class="mt-3 text-xs text-gray-500">${data.message}</p>` : ''}
                    </div>`;
                return;
            }

            if (type === 'erreur') {
                el.innerHTML = `
                    <div class="bg-red-50 border-2 border-red-200 rounded-2xl p-5 mb-4">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 rounded-xl bg-red-500 flex items-center justify-center text-xl">❌</div>
                            <div>
                                <p class="font-bold text-red-900">Scan invalide</p>
                                <p class="text-sm text-red-700 mt-0.5">${data.erreur}</p>
                                <p class="text-xs text-red-400 font-mono mt-1">${data.code}</p>
                            </div>
                        </div>
                    </div>`;
            }
        }

        function ajouterHistorique(data, codeQR, succes) {
            const heure = new Date().toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
            historiqueScans.unshift({ data, codeQR, succes, heure });

            document.getElementById('scan-count').textContent = historiqueScans.length;

            const container = document.getElementById('historique-scans');
            container.innerHTML = historiqueScans.slice(0, 10).map(scan => `
                <div class="px-5 py-3 flex items-center gap-3">
                    <span class="text-lg">${scan.succes ? (scan.data.prioritaire ? '⭐' : '✅') : '❌'}</span>
                    <div class="flex-1 min-w-0">
                        <p class="font-semibold text-gray-900 text-sm truncate">
                            ${scan.succes ? `${scan.data.patient?.prenom} ${scan.data.patient?.nom}` : 'Code invalide'}
                        </p>
                        <p class="text-xs text-gray-400 font-mono truncate">${scan.codeQR}</p>
                    </div>
                    <span class="text-xs text-gray-400 flex-shrink-0">${scan.heure}</span>
                </div>
            `).join('');
        }
    </script>
</body>
</html>