<?php
session_start();

// =====================
// 1) Connexion DB
// =====================
try {
    $pdo = new PDO("mysql:host=localhost;dbname=tostrlgj_mariage_db;charset=utf8mb4", 'tostrlgj_voldy', 'Voldy25@Ilus', [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
} catch (PDOException $e) {
    die("Erreur DB : " . $e->getMessage());
}

// =====================
// 2) API pour chercher les invités
// =====================
if (isset($_GET['api']) && $_GET['api'] === 'search') {
    header('Content-Type: application/json; charset=utf-8');
    $q = $_GET['q'] ?? '';

    if (strlen($q) < 2) {
        echo json_encode(['results' => []]);
        exit;
    }

    $stmt = $pdo->prepare("
        SELECT id, code_invitation, titre1, nom, titre2, nom2, type_invitation, table_num, status, telephone, email
        FROM invites 
        WHERE nom LIKE ? OR nom2 LIKE ? OR code_invitation LIKE ? OR telephone LIKE ?
        LIMIT 20
    ");
    $search = "%$q%";
    $stmt->execute([$search, $search, $search, $search]);
    $results = $stmt->fetchAll();

    echo json_encode(['results' => $results]);
    exit;
}

// =====================
// 3) API pour valider un invité
// =====================
if (isset($_GET['api']) && $_GET['api'] === 'validate') {
    header('Content-Type: application/json; charset=utf-8');
    $code = $_GET['code'] ?? '';

    if (empty($code)) {
        echo json_encode(['success' => false, 'message' => 'Code invalide']);
        exit;
    }

    $stmt = $pdo->prepare("SELECT * FROM invites WHERE code_invitation = ?");
    $stmt->execute([$code]);
    $guest = $stmt->fetch();

    if (!$guest) {
        echo json_encode(['success' => false, 'message' => 'Code non trouvé']);
        exit;
    }

    // Mettre à jour le statut
    $updateStmt = $pdo->prepare("UPDATE invites SET status = 1 WHERE id = ?");
    $updateStmt->execute([$guest['id']]);

    echo json_encode([
        'success' => true,
        'message' => 'Invité validé !',
        'guest' => $guest
    ]);
    exit;
}

// =====================
// 4) Stats
// =====================
$statsStmt = $pdo->query("SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as confirmed
FROM invites");
$stats = $statsStmt->fetch();

// =====================
// 5) Liste initiale des invités
// =====================
$stmt = $pdo->query("SELECT id, code_invitation, titre1, nom, titre2, nom2, type_invitation, table_num, status, telephone FROM invites ORDER BY date_created DESC LIMIT 150");
$invites = $stmt->fetchAll();

// =====================
// 6) Afficher la page HTML (si pas d'API)
// =====================
?>
<!DOCTYPE html>
<html lang="fr">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Check-in des Invités</title>
    <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700;900&family=Montserrat:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Montserrat', sans-serif;
            background: linear-gradient(135deg, #f5f5f2 0%, #e8e6e1 100%);
            color: #2c2c2c;
            min-height: 100vh;
        }

        .header {
            background: linear-gradient(135deg, #2c2c2c 0%, #1a1a1a 100%);
            color: white;
            padding: 2rem;
            text-align: center;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
        }

        .header-title {
            font-family: 'Playfair Display', serif;
            font-size: 2rem;
            margin-bottom: 0.5rem;
        }

        .header-subtitle {
            color: #d4a574;
            font-size: 0.95rem;
        }

        .container {
            max-width: 500px;
            margin: 0 auto;
            padding: 2rem 1rem;
        }

        /* Stats Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
        }

        .stat-number {
            font-family: 'Playfair Display', serif;
            font-size: 2rem;
            font-weight: 900;
            color: #d4a574;
        }

        .stat-label {
            color: #999;
            font-size: 0.85rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-top: 0.5rem;
        }

        .progress-bar {
            width: 100%;
            height: 4px;
            background: #e0e0e0;
            border-radius: 4px;
            overflow: hidden;
            margin-top: 1rem;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #d4a574 0%, #8b6f47 100%);
            transition: width 0.3s ease;
        }

        /* Search Section */
        .search-section {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            margin-bottom: 2rem;
        }

        .search-input {
            width: 100%;
            padding: 1rem;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 1rem;
            font-family: 'Montserrat', sans-serif;
            transition: all 0.3s ease;
        }

        .search-input:focus {
            outline: none;
            border-color: #d4a574;
            box-shadow: 0 0 0 3px rgba(212, 165, 116, 0.1);
        }

        .search-results {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border-radius: 8px;
            max-height: 300px;
            overflow-y: auto;
            z-index: 100;
            display: none;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            margin-top: 0.5rem;
        }

        .search-results.show {
            display: block;
        }

        .search-result-item {
            padding: 1rem;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: background 0.2s ease;
        }

        .search-result-item:hover {
            background: #f9f9f7;
        }

        .search-result-name {
            font-weight: 600;
            color: #2c2c2c;
        }

        .search-result-meta {
            font-size: 0.85rem;
            color: #999;
            margin-top: 0.3rem;
        }

        /* Buttons */
        .button-group {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .btn {
            padding: 1.2rem;
            border-radius: 12px;
            border: none;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 0.5rem;
            text-decoration: none;
            font-family: 'Montserrat', sans-serif;
            font-size: 0.9rem;
        }

        .btn-camera {
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            color: white;
            box-shadow: 0 5px 15px rgba(212, 165, 116, 0.3);
        }

        .btn-camera:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(212, 165, 116, 0.4);
        }

        .btn-list {
            background: white;
            color: #d4a574;
            border: 2px solid #d4a574;
        }

        .btn-list:hover {
            background: #f9f9f7;
            transform: translateY(-3px);
        }

        .btn-icon {
            font-size: 1.5rem;
        }

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            animation: fadeIn 0.3s ease;
        }

        .modal.show {
            display: flex;
            align-items: flex-end;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }

        .modal-content {
            background: white;
            width: 100%;
            border-radius: 15px 15px 0 0;
            max-height: 90vh;
            overflow-y: auto;
            animation: slideUp 0.3s ease;
        }

        @keyframes slideUp {
            from {
                transform: translateY(100px);
                opacity: 0;
            }

            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .modal-header {
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            color: white;
            padding: 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-radius: 15px 15px 0 0;
        }

        .modal-title {
            font-family: 'Playfair Display', serif;
            font-size: 1.5rem;
        }

        .modal-close {
            background: none;
            border: none;
            color: white;
            font-size: 1.5rem;
            cursor: pointer;
        }

        .modal-body {
            padding: 1.5rem;
        }

        #scanner {
            width: 100%;
            max-width: 100%;
            border-radius: 8px;
            margin-bottom: 1rem;
        }

        .scanner-buttons {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
            margin-top: 1rem;
        }

        .btn-close {
            background: #6c757d;
            color: white;
        }

        .btn-close:hover {
            background: #5a6268;
        }

        /* Guest List */
        .guest-list {
            padding: 1.5rem;
        }

        .guest-item {
            background: #f9f9f7;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            border-left: 4px solid #d4a574;
            transition: all 0.2s ease;
        }

        .guest-item.checked {
            background: rgba(40, 167, 69, 0.1);
            border-left-color: #28a745;
        }

        .guest-name {
            font-weight: 600;
            color: #2c2c2c;
        }

        .guest-meta {
            font-size: 0.85rem;
            color: #999;
            margin-top: 0.3rem;
        }

        .guest-status {
            display: inline-block;
            padding: 0.3rem 0.8rem;
            background: #28a745;
            color: white;
            border-radius: 4px;
            font-size: 0.75rem;
            margin-top: 0.5rem;
            font-weight: 600;
        }

        .guest-status.pending {
            background: #ffc107;
            color: #2c2c2c;
        }

        /* Notification */
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            background: white;
            padding: 1.5rem;
            border-radius: 8px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            z-index: 2000;
            animation: slideInRight 0.3s ease;
        }

        .notification.success {
            border-left: 4px solid #28a745;
        }

        .notification.error {
            border-left: 4px solid #dc3545;
        }

        @keyframes slideInRight {
            from {
                transform: translateX(400px);
                opacity: 0;
            }

            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        /* Confetti */
        .confetti {
            position: fixed;
            width: 10px;
            height: 10px;
            pointer-events: none;
            z-index: 999;
        }

        @media (max-width: 768px) {
            .container {
                max-width: 100%;
            }

            .header-title {
                font-size: 1.5rem;
            }
        }
    </style>
</head>

<body>
    <!-- Header -->
    <div class="header">
        <h1 class="header-title">
            <i class="fas fa-clipboard-check"></i> Check-in
        </h1>
        <p class="header-subtitle">Aaron & Princillia - 20 Décembre 2025</p>
    </div>

    <!-- Main Container -->
    <div class="container">
        <!-- Stats -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number"><?= $stats['total'] ?? 0 ?></div>
                <div class="stat-label">Total</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?= $stats['confirmed'] ?? 0 ?></div>
                <div class="stat-label">Confirmés</div>
                <div class="progress-bar">
                    <div class="progress-fill" style="width: <?= ($stats['confirmed'] / max($stats['total'], 1) * 100) ?>%"></div>
                </div>
            </div>
        </div>

        <!-- Search Section -->
        <div class="search-section">
            <div style="position: relative;">
                <input type="text" id="searchInput" class="search-input" placeholder="🔍 Chercher un invité...">
                <div class="search-results" id="searchResults"></div>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="button-group">
            <button class="btn btn-camera" onclick="startCameraScan()">
                <i class="btn-icon fas fa-camera"></i>
                Scanner QR
            </button>
            <button class="btn btn-list" onclick="openGuestList()">
                <i class="btn-icon fas fa-list"></i>
                Liste des invités
            </button>
        </div>
    </div>

    <!-- Scanner Modal -->
    <div id="scannerModal" class="modal">
        <div class="modal-content" style="width: 100%;">
            <div class="modal-header">
                <h2 class="modal-title">Scanner QR</h2>
                <button class="modal-close" onclick="closeScanner()">×</button>
            </div>
            <div class="modal-body">
                <video id="scanner" playsinline></video>
                <canvas id="canvas" style="display: none;"></canvas>
                <div class="scanner-buttons">
                    <button class="btn btn-close" onclick="closeScanner()">Fermer</button>
                    <button class="btn" style="background: #d4a574; color: white;" onclick="toggleCamera()">
                        <i class="fas fa-power-off"></i> Arrêter
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Guest List Modal -->
    <div id="guestListModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">Liste des invités</h2>
                <button class="modal-close" onclick="closeGuestList()">×</button>
            </div>
            <div class="guest-list" id="guestList">
                <!-- Populated by JS -->
            </div>
        </div>
    </div>

    <script>
        let stream = null;
        const invites = <?= json_encode($invites) ?>;

        // =====================
        // Search Function
        // =====================
        document.getElementById('searchInput').addEventListener('input', async function() {
            const q = this.value.trim();
            const resultsDiv = document.getElementById('searchResults');

            if (q.length < 2) {
                resultsDiv.classList.remove('show');
                return;
            }

            try {
                const response = await fetch(`./check-in.php?api=search&q=${encodeURIComponent(q)}`);
                const data = await response.json();

                if (data.results.length === 0) {
                    resultsDiv.innerHTML = '<div style="padding: 1rem; text-align: center; color: #999;">Aucun résultat</div>';
                } else {
                    resultsDiv.innerHTML = data.results.map(guest => `
                        <div class="search-result-item" onclick="stopCameraStream(); validateGuest('${guest.code_invitation}')">
                            <div class="search-result-name">${escapeHtml(guest.titre1 || '')} ${escapeHtml(guest.nom)}</div>
                            <div class="search-result-meta">Code: ${escapeHtml(guest.code_invitation)} • Table ${guest.table_num}</div>
                        </div>
                    `).join('');
                }

                resultsDiv.classList.add('show');
            } catch (error) {
                console.error('Erreur recherche:', error);
            }
        });

        // =====================
// Nouvelle fonction : Scan via caméra cachée
// =====================
function startCameraScan() {
    const video = document.getElementById('scanner');
    const canvas = document.getElementById('canvas');
    let stream = null;

    navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } })
        .then(s => {
            stream = s;
            window.currentStream = stream; // Stocker le flux pour l'arrêter plus tard
            video.srcObject = stream;
            video.play();

            // Masquer la vidéo
            video.style.display = 'none';

            // Afficher un message temporaire
            showNotification('Scannez votre QR code...', 'success');

            scanQR();
        })
        .catch(err => {
            showNotification('Impossible d\'accéder à la caméra', 'error');
        });

    function scanQR() {
        if (!video || video.readyState !== video.HAVE_ENOUGH_DATA) {
            requestAnimationFrame(scanQR);
            return;
        }

        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0);

        try {
            const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
            const code = jsQR(imageData.data, imageData.width, imageData.height);

            if (code && code.data) {
                console.log("QR détecté :", code.data);

                // Extraire l'ID de l'URL
                const url = new URL(code.data);
                const id = url.searchParams.get('id');

                if (id) {
                    // Arrêter la caméra avant de rediriger
                    if (window.currentStream) {
                        window.currentStream.getTracks().forEach(track => track.stop());
                        window.currentStream = null;
                    }
                    // Rediriger vers verify_invite.php avec l'ID
                    window.location.href = `verify_invite.php?id=${id}`;
                } else {
                    showNotification('QR invalide (aucun ID)', 'error');
                }
            } else {
                requestAnimationFrame(scanQR);
            }
        } catch (e) {
            console.error("Erreur scan:", e);
            requestAnimationFrame(scanQR);
        }
    }
}
        // =====================
        // Validate Guest
        // =====================
        async function validateGuest(code) {
            try {
                console.log("Code envoyé:", code);

                // Utilise une URL absolue pour éviter les problèmes de chemin
                const response = await fetch(`https://vkiz-digital.website/aaronandprincillia/check-in.php?api=validate&code=${encodeURIComponent(code)}`);
                const data = await response.json();

                console.log("Réponse du serveur:", data);

                if (data.success) {
                    const guestId = data.guest.id;
                    showNotification(`✅ ${escapeHtml(data.guest.titre1 || '')} ${escapeHtml(data.guest.nom)} validé!`, 'success');
                    createConfetti();
                    setTimeout(() => {
                        window.location.href = `https://vkiz-digital.website/aaronandprincillia/verify_invite.php?id=${guestId}`;
                    }, 1500);
                } else {
                    showNotification(data.message, 'error');
                }
            } catch (error) {
                console.error('Erreur de connexion ou réponse invalide:', error);
                showNotification('Erreur de connexion ou réponse invalide', 'error');
            }
        }

        // =====================
        // Guest List
        // =====================
        function openGuestList() {
            const guestList = document.getElementById('guestList');
            guestList.innerHTML = invites.map(guest => `
                <div class="guest-item ${guest.status ? 'checked' : ''}">
                    <div class="guest-name">${escapeHtml(guest.titre1 || '')} ${escapeHtml(guest.nom)}</div>
                    <div class="guest-meta">
                        Code: ${escapeHtml(guest.code_invitation)} • Table ${guest.table_num}
                        ${guest.type_invitation === 'couple' && guest.nom2 ? `<br>+ ${escapeHtml(guest.titre2 || '')} ${escapeHtml(guest.nom2)}` : ''}
                    </div>
                    <div class="guest-status ${guest.status ? '' : 'pending'}">
                        ${guest.status ? '✓ Confirmé' : '⏳ En attente'}
                    </div>
                </div>
            `).join('');
            document.getElementById('guestListModal').classList.add('show');
        }

        function closeGuestList() {
            document.getElementById('guestListModal').classList.remove('show');
        }

        // =====================
        // Notifications & Effects
        // =====================
        function showNotification(message, type) {
            const notification = document.createElement('div');
            notification.className = `notification ${type}`;
            notification.textContent = message;
            document.body.appendChild(notification);

            setTimeout(() => notification.remove(), 3000);
        }

        function createConfetti() {
    // Palette de couleurs du mariage : doré, beige, marron clair
    const colors = ['#d4a574', '#8b6f47', '#e7c04d', '#f3d89c', '#c19a6b'];
    
    for (let i = 0; i < 40; i++) {
        const confetti = document.createElement('div');
        confetti.style.position = 'fixed';
        confetti.style.left = Math.random() * 100 + 'vw';
        confetti.style.top = '-10px';
        confetti.style.width = `${Math.random() * 8 + 6}px`;
        confetti.style.height = `${Math.random() * 8 + 6}px`;
        confetti.style.zIndex = '9999';
        confetti.style.pointerEvents = 'none';
        confetti.style.opacity = '0.9';
        confetti.style.fontSize = '10px';
        confetti.style.fontFamily = "'Playfair Display', 'Great Vibes', serif";
        confetti.style.color = colors[Math.floor(Math.random() * colors.length)];
        confetti.style.display = 'flex';
        confetti.style.alignItems = 'center';
        confetti.style.justifyContent = 'center';
        confetti.style.textAlign = 'center';

        // Alternance subtile entre cœur et "A & P"
        if (Math.random() > 0.5) {
            // Cœur doré, fin et élégant
            confetti.style.clipPath = 'polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%)';
            confetti.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
        } else {
            // Texte "A & P" avec police élégante
            confetti.style.backgroundColor = 'transparent';
            confetti.textContent = 'A & P';
            confetti.style.fontWeight = 'normal';
            confetti.style.letterSpacing = '0.5px';
        }

        document.body.appendChild(confetti);

        // Animation douce et naturelle
        const animation = confetti.animate([
            { transform: 'translateY(0) rotate(0deg)', opacity: 1 },
            { transform: `translateY(${window.innerHeight}px) rotate(${Math.random() * 720}deg)`, opacity: 0 }
        ], {
            duration: 6000 + Math.random() * 4000,
            easing: 'cubic-bezier(0.2, 0.8, 0.3, 1)',
            delay: Math.random() * 500
        });

        animation.onfinish = () => confetti.remove();
    }
}
        // Add fall animation
        const style = document.createElement('style');
        style.textContent = `
            @keyframes fall {
                to {
                    transform: translateY(100vh) rotate(360deg);
                    opacity: 0;
                }
            }
        `;
        document.head.appendChild(style);

        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '<',
                '>': '>',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, m => map[m]);
        }

        // =====================
        // pour stopper la camera
        function stopCameraStream() {
    if (window.currentStream) {
        window.currentStream.getTracks().forEach(track => track.stop());
        window.currentStream = null;
    }
}

        // Close modals on outside click
        window.onclick = function(event) {
            const scannerModal = document.getElementById('scannerModal');
            const guestListModal = document.getElementById('guestListModal');

            if (event.target === scannerModal) {
                closeScanner();
            }
            if (event.target === guestListModal) {
                closeGuestList();
            }
        };
    </script>
</body>

</html>