<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Eduflow QR Attendance</title>
    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;800&display=swap" rel="stylesheet">
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
    <!-- html5-qrcode -->
    <script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
    <style>
        :root {
            --bg-grad-1: #0f172a;
            --bg-grad-2: #240b3b;
            --bg-grad-3: #111827;
            --glass-bg: rgba(255, 255, 255, 0.04);
            --glass-border: rgba(255, 255, 255, 0.08);
            --accent: #8b5cf6;
            --accent-glow: rgba(139, 92, 246, 0.5);
            --text-primary: #f8fafc;
            --text-secondary: #94a3b8;
            --error: #ef4444;
            --success: #10b981;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Outfit', sans-serif; }
        body {
            background: linear-gradient(135deg, var(--bg-grad-1), var(--bg-grad-2), var(--bg-grad-3));
            background-size: 400% 400%;
            animation: gradientBG 15s ease infinite;
            color: var(--text-primary);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        @keyframes gradientBG { 0% {background-position: 0% 50%;} 50% {background-position: 100% 50%;} 100% {background-position: 0% 50%;} }
        
        .glass-card {
            background: var(--glass-bg);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border: 1px solid var(--glass-border);
            border-radius: 28px;
            padding: 40px;
            width: 100%;
            max-width: 480px;
            box-shadow: 0 30px 60px -15px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255,255,255,0.1);
            transition: transform 0.3s ease;
        }
        
        .header { text-align: center; margin-bottom: 35px; }
        .header h1 { 
            font-weight: 800; font-size: 2.4rem; 
            background: linear-gradient(to right, #a78bfa, #ec4899); 
            -webkit-background-clip: text; 
            -webkit-text-fill-color: transparent; 
            margin-bottom: 8px; letter-spacing: -1px;
        }
        .header p { color: var(--text-secondary); font-weight: 300; font-size: 1.05rem; }
        
        /* Forms */
        .form-group { margin-bottom: 24px; position: relative; }
        .form-control {
            width: 100%; padding: 18px; border-radius: 14px;
            background: rgba(0,0,0,0.25); border: 1px solid var(--glass-border);
            color: white; font-size: 1.05rem; transition: all 0.3s ease; box-shadow: inset 0 2px 4px rgba(0,0,0,0.1);
        }
        .form-control::placeholder { color: rgba(255,255,255,0.3); }
        .form-control:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 20px rgba(139, 92, 246, 0.25), inset 0 2px 4px rgba(0,0,0,0.1); background: rgba(0,0,0,0.4); }
        
        .btn {
            width: 100%; padding: 18px; border-radius: 14px; border: none;
            background: linear-gradient(to right, var(--accent), #d946ef);
            color: white; font-size: 1.15rem; font-weight: 600; cursor: pointer;
            transition: all 0.3s ease; box-shadow: 0 10px 25px rgba(139, 92, 246, 0.4);
            text-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        .btn:hover { transform: translateY(-3px); box-shadow: 0 15px 35px rgba(139, 92, 246, 0.6); }
        .btn:active { transform: translateY(1px); }
        .btn:disabled { opacity: 0.7; cursor: not-allowed; transform: none; box-shadow: none; }
        
        .btn-danger { background: linear-gradient(to right, #ef4444, #f43f5e); box-shadow: 0 10px 25px rgba(239, 68, 68, 0.3); }
        .btn-danger:hover { box-shadow: 0 15px 35px rgba(239, 68, 68, 0.5); }
        
        /* Views visibility */
        #login-view, #scanner-view { display: none; opacity: 0; animation: fadeIn 0.6s forwards cubic-bezier(0.16, 1, 0.3, 1); }
        .active-view { display: block !important; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
        
        /* Scanner specifics */
        #reader { 
            border-radius: 18px; overflow: hidden; border: 2px solid rgba(139, 92, 246, 0.3); 
            margin-bottom: 25px; background: rgba(0,0,0,0.5); box-shadow: 0 10px 30px rgba(0,0,0,0.5);
        }
        .reader-controls { display: flex; gap: 15px; margin-top: 15px; }
        .reader-controls .btn { padding: 14px; font-size: 1.05rem; }
        
        /* Notifications */
        .alert { padding: 16px 20px; border-radius: 12px; margin-bottom: 25px; font-size: 0.95rem; display: none; font-weight: 400; animation: alertFade 0.4s ease; backdrop-filter: blur(10px); }
        @keyframes alertFade { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }
        .alert.error { background: rgba(127, 29, 29, 0.5); border: 1px solid rgba(239, 68, 68, 0.4); color: #fca5a5; box-shadow: 0 4px 15px rgba(239, 68, 68, 0.2); }
        .alert.success { background: rgba(6, 78, 59, 0.5); border: 1px solid rgba(16, 185, 129, 0.4); color: #6ee7b7; box-shadow: 0 4px 15px rgba(16, 185, 129, 0.2); }

        /* Report styling */
        .report-section { margin-top: 35px; position: relative; }
        .report-section::before {
            content: ''; position: absolute; top: -20px; left: 0; right: 0; height: 1px;
            background: linear-gradient(to right, transparent, var(--glass-border), transparent);
        }
        .report-list { list-style: none; max-height: 220px; overflow-y: auto; padding-right: 5px; margin-top: 15px; }
        /* Custom scrollbar */
        .report-list::-webkit-scrollbar { width: 6px; }
        .report-list::-webkit-scrollbar-track { background: rgba(0,0,0,0.1); border-radius: 10px; }
        .report-list::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.2); border-radius: 10px; }
        
        .report-item { 
            background: rgba(0,0,0,0.3); padding: 16px; border-radius: 12px; margin-bottom: 12px; 
            display: flex; justify-content: space-between; align-items: center; font-size: 0.9rem;
            border: 1px solid transparent; transition: all 0.2s ease;
        }
        .report-item:hover { background: rgba(0,0,0,0.4); border-color: rgba(255,255,255,0.05); transform: translateX(2px); }
        
        /* Utilities */
        .pill { padding: 4px 10px; border-radius: 20px; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
        .pill-success { background: rgba(16, 185, 129, 0.2); color: #6ee7b7; }
        .pill-error { background: rgba(239, 68, 68, 0.2); color: #fca5a5; }
    </style>
</head>
<body>

    <div class="glass-card">
        <div class="header">
            <h1>Eduflow Scanner</h1>
            <p id="subtitle">Smart & Secure QR Attendance</p>
        </div>

        <div id="alert-box" class="alert"></div>

        <!-- Login View -->
        <div id="login-view" class="active-view">
            <form id="login-form">
                <div class="form-group">
                    <input type="text" id="username" class="form-control" placeholder="Username (eduflow)" required>
                </div>
                <div class="form-group">
                    <input type="password" id="password" class="form-control" placeholder="Password (ssam2023)" required>
                </div>
                <button type="submit" class="btn" id="login-btn">Secure Login</button>
            </form>
        </div>

        <!-- Scanner View -->
        <div id="scanner-view">
            <div style="text-align: center; margin-bottom: 25px; font-size: 1.1rem; color: var(--text-secondary);">
                Welcome back, <span id="user-display-name" style="font-weight: 800; color: #fff;">User</span>
                <span style="display:block; font-size: 0.85rem; margin-top: 4px; color: var(--accent);">Ready to scan</span>
            </div>
            
            <div id="reader"></div>
            
            <div class="reader-controls">
                <button type="button" class="btn" id="start-scan-btn">Start Camera</button>
                <button type="button" class="btn btn-danger" id="logout-btn">Log Out</button>
            </div>
            
            <div class="report-section">
                <h3 style="font-size: 1.15rem; color: #fff; display: flex; align-items: center; justify-content: space-between;">
                    Recent Scans <button id="refresh-btn" style="background:none; border:none; color:var(--accent); cursor:pointer; font-size: 0.9rem; font-weight:600;">↻ Refresh</button>
                </h3>
                <ul class="report-list" id="report-list">
                    <!-- Dynamic -->
                </ul>
            </div>
        </div>
    </div>

    <script>
        const baseUrl = '<?php echo e(url('/')); ?>';
        const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
        
        const loginView = document.getElementById('login-view');
        const scannerView = document.getElementById('scanner-view');
        const alertBox = document.getElementById('alert-box');
        const loginForm = document.getElementById('login-form');
        let html5QrcodeScanner = null;
        let isScanning = false;

        async function apiCall(endpoint, method = 'GET', body = null) {
            const options = {
                method,
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                }
            };
            if (body) options.body = JSON.stringify(body);
            try {
                const response = await fetch(`${baseUrl}${endpoint}`, options);
                const data = await response.json();
                return { status: response.status, data };
            } catch (e) {
                return { status: 500, data: { message: 'Network error occurred.' } };
            }
        }

        function showAlert(msg, isError = false) {
            alertBox.textContent = msg;
            alertBox.className = 'alert ' + (isError ? 'error' : 'success');
            alertBox.style.display = 'block';
            setTimeout(() => { alertBox.style.display = 'none'; }, 4000);
        }

        async function checkSession() {
            const { status, data } = await apiCall('/api/me');
            if (status === 200 && data.user) {
                showScanner(data.user);
            }
        }

        function showScanner(user) {
            document.getElementById('user-display-name').textContent = user.name;
            loginView.classList.remove('active-view');
            scannerView.classList.add('active-view');
            loadReports();
        }

        function showLogin() {
            scannerView.classList.remove('active-view');
            loginView.classList.add('active-view');
            if (html5QrcodeScanner && isScanning) {
                html5QrcodeScanner.stop().then(() => {
                    html5QrcodeScanner.clear();
                });
                isScanning = false;
                document.getElementById('start-scan-btn').textContent = 'Start Camera';
            }
        }

        loginForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const btn = document.getElementById('login-btn');
            btn.textContent = 'Authenticating...';
            btn.disabled = true;

            const res = await apiCall('/api/login', 'POST', {
                username: document.getElementById('username').value,
                password: document.getElementById('password').value
            });

            if (res.status === 200) {
                showAlert('Login successful!');
                showScanner(res.data.user);
            } else {
                showAlert(res.data.message || 'Login failed', true);
            }
            
            btn.textContent = 'Secure Login';
            btn.disabled = false;
        });

        document.getElementById('logout-btn').addEventListener('click', async () => {
            await apiCall('/api/logout', 'POST');
            showLogin();
            document.getElementById('username').value = '';
            document.getElementById('password').value = '';
        });

        document.getElementById('refresh-btn').addEventListener('click', loadReports);

        async function onScanSuccess(decodedText, decodedResult) {
            if (!isScanning) return;
            isScanning = false;
            html5QrcodeScanner.pause();
            
            showAlert('QR Scanned! Submitting...', false);

            const payloadData = {
                qr_payload: decodedText,
                device_id: navigator.userAgent,
                latitude: null,
                longitude: null
            };

            const {status, data} = await apiCall('/api/scan-attendance', 'POST', payloadData);
            
            if (status === 200 || status === 201) {
                showAlert('Attendance recorded successfully!');
                loadReports();
            } else {
                showAlert(data.message || 'Validation Failed: Payload Error', true);
            }

            setTimeout(() => {
                isScanning = true;
                html5QrcodeScanner.resume();
            }, 3500);
        }

        function onScanFailure(error) {
            // keep scanning silently
        }

        document.getElementById('start-scan-btn').addEventListener('click', (e) => {
            if (!html5QrcodeScanner) {
                html5QrcodeScanner = new Html5Qrcode("reader");
            }
            
            const btn = e.target;
            if (isScanning) {
                html5QrcodeScanner.stop().then(() => {
                    isScanning = false;
                    btn.textContent = 'Start Camera';
                    btn.style.background = 'linear-gradient(to right, var(--accent), #d946ef)';
                });
            } else {
                html5QrcodeScanner.start(
                    { facingMode: "environment" },
                    { fps: 10, qrbox: { width: 260, height: 260 } },
                    onScanSuccess,
                    onScanFailure
                ).then(() => {
                    isScanning = true;
                    btn.textContent = 'Stop Camera';
                    btn.style.background = 'linear-gradient(to right, #f59e0b, #ea580c)';
                }).catch(err => {
                    showAlert('Camera access denied or unavailable.', true);
                });
            }
        });

        async function loadReports() {
            const {status, data} = await apiCall('/api/attendance-report');
            const list = document.getElementById('report-list');
            list.innerHTML = '';
            
            if (status === 200 && data.data) {
                if (data.data.length === 0) list.innerHTML = '<li class="report-item" style="justify-content:center; color: var(--text-secondary);">No scans yet today</li>';
                data.data.forEach(record => {
                    const li = document.createElement('li');
                    li.className = 'report-item';
                    const time = new Date(record.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
                    const statusPill = record.is_flagged 
                        ? '<span class="pill pill-error">Flagged</span>' 
                        : '<span class="pill pill-success">Valid</span>';
                    
                    const codeLabel = record.qr_payload ? `...${record.qr_payload.substring(record.qr_payload.length - 6)}` : `Loc: ${record.location_id}`;
                    
                    li.innerHTML = `
                        <div style="display:flex; flex-direction:column; gap:4px;">
                            <span style="font-weight:600; color:#fff;">${codeLabel}</span>
                            <span style="color:var(--text-secondary); font-size:0.8rem;">${time}</span>
                        </div>
                        <div>${statusPill}</div>
                    `;
                    list.appendChild(li);
                });
            } else {
                 list.innerHTML = '<li class="report-item" style="justify-content:center; color: var(--error);">Failed to load recent scans</li>';
            }
        }

        // Init
        checkSession();
    </script>
</body>
</html>
<?php /**PATH C:\wamp64\www\Edumacflow\eduflow\qr-attendance\resources\views/welcome.blade.php ENDPATH**/ ?>