<?php
require_once 'includes/auth.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';

requireLogin();
if (!hasRole(['owner', 'manager', 'kiosk'])) {
    header("Location: " . url('login'));
    exit;
}

$company_id = $_SESSION['company_id'];
$company = fetch("SELECT name FROM companies WHERE id = ?", [$company_id]);
$company_name = $company ? $company['name'] : 'Apparel Management System';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Attendance Kiosk - <?php echo htmlspecialchars($company_name); ?></title>
    <!-- Favicon -->
    <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>👕</text></svg>">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;700&display=swap" rel="stylesheet">
    <!-- FontAwesome Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        :root {
            --bg-color: #0B0F19;
            --card-bg: rgba(20, 27, 45, 0.7);
            --border-color: rgba(255, 255, 255, 0.08);
            --text-color: #F3F4F6;
            --text-muted: #9CA3AF;
            --primary: #6366F1;
            --primary-glow: rgba(99, 102, 241, 0.15);
            --success: #10B981;
            --success-glow: rgba(16, 185, 129, 0.2);
            --danger: #EF4444;
            --danger-glow: rgba(239, 68, 68, 0.2);
            --glass-bg: rgba(255, 255, 255, 0.03);
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Outfit', sans-serif;
            background-color: var(--bg-color);
            color: var(--text-color);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            overflow-x: hidden;
            background-image: 
                radial-gradient(at 0% 0%, rgba(99, 102, 241, 0.05) 0px, transparent 50%),
                radial-gradient(at 100% 100%, rgba(16, 185, 129, 0.05) 0px, transparent 50%);
        }

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1.25rem 2rem;
            background: rgba(11, 15, 25, 0.8);
            backdrop-filter: blur(10px);
            border-bottom: 1px solid var(--border-color);
            z-index: 10;
        }

        .logo-container {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .logo-icon {
            font-size: 1.5rem;
            color: var(--primary);
            background: rgba(99, 102, 241, 0.1);
            padding: 0.5rem;
            border-radius: 10px;
            border: 1px solid rgba(99, 102, 241, 0.2);
        }

        .logo-text h1 {
            font-size: 1.25rem;
            font-weight: 700;
            letter-spacing: -0.5px;
        }

        .logo-text p {
            font-size: 0.75rem;
            color: var(--text-muted);
            text-transform: uppercase;
            letter-spacing: 1px;
            font-weight: 600;
        }

        .header-actions {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .btn-exit {
            background: rgba(239, 68, 68, 0.1);
            color: var(--danger);
            border: 1px solid rgba(239, 68, 68, 0.2);
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-family: inherit;
            font-weight: 600;
            font-size: 0.875rem;
            cursor: pointer;
            transition: all 0.2s ease;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn-exit:hover {
            background: var(--danger);
            color: white;
            box-shadow: 0 4px 12px var(--danger-glow);
        }

        main {
            flex: 1;
            display: grid;
            grid-template-columns: 1.1fr 0.9fr;
            gap: 2rem;
            padding: 1.5rem 2rem;
            max-width: 1200px;
            width: 100%;
            margin: 0 auto;
            align-items: center; /* Center cards vertically */
            min-height: calc(100vh - 80px); /* Fill screen height minus header */
            box-sizing: border-box;
        }

        @keyframes pulse {
            0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); }
            70% { transform: scale(1); box-shadow: 0 0 0 8px rgba(16, 185, 129, 0); }
            100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
        }


        .scanner-card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 20px;
            padding: 2rem;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            position: relative;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            backdrop-filter: blur(12px);
        }

        .camera-outer {
            width: 100%;
            max-width: 640px;
            aspect-ratio: 4/3;
            border-radius: 16px;
            overflow: hidden;
            background: #000;
            position: relative;
            border: 2px solid var(--border-color);
            box-shadow: 0 0 20px rgba(0,0,0,0.5);
        }

        #reader {
            width: 100%;
            height: 100%;
        }

        #reader video {
            transform: none !important;
        }

        /* Overlay scan guide lines */
        .scanner-overlay {
            position: absolute;
            inset: 0;
            pointer-events: none;
            z-index: 5;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .scan-target {
            width: 300px;
            height: 300px;
            border: 2px dashed rgba(255, 255, 255, 0.4);
            border-radius: 12px;
            position: relative;
            box-shadow: 0 0 0 4000px rgba(0, 0, 0, 0.4);
        }

        .scan-target::before, .scan-target::after {
            content: '';
            position: absolute;
            width: 20px;
            height: 20px;
            border-color: var(--primary);
            border-style: solid;
        }

        .scan-target::before {
            top: -2px;
            left: -2px;
            border-width: 4px 0 0 4px;
            border-top-left-radius: 8px;
        }

        .scan-target::after {
            bottom: -2px;
            right: -2px;
            border-width: 0 4px 4px 0;
            border-bottom-right-radius: 8px;
        }

        /* Scan Line Animation */
        .scan-laser {
            position: absolute;
            width: 100%;
            height: 3px;
            background: linear-gradient(to right, transparent, var(--primary), transparent);
            top: 0;
            animation: scanning 2s linear infinite;
        }

        @keyframes scanning {
            0% { top: 0%; }
            50% { top: 100%; }
            100% { top: 0%; }
        }

        .scanner-info {
            margin-top: 1.5rem;
            text-align: center;
        }

        .scanner-info h2 {
            font-size: 1.25rem;
            margin-bottom: 0.5rem;
            font-weight: 600;
        }

        .scanner-info p {
            font-size: 0.875rem;
            color: var(--text-muted);
        }

        .info-card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 20px;
            padding: 2rem;
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            backdrop-filter: blur(12px);
        }

        .kiosk-clock {
            text-align: center;
            padding: 1.5rem;
            background: var(--glass-bg);
            border-radius: 16px;
            border: 1px solid var(--border-color);
        }

        .digital-time {
            font-family: 'JetBrains Mono', monospace;
            font-size: 3.5rem;
            font-weight: 700;
            color: var(--primary);
            letter-spacing: -1px;
            line-height: 1;
        }

        .digital-date {
            font-size: 1rem;
            color: var(--text-muted);
            margin-top: 0.5rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            font-weight: 600;
        }

        .recent-scans-container {
            display: flex;
            flex-direction: column;
            flex: 1;
            min-height: 300px;
        }

        .recent-scans-header {
            font-size: 0.875rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: var(--text-muted);
            font-weight: 700;
            margin-bottom: 1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .recent-scans-list {
            display: flex;
            flex-direction: column;
            gap: 0.75rem;
            overflow-y: auto;
            flex: 1;
        }

        .scan-item {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 0.75rem 1rem;
            background: var(--glass-bg);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            transition: transform 0.2s ease;
        }

        .scan-item:hover {
            transform: translateX(4px);
        }

        .scan-item-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.05);
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid var(--border-color);
            font-size: 1rem;
            color: var(--text-muted);
            overflow: hidden;
        }

        .scan-item-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .scan-item-info {
            flex: 1;
        }

        .scan-item-name {
            font-weight: 600;
            font-size: 0.95rem;
        }

        .scan-item-code {
            font-size: 0.75rem;
            color: var(--text-muted);
            font-family: 'JetBrains Mono', monospace;
        }

        .scan-item-meta {
            text-align: right;
        }

        .scan-item-time {
            font-weight: 700;
            font-size: 0.9rem;
            font-family: 'JetBrains Mono', monospace;
        }

        .badge-scan {
            display: inline-block;
            font-size: 0.7rem;
            padding: 0.15rem 0.4rem;
            border-radius: 4px;
            font-weight: 700;
            text-transform: uppercase;
            margin-top: 0.25rem;
        }

        .badge-in {
            background: rgba(16, 185, 129, 0.1);
            color: var(--success);
        }

        .badge-out {
            background: rgba(239, 68, 68, 0.1);
            color: var(--danger);
        }

        /* Visual Feedback Modal Overlay */
        .feedback-overlay {
            position: fixed;
            inset: 0;
            background: rgba(11, 15, 25, 0.95);
            z-index: 100;
            display: none;
            align-items: center;
            justify-content: center;
            padding: 2rem;
            backdrop-filter: blur(8px);
        }

        .feedback-card {
            width: 100%;
            max-width: 500px;
            background: var(--card-bg);
            border: 2px solid var(--border-color);
            border-radius: 28px;
            padding: 3rem 2rem;
            text-align: center;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 1.5rem;
            animation: popIn 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
        }

        @keyframes popIn {
            0% { transform: scale(0.8); opacity: 0; }
            100% { transform: scale(1); opacity: 1; }
        }

        .feedback-icon {
            width: 90px;
            height: 90px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2.75rem;
            box-shadow: 0 10px 25px rgba(0,0,0,0.2);
        }

        .feedback-success .feedback-icon {
            background: linear-gradient(135deg, #10B981, #059669);
            color: white;
            box-shadow: 0 10px 25px rgba(16, 185, 129, 0.3);
        }

        .feedback-error .feedback-icon {
            background: linear-gradient(135deg, #EF4444, #DC2626);
            color: white;
            box-shadow: 0 10px 25px rgba(239, 68, 68, 0.3);
        }

        .feedback-status-title {
            font-size: 1.75rem;
            font-weight: 800;
            letter-spacing: -0.5px;
        }

        .feedback-success .feedback-status-title {
            color: var(--success);
        }

        .feedback-error .feedback-status-title {
            color: var(--danger);
        }

        .feedback-photo-container {
            width: 140px;
            height: 140px;
            border-radius: 16px;
            overflow: hidden;
            border: 3px solid var(--border-color);
            background: #000;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }

        .feedback-photo-container img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .feedback-details {
            background: rgba(255, 255, 255, 0.02);
            border: 1px solid var(--border-color);
            border-radius: 16px;
            padding: 1.25rem 2rem;
            width: 100%;
        }

        .feedback-emp-name {
            font-size: 1.35rem;
            font-weight: 700;
            margin-bottom: 0.25rem;
        }

        .feedback-emp-code {
            font-family: 'JetBrains Mono', monospace;
            color: var(--text-muted);
            font-size: 0.9rem;
            letter-spacing: 0.5px;
        }

        .feedback-time-badge {
            margin-top: 0.75rem;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            background: rgba(99, 102, 241, 0.1);
            border: 1px solid rgba(99, 102, 241, 0.2);
            color: var(--primary);
            padding: 0.35rem 1rem;
            border-radius: 20px;
            font-size: 0.9rem;
            font-weight: 700;
            font-family: 'JetBrains Mono', monospace;
        }

        .feedback-success .feedback-time-badge {
            background: rgba(16, 185, 129, 0.1);
            border: 1px solid rgba(16, 185, 129, 0.2);
            color: var(--success);
        }

        .feedback-countdown {
            font-size: 0.8rem;
            color: var(--text-muted);
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .countdown-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: var(--primary);
            animation: pulse 1s infinite alternate;
        }

        @keyframes pulse {
            0% { transform: scale(0.8); opacity: 0.5; }
            100% { transform: scale(1.2); opacity: 1; }
        }

        #camera-error {
            display: none;
            background: rgba(239, 68, 68, 0.1);
            border: 1px solid rgba(239, 68, 68, 0.2);
            color: var(--danger);
            border-radius: 12px;
            padding: 1rem;
            margin-top: 1rem;
            width: 100%;
            max-width: 640px;
            text-align: center;
            font-size: 0.9rem;
            line-height: 1.4;
        }

        /* Mobile Responsive Styles */
        @media (max-width: 992px) {
            main {
                grid-template-columns: 1fr;
                gap: 1.5rem;
                padding: 1rem;
                min-height: auto;
                align-items: stretch;
            }
            .info-card {
                min-height: auto !important;
                padding: 1.5rem !important;
                order: -1; /* Display clock above scanner on mobile */
            }
            .kiosk-clock {
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 0.25rem;
            }
            .kiosk-clock i {
                font-size: 2rem !important;
                margin-bottom: 0.5rem !important;
            }
            .digital-time {
                font-size: 3rem !important;
            }
            .digital-date {
                font-size: 1rem !important;
                margin-top: 0.25rem !important;
            }
            .info-card div[style*="margin-top: 3rem"] {
                margin-top: 1.5rem !important;
            }
            .scanner-card {
                padding: 1.5rem 1rem;
            }
            .camera-outer {
                max-width: 100%;
            }
            .scan-target {
                width: 240px;
                height: 240px;
            }
            header {
                padding: 1rem;
            }
            .logo-text h1 {
                font-size: 1.1rem;
            }
            .logo-text p {
                font-size: 0.7rem;
            }
            .btn-exit {
                padding: 0.4rem 0.8rem;
                font-size: 0.8rem;
            }
        }

        @media (max-width: 480px) {
            .feedback-card {
                padding: 1.5rem 1rem !important;
                gap: 1rem !important;
                border-radius: 20px !important;
            }
            .feedback-icon {
                width: 70px !important;
                height: 70px !important;
                font-size: 2rem !important;
            }
            .feedback-photo-container {
                width: 100px !important;
                height: 100px !important;
            }
            .feedback-emp-name {
                font-size: 1.1rem !important;
            }
            .scan-target {
                width: 180px;
                height: 180px;
            }
            #feedbackPhotosWrapper {
                flex-direction: row;
                gap: 0.75rem !important;
            }
        }
    </style>
</head>
<body>

    <header>
        <div class="logo-container">
            <i class="fas fa-qrcode logo-icon"></i>
            <div class="logo-text">
                <h1>Attendance Kiosk</h1>
                <p><?php echo htmlspecialchars($company_name); ?></p>
            </div>
        </div>
        <div class="header-actions">
            <?php if (hasRole('kiosk')): ?>
                <a href="<?php echo url('logout'); ?>" class="btn-exit" style="background: rgba(239, 68, 68, 0.15); color: #ef4444; border: 1px solid rgba(239, 68, 68, 0.3);">
                    <i class="fas fa-sign-out-alt"></i> Log Out
                </a>
            <?php else: ?>
                <a href="<?php echo url('attendance'); ?>" class="btn-exit">
                    <i class="fas fa-arrow-left"></i> Exit Kiosk
                </a>
            <?php endif; ?>
        </div>
    </header>

    <main>
        <!-- Left: Scanner -->
        <div class="scanner-card">
            <div class="camera-outer">
                <div id="reader"></div>
                <div class="scanner-overlay">
                    <div class="scan-target">
                        <div class="scan-laser"></div>
                    </div>
                </div>
            </div>
            
            <div id="camera-error">
                <i class="fas fa-exclamation-triangle" style="font-size: 1.5rem; margin-bottom: 0.5rem;"></i>
                <p><strong>Camera Access Error</strong><br>Could not access the camera stream. Please ensure camera permissions are enabled and no other app is using it.</p>
            </div>

            <!-- Camera Selector Dropdown -->
            <div style="margin: 1rem 0 0.5rem 0; width: 100%; max-width: 640px; text-align: left;">
                <label for="cameraSelect" style="font-size: 0.75rem; text-transform: uppercase; color: var(--text-muted); font-weight: 700; letter-spacing: 0.5px; display: block; margin-bottom: 0.35rem;">
                    <i class="fas fa-video" style="margin-right: 0.35rem; color: var(--primary);"></i> Active Camera
                </label>
                <select id="cameraSelect" style="width: 100%; background: rgba(11, 15, 25, 0.6); border: 1px solid var(--border-color); color: var(--text-color); border-radius: 10px; padding: 0.6rem; font-family: inherit; font-size: 0.9rem; cursor: pointer; outline: none; transition: border-color 0.2s;">
                    <option value="">Selecting camera...</option>
                </select>
            </div>

            <div class="scanner-info">
                <h2>Scan Employee QR Code</h2>
                <p>Position the card's QR code in the target frame to log check-in/out.</p>
            </div>
        </div>

        <!-- Right: Time & Status -->
        <div class="info-card" style="display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 480px; text-align: center;">
            <div class="kiosk-clock" style="border: none; background: transparent; padding: 0; width: 100%;">
                <div style="font-size: 3.5rem; color: var(--primary); margin-bottom: 1.5rem; opacity: 0.85;">
                    <i class="fas fa-clock"></i>
                </div>
                <div id="kioskTime" class="digital-time" style="font-size: 4rem; font-weight: 800;">00:00:00</div>
                <div id="kioskDate" class="digital-date" style="font-size: 1.25rem; margin-top: 1rem; color: var(--text-muted); font-weight: 500; text-transform: none; letter-spacing: 0.5px;">Wednesday, May 20, 2026</div>
            </div>
            
            <div style="margin-top: 3rem; display: flex; align-items: center; gap: 0.75rem; background: rgba(16, 185, 129, 0.08); border: 1px solid rgba(16, 185, 129, 0.2); padding: 0.75rem 1.5rem; border-radius: 50px;">
                <span class="status-indicator" style="width: 10px; height: 10px; background: var(--success); border-radius: 50%; display: inline-block; animation: pulse 2s infinite;"></span>
                <span style="font-size: 0.875rem; font-weight: 600; color: var(--success); text-transform: uppercase; letter-spacing: 1px;">Kiosk Active</span>
            </div>
        </div>
    </main>

    <!-- Overlay Feedback Modal -->
    <div id="feedbackOverlay" class="feedback-overlay">
        <div id="feedbackCard" class="feedback-card">
            <div class="feedback-icon">
                <i id="feedbackIconSymbol" class="fas fa-check"></i>
            </div>
            
            <h3 id="feedbackTitle" class="feedback-status-title">Scan Logged</h3>
            
            <!-- Dynamic Side-by-Side Photos (Profile vs Captured) -->
            <div id="feedbackPhotosWrapper" style="display: flex; gap: 1.25rem; justify-content: center; margin: 1rem 0; width: 100%;">
                <div style="text-align: center;">
                    <div style="font-size: 0.7rem; text-transform: uppercase; color: var(--text-muted); font-weight: 700; margin-bottom: 0.35rem; letter-spacing: 0.5px;">Profile Registry</div>
                    <div class="feedback-photo-container" style="border-color: rgba(99, 102, 241, 0.4);">
                        <img id="feedbackPhotoProfile" src="assets/img/avatar-placeholder.png" alt="Profile">
                    </div>
                </div>
                <div style="text-align: center;">
                    <div style="font-size: 0.7rem; text-transform: uppercase; color: var(--text-muted); font-weight: 700; margin-bottom: 0.35rem; letter-spacing: 0.5px;">Kiosk Capture</div>
                    <div class="feedback-photo-container" style="border-color: rgba(16, 185, 129, 0.4);">
                        <img id="feedbackPhotoCaptured" src="" alt="Snapshot">
                    </div>
                </div>
            </div>

            <div class="feedback-details">
                <div id="feedbackEmpName" class="feedback-emp-name">Employee Name</div>
                <div id="feedbackEmpCode" class="feedback-emp-code">EMP-00000</div>
                
                <div>
                    <span id="feedbackTimeBadge" class="feedback-time-badge">
                        <i class="fas fa-clock" style="margin-right: 0.35rem;"></i>
                        <span id="feedbackTimeText">00:00 AM</span>
                    </span>
                </div>
            </div>

            <div class="feedback-countdown">
                <div class="countdown-dot"></div>
                Resuming scan in <span id="countdownSecs">3</span>s...
            </div>
        </div>
    </div>

    <!-- Scanner library -->
    <script src="assets/js/html5-qrcode.min.js"></script>

    <script>
        // Synth Audio Controller for offline feedback
        const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
        
        function playChime(success = true) {
            try {
                if (audioCtx.state === 'suspended') {
                    audioCtx.resume();
                }
                const osc = audioCtx.createOscillator();
                const gain = audioCtx.createGain();
                osc.connect(gain);
                gain.connect(audioCtx.destination);

                if (success) {
                    // Quick rising double-beep (happy chime)
                    osc.frequency.setValueAtTime(523.25, audioCtx.currentTime); // C5
                    gain.gain.setValueAtTime(0.1, audioCtx.currentTime);
                    osc.start();
                    
                    setTimeout(() => {
                        osc.frequency.setValueAtTime(880.00, audioCtx.currentTime); // A5
                    }, 80);
                    
                    setTimeout(() => {
                        gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 0.1);
                        osc.stop(audioCtx.currentTime + 0.15);
                    }, 200);
                } else {
                    // Low warning buzzer
                    osc.type = 'sawtooth';
                    osc.frequency.setValueAtTime(150, audioCtx.currentTime);
                    gain.gain.setValueAtTime(0.15, audioCtx.currentTime);
                    osc.start();
                    
                    gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 0.35);
                    osc.stop(audioCtx.currentTime + 0.4);
                }
            } catch (err) {
                console.error("Audio playback error:", err);
            }
        }

        // Live Clock
        function updateClock() {
            const timeEl = document.getElementById("kioskTime");
            const dateEl = document.getElementById("kioskDate");
            if (!timeEl || !dateEl) return;

            const now = new Date();
            let h = now.getHours();
            let m = now.getMinutes();
            let s = now.getSeconds();
            const ampm = h >= 12 ? 'PM' : 'AM';

            h = h % 12;
            h = h ? h : 12;
            m = m < 10 ? '0' + m : m;
            s = s < 10 ? '0' + s : s;

            timeEl.textContent = `${h}:${m}:${s} ${ampm}`;

            const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
            dateEl.textContent = now.toLocaleDateString('en-US', options);
        }
        setInterval(updateClock, 1000);
        updateClock();

        // Local Storage Session Scan Logs helper
        function addScanToSession(log) {
            // No-op - recent scans log list was removed from Kiosk dashboard
        }

        function escapeHtml(str) {
            if (!str) return '';
            return str.toString()
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // Camera Frame Capture helper
        function capturePhoto() {
            try {
                const videoEl = document.querySelector("#reader video");
                if (!videoEl) {
                    console.error("Video element not found for capture");
                    return null;
                }

                const canvas = document.createElement("canvas");
                // Match resolution of the actual camera frame
                canvas.width = videoEl.videoWidth || 640;
                canvas.height = videoEl.videoHeight || 480;
                
                const ctx = canvas.getContext("2d");
                ctx.drawImage(videoEl, 0, 0, canvas.width, canvas.height);
                
                // Return base64 JPEG format with 0.85 compression
                return canvas.toDataURL("image/jpeg", 0.85);
            } catch (err) {
                console.error("Error capturing canvas photo:", err);
                return null;
            }
        }

        // Camera QR Code Scanner logic
        let html5Qrcode = null;
        let isScanning = false;
        const scannerConfig = {
            fps: 20, // Scan up to 20 frames per second for ultra-responsive capture
            qrbox: { width: 220, height: 220 }, // Match the 200x200 dashed UI frame to optimize CPU decoding
            experimentalFeatures: {
                useBarCodeDetectorIfSupported: true // Leverage native hardware acceleration in Chrome
            },
            videoConstraints: {
                width: { ideal: 1280 },
                height: { ideal: 720 }
            }
        };

        async function initScanner() {
            try {
                html5Qrcode = new Html5Qrcode("reader");
                
                // Query video devices
                const devices = await Html5Qrcode.getCameras();
                const select = document.getElementById("cameraSelect");
                
                if (devices && devices.length > 0) {
                    select.innerHTML = devices.map((d, index) => 
                        `<option value="${d.id}">${d.label || 'Camera ' + (index + 1)}</option>`
                    ).join('');
                    
                    // Add listener to switch camera on dropdown change
                    select.addEventListener('change', async (e) => {
                        const deviceId = e.target.value;
                        if (html5Qrcode && isScanning) {
                            try {
                                await html5Qrcode.stop();
                            } catch (stopErr) {}
                            isScanning = false;
                        }
                        await startScanner(deviceId);
                    });

                    // Search for a front-facing / user camera
                    let defaultDevice = devices[0].id;
                    const front = devices.find(d => {
                        const label = (d.label || '').toLowerCase();
                        return label.includes('front') || label.includes('user') || label.includes('face');
                    });
                    if (front) {
                        defaultDevice = front.id;
                    }
                    
                    select.value = defaultDevice;
                    await startScanner(defaultDevice);
                } else {
                    // No devices listed, fall back to standard facingMode constraints
                    select.parentElement.style.display = 'none';
                    await startScanner({ facingMode: "user" });
                }
            } catch (err) {
                console.warn("Listing cameras failed, using constraints fallback:", err);
                const select = document.getElementById("cameraSelect");
                if (select) select.parentElement.style.display = 'none';
                await startScanner({ facingMode: "user" });
            }
        }

        async function startScanner(cameraSource) {
            try {
                document.getElementById("camera-error").style.display = "none";
                
                await html5Qrcode.start(
                    cameraSource,
                    scannerConfig,
                    onQrCodeScanned,
                    onQrCodeScanError
                );
                isScanning = true;
            } catch (err) {
                console.warn("Failed starting camera source with HD constraints, trying default:", cameraSource, err);
                try {
                    // Fallback to standard start without HD constraints
                    const fallbackConfig = {
                        fps: 20,
                        qrbox: { width: 220, height: 220 },
                        experimentalFeatures: {
                            useBarCodeDetectorIfSupported: true
                        }
                    };
                    await html5Qrcode.start(
                        cameraSource,
                        fallbackConfig,
                        onQrCodeScanned,
                        onQrCodeScanError
                    );
                    isScanning = true;
                } catch (fallbackErr) {
                    console.error("Fallback start failed:", fallbackErr);
                    
                    // Fall back to environment camera if "user" failed
                    if (cameraSource && (cameraSource.facingMode === "user" || typeof cameraSource === 'string')) {
                        try {
                            await html5Qrcode.start(
                                { facingMode: "environment" },
                                scannerConfig,
                                onQrCodeScanned,
                                onQrCodeScanError
                            );
                            isScanning = true;
                            return;
                        } catch (envErr) {
                            console.error("Environment fallback failed:", envErr);
                        }
                    }
                    document.getElementById("camera-error").style.display = "block";
                    isScanning = false;
                }
            }
        }

        function onQrCodeScanError(err) {
            // Quiet fail during scanning loops to avoid console clutter
        }

        async function onQrCodeScanned(decodedText, decodedResult) {
            if (!isScanning) return;
            isScanning = false;

            // Immediately grab the camera image frame
            const snapshotBase64 = capturePhoto();
            playChime(true); // Audible beep to alert the worker

            // Post scan payload to backend API
            try {
                const response = await fetch("api/attendance.php", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "X-User-Timezone": Intl.DateTimeFormat().resolvedOptions().timeZone
                    },
                    body: JSON.stringify({
                        action: "kiosk_scan",
                        employee_code: decodedText.trim(),
                        photo: snapshotBase64
                    })
                });

                const result = await response.json();
                
                if (result.success) {
                    showFeedback(true, result);
                    addScanToSession({
                        name: result.employee_name,
                        code: decodedText.trim(),
                        time: result.time_formatted,
                        type: result.type,
                        photo: snapshotBase64
                    });
                } else {
                    playChime(false); // Play negative tone
                    showFeedback(false, { message: result.message });
                }
            } catch (err) {
                console.error("Scan dispatch error:", err);
                playChime(false);
                showFeedback(false, { message: "Network connection error" });
            }
        }

        // UI Feedback modal controllers
        let feedbackTimer = null;

        function showFeedback(success, data) {
            const overlay = document.getElementById("feedbackOverlay");
            const card = document.getElementById("feedbackCard");
            const iconSymbol = document.getElementById("feedbackIconSymbol");
            const title = document.getElementById("feedbackTitle");
            const empName = document.getElementById("feedbackEmpName");
            const empCode = document.getElementById("feedbackEmpCode");
            const timeText = document.getElementById("feedbackTimeText");
            const countdownEl = document.getElementById("countdownSecs");

            // Reset classes
            card.className = "feedback-card " + (success ? "feedback-success" : "feedback-error");

            if (success) {
                iconSymbol.className = "fas fa-check";
                title.textContent = data.type === 'clock_in' ? 'Clocked In Successfully!' : 'Clocked Out Successfully!';
                
                const profileImg = document.getElementById("feedbackPhotoProfile");
                const capturedImg = document.getElementById("feedbackPhotoCaptured");
                
                profileImg.src = data.profile_picture ? data.profile_picture : 'assets/img/avatar-placeholder.png';
                capturedImg.src = data.photo_url || data.photo_data || '';
                
                document.getElementById("feedbackPhotosWrapper").style.display = 'flex';
                empName.textContent = data.employee_name;
                
                // Show both employee code and their designative role
                empCode.innerHTML = `${escapeHtml(data.employee_code)} &bull; <span style="color: var(--primary); font-weight: 700;">${escapeHtml(data.role_name)}</span>`;
                
                timeText.textContent = data.time_formatted;
                document.getElementById("feedbackTimeBadge").style.display = 'inline-flex';
            } else {
                iconSymbol.className = "fas fa-times";
                title.textContent = "Scan Rejected";
                
                document.getElementById("feedbackPhotosWrapper").style.display = 'none';
                empName.textContent = data.message;
                empCode.textContent = "Please try scanning again";
                document.getElementById("feedbackTimeBadge").style.display = 'none';
            }

            overlay.style.display = "flex";

            // Start 3 second countdown timer
            let remaining = 3;
            countdownEl.textContent = remaining;
            
            if (feedbackTimer) clearInterval(feedbackTimer);
            
            feedbackTimer = setInterval(() => {
                remaining--;
                countdownEl.textContent = remaining;
                if (remaining <= 0) {
                    clearInterval(feedbackTimer);
                    closeFeedback();
                }
            }, 1000);
        }

        function closeFeedback() {
            const overlay = document.getElementById("feedbackOverlay");
            overlay.style.display = "none";
            isScanning = true;
        }

        // Initialize Kiosk
        document.addEventListener("DOMContentLoaded", () => {
            initScanner();
        });
    </script>
</body>
</html>
