<?php

/**
 * Event-Aware Guest Check-in Terminal View
 * Location: app/views/operation/scanner.php
 *
 * Variables expected:
 *   $title          — string — Page title.
 *   $event          — array — Current wedding event row.
 *   $stats          — array — Event-specific check-in stats.
 *   $search         — string — Current guest search query.
 *   $searchResults  — array — List of found guests.
 *   $errors         — array — Validation/session errors.
 *   $success        — string|null — Success flash message.
 *
 * @package Inveetaire
 * @ref     RC-013
 */

$role = \App\Core\Session::get('role_snapshot') === 'crew' ? 'crew' : 'couple';

?>

<script src="<?= asset('/assets/js/html5-qrcode.min.js') ?>" defer></script>

<div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 space-y-8 py-4"
     x-data="{
        search: '<?= escape_html($search ?? '') ?>',
        searchLoading: false,
        selectedIndex: -1,
        navigateSearch() {
            this.searchLoading = true;
            this.selectedIndex = -1;
            let url = new URL(window.location.href);
            url.searchParams.set('search', this.search);
            url.searchParams.set('ajax', '1');
            fetch(url.toString())
                .then(res => res.text())
                .then(html => {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');
                    const wrapper = doc.getElementById('scanner-search-wrapper');
                    if (wrapper) {
                        document.getElementById('scanner-search-wrapper').innerHTML = wrapper.innerHTML;
                    }
                    window.history.pushState({}, '', url.toString());
                    this.searchLoading = false;
                    
                    // Highlight first row automatically
                    this.selectedIndex = 0;
                    setTimeout(() => {
                        const rows = document.querySelectorAll('#scanner-search-wrapper tbody tr');
                        this.highlightRows(rows);
                    }, 50);
                })
                .catch(err => {
                    console.error(err);
                    this.searchLoading = false;
                });
        },
        selectNextRow() {
            const rows = document.querySelectorAll('#scanner-search-wrapper tbody tr');
            if (rows.length === 0) return;
            this.selectedIndex = (this.selectedIndex + 1) % rows.length;
            this.highlightRows(rows);
        },
        selectPrevRow() {
            const rows = document.querySelectorAll('#scanner-search-wrapper tbody tr');
            if (rows.length === 0) return;
            this.selectedIndex = (this.selectedIndex - 1 + rows.length) % rows.length;
            this.highlightRows(rows);
        },
        highlightRows(rows) {
            rows.forEach((row, index) => {
                if (index === this.selectedIndex) {
                    row.classList.add('bg-slate-200', 'font-black');
                    row.scrollIntoView({ block: 'nearest' });
                } else {
                    row.classList.remove('bg-slate-200', 'font-black');
                }
            });
        },
        submitSelectedRow() {
            const rows = document.querySelectorAll('#scanner-search-wrapper tbody tr');
            if (rows.length === 0) return;
            const targetIndex = this.selectedIndex >= 0 ? this.selectedIndex : 0;
            const targetRow = rows[targetIndex];
            if (targetRow) {
                const link = targetRow.querySelector('a');
                if (link) {
                    link.click();
                }
            }
        }
     }">

    <!-- ── 1. HEADER & EVENT IDENTITY ─────────────────────────────────── -->
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 border-b border-slate-200 pb-4">
        <div>
            <span class="bg-blue-100 text-blue-750 text-[10px] font-black uppercase tracking-wider px-2.5 py-1 rounded-full">
                Workspace Event Terminal
            </span>
            <h1 class="text-3xl font-black text-slate-800 tracking-tight mt-1.5"><?= escape_html($event['event_name']) ?></h1>
            <p class="text-xs text-slate-400 mt-1 flex items-center gap-2">
                <span>📍 <?= escape_html($event['venue_name']) ?></span>
                <span>•</span>
                <span>📅 <?= (new \DateTime($event['event_date']))->format('d M Y — H:i') ?></span>
            </p>
        </div>
        <div class="flex gap-2">
            <span class="text-xs bg-emerald-50 border border-emerald-200 text-emerald-700 font-bold px-3 py-1.5 rounded-xl">
                Active Session
            </span>
        </div>
    </div>

    <!-- Notices / Banners -->
    <?php if (!empty($errors)): ?>
        <div class="rounded-2xl bg-red-50 border border-red-200 p-4 text-xs text-red-700 shadow-sm max-w-xl mx-auto">
            <ul class="list-disc pl-4 space-y-1">
                <?php foreach ($errors as $err): ?>
                    <li><?= escape_html($err) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if ($success !== null): ?>
        <div class="rounded-2xl bg-emerald-50 border border-emerald-200 p-4 text-xs text-emerald-800 font-bold text-center shadow-sm max-w-xl mx-auto">
            <?= escape_html($success) ?>
        </div>
    <?php endif; ?>

    <!-- ── 2. EVENT ATTENDANCE METRICS ────────────────────────────────── -->
    <div class="grid grid-cols-2 lg:grid-cols-5 gap-4">
        <div class="card p-4 flex items-center justify-between">
            <div>
                <span class="text-[10px] text-slate-400 uppercase font-bold tracking-wider block">Expected Guests</span>
                <span class="text-2xl font-black text-slate-800 mt-1 block font-mono"><?= (int) $stats['expected_guests'] ?> <span class="text-xs text-slate-400 font-normal">pax: <?= (int) $stats['expected_pax'] ?></span></span>
            </div>
            <span class="w-10 h-10 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center text-lg"><i class="fa-solid fa-users"></i></span>
        </div>

        <div class="card p-4 flex items-center justify-between">
            <div>
                <span class="text-[10px] text-slate-400 uppercase font-bold tracking-wider block">Checked In</span>
                <span class="text-2xl font-black text-green-700 mt-1 block font-mono"><?= (int) $stats['checked_in_count'] ?></span>
            </div>
            <span class="w-10 h-10 rounded-xl bg-green-50 text-green-600 flex items-center justify-center text-lg"><i class="fa-solid fa-circle-check"></i></span>
        </div>

        <div class="card p-4 flex items-center justify-between">
            <div>
                <span class="text-[10px] text-slate-400 uppercase font-bold tracking-wider block">Pending</span>
                <span class="text-2xl font-black text-amber-700 mt-1 block font-mono"><?= (int) $stats['pending_count'] ?></span>
            </div>
            <span class="w-10 h-10 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center text-lg"><i class="fa-solid fa-hourglass-half"></i></span>
        </div>

        <div class="card p-4 flex items-center justify-between">
            <div>
                <span class="text-[10px] text-slate-400 uppercase font-bold tracking-wider block">Manual Overrides</span>
                <span class="text-2xl font-black text-slate-700 mt-1 block font-mono"><?= (int) $stats['overrides_count'] ?></span>
            </div>
            <span class="w-10 h-10 rounded-xl bg-slate-100 text-slate-600 flex items-center justify-center text-lg"><i class="fa-solid fa-user-shield"></i></span>
        </div>

        <div class="card p-4 flex items-center justify-between col-span-2 lg:col-span-1">
            <div>
                <span class="text-[10px] text-slate-400 uppercase font-bold tracking-wider block">Rejected Entries</span>
                <span class="text-2xl font-black text-red-700 mt-1 block font-mono"><?= (int) $stats['rejected_count'] ?></span>
            </div>
            <span class="w-10 h-10 rounded-xl bg-red-50 text-red-600 flex items-center justify-center text-lg"><i class="fa-solid fa-ban"></i></span>
        </div>
    </div>

    <!-- ── 3. WORKSPACE TERMINAL (QR & SEARCH) ────────────────────────── -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
        
        <!-- Barcode / QR Scanner Column -->
        <div class="card p-0 overflow-hidden shadow-lg border border-slate-200">
            <div class="p-4 border-b border-slate-100 bg-slate-50/50 text-center font-bold text-[10px] text-slate-400 uppercase tracking-widest">
                <i class="fa-solid fa-qrcode mr-1"></i> Simulated Barcode / QR Scanner Input
            </div>
            <form action="<?= url("/app/{$role}/operation/event/{$event['id']}/checkin") ?>" method="POST" class="p-6 space-y-4">
                <?= csrf_field() ?>
                
                <div class="form-group text-center">
                    <label for="scanner_input" class="form-label text-[10px] uppercase tracking-wider text-slate-400 font-black mb-3 block">
                        Invitation QR Code Token (16-char Hex)
                    </label>
                    <input 
                        type="text" 
                        id="scanner_input" 
                        name="guest_token" 
                        placeholder="Scan QR or Enter Token..." 
                        class="form-input w-full text-center text-xl font-mono font-bold tracking-widest p-4 text-slate-800 bg-slate-50 border-2 border-slate-200 focus:border-blue-500 rounded-xl"
                        required
                        autocomplete="off"
                        autofocus
                    >
                    <span class="text-[10px] text-slate-400 block mt-2">
                        Keep cursor focused in the box above to receive physical laser scanner inputs automatically.
                    </span>
                </div>

                <div class="form-group">
                    <button type="button" onclick="startScanner()" class="btn btn-secondary w-full py-3 rounded-xl font-bold text-xs flex items-center justify-center gap-2" style="background:#f1f5f9; color:#475569; border:1px solid #cbd5e1;">
                        <i class="fa-solid fa-camera mr-1"></i> Scan QR via Camera
                    </button>
                </div>

                <button type="submit" class="btn btn-primary w-full py-4 rounded-xl font-bold text-sm tracking-wide flex items-center justify-center gap-1.5">
                    <i class="fa-solid fa-magnifying-glass"></i> Lookup Guest Code
                </button>
            </form>
        </div>

        <!-- Search Guest Column -->
        <div class="card p-6 shadow-lg border border-slate-200 flex flex-col justify-between">
            <div class="space-y-4">
                <div class="border-b border-slate-100 pb-2">
                    <h2 class="text-sm font-bold text-slate-800"><i class="fa-solid fa-magnifying-glass mr-1"></i> Guest Lookup Search</h2>
                    <p class="text-[10px] text-slate-400">Search guests by Name, Phone Number, or Guest Token to check in manually.</p>
                </div>

                <form method="GET" action="<?= url("/app/{$role}/operation/event/{$event['id']}/checkin") ?>" @submit.prevent="navigateSearch()" class="flex gap-2">
                    <input 
                        type="text" 
                        name="search" 
                        x-model.debounce.250ms="search"
                        @input.debounce.250ms="navigateSearch()"
                        @keydown.arrow-down.prevent="selectNextRow()"
                        @keydown.arrow-up.prevent="selectPrevRow()"
                        @keydown.enter.prevent="submitSelectedRow()"
                        value="<?= escape_html($search) ?>" 
                        placeholder="Search Guest name, phone, or token..." 
                        class="form-input text-xs w-full rounded-xl"
                        autocomplete="off"
                    >
                    <button type="submit" class="btn btn-secondary text-xs font-semibold px-4 rounded-xl">
                        Search
                    </button>
                </form>

                <div id="scanner-search-wrapper" class="w-full">
                    <div x-show="searchLoading" class="flex flex-col items-center justify-center py-8 space-y-2">
                        <i class="fa-solid fa-spinner animate-spin text-xl text-blue-500"></i>
                        <span class="text-xs text-slate-400">Searching guest list...</span>
                    </div>
                    <div x-show="!searchLoading">
                        <!-- Search Results Area -->
                        <?php if ($search !== ''): ?>
                            <div class="mt-4 space-y-2 max-h-60 overflow-y-auto pr-1 border border-slate-100 rounded-xl p-2 bg-slate-50/50">
                                <?php if (empty($searchResults)): ?>
                                    <div class="empty-state-elegant py-6" style="padding: 1.5rem 1rem;">
                                        <div class="empty-state-icon" style="font-size: 1.5rem; margin-bottom: 0.25rem;">
                                            <i class="fa-solid fa-magnifying-glass text-slate-300"></i>
                                        </div>
                                        <h4 class="empty-state-title" style="font-size: 0.75rem; font-weight: 700;">No guests found</h4>
                                        <p class="empty-state-text" style="font-size: 0.65rem; margin-bottom: 0;">No matching entries found for "<?= escape_html($search) ?>". Try partial matching.</p>
                                    </div>
                                <?php else: ?>
                                    <div class="overflow-x-auto">
                                        <table class="w-full text-left border-collapse text-xxs">
                                            <thead>
                                                <tr class="border-b border-slate-200 text-slate-400 uppercase font-black tracking-wider">
                                                    <th class="py-2 px-1">Guest Name</th>
                                                    <th class="py-2 px-1">Group</th>
                                                    <th class="py-2 px-1 text-center">Pax</th>
                                                    <th class="py-2 px-1 text-right">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody class="divide-y divide-slate-100 text-slate-600">
                                                <?php foreach ($searchResults as $sg): ?>
                                                    <tr class="hover:bg-slate-100 transition-colors">
                                                        <td class="py-2.5 px-1 font-bold text-slate-800">
                                                            <?= escape_html($sg['full_name']) ?>
                                                            <span class="block font-mono text-[9px] text-slate-400 font-normal"><?= escape_html($sg['guest_code']) ?></span>
                                                        </td>
                                                        <td class="py-2.5 px-1 uppercase text-slate-400 font-bold"><?= escape_html($sg['guest_group']) ?></td>
                                                        <td class="py-2.5 px-1 text-center font-bold font-mono"><?= (int) $sg['invited_pax'] ?></td>
                                                        <td class="py-2.5 px-1 text-right">
                                                            <a 
                                                                href="<?= url("/app/{$role}/operation/event/{$event['id']}/guest/{$sg['guest_code']}") ?>" 
                                                                class="btn btn-secondary bg-blue-50 text-blue-700 hover:bg-blue-100 border-blue-100 font-black px-2.5 py-1 text-[9px]"
                                                            >
                                                                Check In
                                                            </a>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>

                        <?php if ($search === ''): ?>
                            <div class="empty-state-elegant py-8 border-dashed" style="padding: 2rem 1rem; border-style: dashed;">
                                <div class="empty-state-icon" style="font-size: 1.75rem; margin-bottom: 0.5rem;">
                                    <i class="fa-solid fa-envelope text-slate-300"></i>
                                </div>
                                <h4 class="empty-state-title" style="font-size: 0.875rem;">Waiting for Search Query</h4>
                                <p class="empty-state-text" style="font-size: 0.75rem; margin-bottom: 0;">Type a name, phone number, or guest token in the lookup search field above.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
        </div>

    </div>

</div>

<!-- ── QR SCANNER MODAL ── -->
<div 
    id="scanner-modal" 
    class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-4" 
    style="display: none; align-items: center; justify-content: center;"
>
    <div class="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl space-y-4 flex flex-col items-center">
        <!-- Modal Header -->
        <div class="w-full flex justify-between items-center border-b border-slate-100 pb-2">
            <h3 class="text-sm font-bold text-slate-800 flex items-center gap-1.5"><i class="fa-solid fa-camera"></i> Scan Invitation QR Code</h3>
            <button type="button" onclick="stopScanner()" class="text-slate-400 hover:text-slate-600 font-bold text-lg flex items-center justify-center"><i class="fa-solid fa-xmark"></i></button>
        </div>
        
        <!-- Webcam status / state info -->
        <div class="w-full flex items-center justify-between bg-slate-50 border border-slate-100 rounded-xl p-2.5">
            <span class="text-[10px] uppercase font-bold text-slate-400">Camera Status</span>
            <span id="scanner-status-badge" class="px-2.5 py-1 rounded-full text-[9px] font-bold bg-slate-100 text-slate-650 flex items-center gap-1">
                <i class="fa-solid fa-spinner animate-spin text-[8px] hidden" id="scanner-status-spinner"></i>
                <span id="scanner-status-text">Inactive</span>
            </span>
        </div>

        <!-- Camera select dropdown (hidden if single webcam or mobile environment) -->
        <div id="camera-selection-container" class="w-full hidden space-y-1">
            <label for="camera-select" class="text-[10px] uppercase font-bold text-slate-400 block">Active Device Source</label>
            <select id="camera-select" class="form-select text-xs w-full rounded-xl bg-slate-50 border border-slate-200 py-2 px-3" onchange="switchCamera(this.value)"></select>
        </div>
        
        <!-- Scanning Viewport Frame with pulsing target animation -->
        <div class="relative w-full rounded-xl overflow-hidden bg-black flex items-center justify-center" style="min-height: 250px;">
            <div id="qr-reader" class="w-full" style="min-height: 250px;"></div>
            <!-- Overlay Scanning target lines -->
            <div class="absolute inset-0 pointer-events-none flex items-center justify-center border-2 border-blue-500/10">
                <div class="w-48 h-48 border-2 border-dashed border-blue-400/40 rounded-xl animate-pulse"></div>
            </div>
        </div>
        
        <div class="w-full text-center text-xs text-slate-550 leading-relaxed">
            Align the invitation QR code within the target scanning zone.
        </div>
        
        <!-- Controls actions footer -->
        <div class="flex gap-2 w-full pt-2">
            <button type="button" id="scanner-action-btn" onclick="toggleScannerAction()" class="btn btn-primary flex-1 py-2.5 text-xs font-bold flex items-center justify-center gap-1.5" disabled>
                <i class="fa-solid fa-play"></i> Start Scan
            </button>
            <button type="button" onclick="stopScanner()" class="btn btn-secondary flex-1 py-2.5 text-xs font-bold">
                Cancel
            </button>
        </div>
    </div>
</div>

<script>
    // -----------------------------------------------------------------
    // QR SCANNER ENGINE: html5-qrcode
    // -----------------------------------------------------------------
    let html5QrCode = null;

    // Beep sound on successful scan
    function playBeep() {
        try {
            const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = audioCtx.createOscillator();
            const gainNode = audioCtx.createGain();
            oscillator.connect(gainNode);
            gainNode.connect(audioCtx.destination);
            oscillator.type = 'sine';
            oscillator.frequency.setValueAtTime(880, audioCtx.currentTime); // A5 note
            gainNode.gain.setValueAtTime(0.1, audioCtx.currentTime);
            oscillator.start();
            setTimeout(() => oscillator.stop(), 150);
        } catch (e) {
            console.warn("Could not play beep", e);
        }
    }

    // Update UI status badges
    function updateScannerStatus(state, message = '') {
        const badge = document.getElementById('scanner-status-badge');
        const text = document.getElementById('scanner-status-text');
        const spinner = document.getElementById('scanner-status-spinner');
        const actionBtn = document.getElementById('scanner-action-btn');
        
        if (badge) badge.className = "px-2.5 py-1 rounded-full text-[9px] font-bold flex items-center gap-1";
        if (spinner) spinner.classList.add('hidden');
        if (actionBtn) actionBtn.disabled = false;
        
        switch (state) {
            case 'loading':
                if (badge) badge.classList.add('bg-slate-100', 'text-slate-650');
                if (text) text.textContent = message || 'Loading...';
                if (spinner) spinner.classList.remove('hidden');
                if (actionBtn) actionBtn.disabled = true;
                break;
            case 'scanning':
                if (badge) badge.classList.add('bg-blue-50', 'text-blue-700', 'border', 'border-blue-200', 'animate-pulse');
                if (text) text.textContent = 'Scanning Live';
                if (actionBtn) actionBtn.innerHTML = '<i class="fa-solid fa-stop"></i> Stop Scan';
                break;
            case 'found':
                if (badge) badge.classList.add('bg-green-50', 'text-green-700', 'border', 'border-green-200');
                if (text) text.textContent = 'Guest Found';
                if (actionBtn) actionBtn.disabled = true;
                break;
            case 'error':
                if (badge) badge.classList.add('bg-red-50', 'text-red-700', 'border', 'border-red-200');
                if (text) text.textContent = message || 'Camera Error';
                if (actionBtn) actionBtn.innerHTML = '<i class="fa-solid fa-rotate"></i> Retry';
                break;
            default:
                if (badge) badge.classList.add('bg-slate-100', 'text-slate-650');
                if (text) text.textContent = 'Inactive';
                if (actionBtn) actionBtn.innerHTML = '<i class="fa-solid fa-play"></i> Start Scan';
        }
    }

    // Handle the Start/Stop toggle button in the UI
    function toggleScannerAction() {
        if (html5QrCode && html5QrCode.isScanning) {
            stopScanner();
        } else {
            startScanner();
        }
    }
    
    // Prevent errors if UI calls switchCamera
    function switchCamera(deviceId) {
        console.log('Manual camera switching is disabled in this engine mode.');
    }

    // Modal Lifecycle: OPEN
    function startScanner() {
        const modal = document.getElementById('scanner-modal');
        if (modal) modal.style.display = 'flex';
        
        // Prevent duplicate initialization
        if (html5QrCode) {
            console.warn("Scanner already initialized.");
            return;
        }

        updateScannerStatus('loading', 'Starting Camera...');
        
        // Clear DOM before start
        const qrReader = document.getElementById('qr-reader');
        if (qrReader) qrReader.innerHTML = '';

        html5QrCode = new Html5Qrcode("qr-reader");

        // Optimal configuration for mobile scanning
        const config = {
            fps: 10,
            qrbox: { width: 250, height: 250 },
            aspectRatio: 1.0
        };

        const onScanSuccess = (decodedText, decodedResult) => {
            // Immediate stop and clear on success
            playBeep();
            updateScannerStatus('found');
            
            if (html5QrCode) {
                html5QrCode.stop().then(() => {
                    html5QrCode.clear();
                    html5QrCode = null;
                    if (modal) modal.style.display = 'none';
                    
                    // Pass guest code to the form input and submit
                    const input = document.getElementById('scanner_input');
                    if (input) {
                        input.value = decodedText;
                        const form = input.closest('form');
                        if (form) {
                            form.submit();
                        }
                    }
                }).catch(err => {
                    console.error("Failed to stop scanner on success", err);
                });
            }
        };

        const onScanFailure = (error) => {
            // Ignore invalid frames silently
        };

        // Attempt Environment (Rear) camera first
        html5QrCode.start({ facingMode: "environment" }, config, onScanSuccess, onScanFailure)
            .then(() => {
                updateScannerStatus('scanning');
            })
            .catch((err) => {
                console.warn("Rear camera failed, falling back to user camera", err);
                // Fallback to User (Front) camera
                html5QrCode.start({ facingMode: "user" }, config, onScanSuccess, onScanFailure)
                    .then(() => {
                        updateScannerStatus('scanning');
                    })
                    .catch((errFallback) => {
                        console.error("Camera access failed", errFallback);
                        updateScannerStatus('error', 'Permission Denied or No Camera');
                    });
            });
    }

    // Modal Lifecycle: CLOSE
    function stopScanner() {
        updateScannerStatus('loading', 'Shutting Down...');
        
        const modal = document.getElementById('scanner-modal');
        if (html5QrCode) {
            html5QrCode.stop().then(() => {
                html5QrCode.clear();
                html5QrCode = null;
                if (modal) modal.style.display = 'none';
                updateScannerStatus('inactive');
            }).catch(err => {
                console.error("Failed to stop scanner", err);
                // Force UI close and cleanup if camera lock fails
                html5QrCode.clear();
                html5QrCode = null;
                if (modal) modal.style.display = 'none';
                updateScannerStatus('inactive');
            });
        } else {
            if (modal) modal.style.display = 'none';
            updateScannerStatus('inactive');
        }
    }

    // Helper: keep input focused for hardware physical scanners
    window.addEventListener('DOMContentLoaded', () => {
        const input = document.getElementById('scanner_input');
        if (input) {
            input.focus();
            document.body.addEventListener('click', (e) => {
                const modal = document.getElementById('scanner-modal');
                if (modal && modal.style.display === 'flex') return;
                
                const ignoreTags = ['BUTTON', 'A', 'INPUT', 'SELECT', 'TEXTAREA'];
                if (e.target !== input && !ignoreTags.includes(e.target.tagName)) {
                    input.focus();
                }
            });
        }
    });
</script>
