<?php
session_start();
include "../include/config.php"; 

$message = "";
$result = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $verification_code = trim($_POST['verification_code']);

    if (!empty($verification_code)) {
        // Join certificates with students table to get student info
        $stmt = $conn->prepare("
            SELECT c.*, s.studentname, s.image, s.program, s.intake 
            FROM certificates c
            INNER JOIN students s ON c.studentid = s.studentid
            WHERE c.document_id = ? OR c.security_code = ?
            LIMIT 1
        ");
        $stmt->bind_param("ss", $verification_code, $verification_code);
        $stmt->execute();
        $res = $stmt->get_result();

        if ($res->num_rows > 0) {
            $result = $res->fetch_assoc();
            // Calculate expiry date 21 days from generated_on
            $expiry_date = date("Y-m-d", strtotime($result['generated_on'] . ' +21 days'));
        } else {
            $message = "No certificate found with this code.";
        }
    } else {
        $message = "Please enter a verification code.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Certificate Verification - UNICOHS University</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Signika+Negative:wght@300..700&family=Source+Sans+Pro&display=swap" rel="stylesheet">
    <link rel="icon" href="favicon.png" type="image/png">
    <meta name="theme-color" content="var(--primary)">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <style>
        :root {
            --primary-color: var(--primary);
            --secondary-color: #146c43;
            --danger-color: #dc3545;
            --light-color: #f7f9fc;
            --dark-color: #343a40;
            --border-radius: 12px;
            --box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            --transition: all 0.3s ease;
        }
        
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: var(--dark-color);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .container {
            flex: 1;
            padding-top: 2rem;
            padding-bottom: 2rem;
        }
        
        .page-title {
            color: var(--primary);
            font-weight: 700;
            margin-bottom: 1.5rem;
            text-align: center;
            font-size: 2.2rem;
        }
        
        .page-subtitle {
            color: #6c757d;
            text-align: center;
            margin-bottom: 2rem;
            font-size: 1.1rem;
        }
        
        .card-verification {
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            border: none;
            overflow: hidden;
            margin-bottom: 2rem;
            transition: var(--transition);
            background: white;
        }
        
        .student-image {
            width: 120px;
            height: 120px;
            object-fit: cover;
            border-radius: 50%;
            border: 3px solid var(--primary);
            margin: 0 auto 1rem;
            display: block;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .certificate-header {
            background: linear-gradient(135deg, var(--primary), #a8323e);
            color: #fff;
            font-weight: bold;
            font-size: 1.2rem;
            text-align: center;
            padding: 15px;
            position: relative;
        }
        
        .info-row {
            margin-bottom: 12px;
            display: flex;
            flex-wrap: wrap;
            border-bottom: 1px dashed #e9ecef;
            padding-bottom: 8px;
        }
        
        .info-label {
            font-weight: 600;
            color: var(--dark-color);
            min-width: 140px;
            margin-right: 10px;
        }
        
        .info-value {
            flex: 1;
            color: #495057;
        }
        
        .expiry-text {
            font-weight: bold;
            color: var(--danger-color);
            background-color: rgba(220, 53, 69, 0.1);
            padding: 8px 12px;
            border-radius: 6px;
            margin-top: 5px;
        }
        
        .verification-form {
            background: white;
            padding: 2rem;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            margin-bottom: 2rem;
        }
        
        .form-label {
            font-weight: 600;
            color: var(--dark-color);
            margin-bottom: 0.5rem;
        }
        
        .btn-verify {
            background: var(--primary);
            border: none;
            padding: 12px;
            font-weight: 600;
            font-size: 1.1rem;
            transition: var(--transition);
            color: white;
        }
        
        .btn-verify:hover {
            background: #a8323e;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(208, 63, 77, 0.3);
            color: white;
        }
        
        .alert {
            border-radius: var(--border-radius);
            border: none;
            font-weight: 500;
        }
        
        .authentic-badge {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 10px 20px;
            border-radius: 50px;
            display: inline-block;
            margin-top: 1rem;
            font-weight: 600;
            box-shadow: 0 4px 10px rgba(40, 167, 69, 0.3);
        }
        
        /* Scanner Styles */
        .scanner-container {
            background: white;
            padding: 2rem;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            margin-bottom: 2rem;
            text-align: center;
        }
        
        .scanner-section {
            margin-bottom: 2rem;
        }
        
        #reader {
            width: 100%;
            max-width: 500px;
            margin: 0 auto;
            border-radius: var(--border-radius);
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            min-height: 300px;
            position: relative;
            background: #f8f9fa;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 2px dashed #dee2e6;
        }
        
        .scanner-controls {
            display: flex;
            gap: 1rem;
            justify-content: center;
            margin-top: 1rem;
            flex-wrap: wrap;
        }
        
        .btn-scan {
            background: var(--primary);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            font-weight: 600;
            transition: var(--transition);
        }
        
        .btn-scan:hover {
            background: #a8323e;
            transform: translateY(-2px);
            color: white;
        }
        
        .btn-scan.secondary {
            background: #6c757d;
        }
        
        .btn-scan.secondary:hover {
            background: #5a6268;
            color: white;
        }
        
        .btn-scan:disabled {
            background: #6c757d;
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .scanner-status {
            margin-top: 1rem;
            padding: 10px;
            border-radius: 6px;
            font-weight: 500;
        }
        
        .scanner-active {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .scanner-inactive {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .scanner-ready {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .scanner-loading {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        .verification-methods {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 2rem;
            margin-bottom: 2rem;
        }
        
        @media (max-width: 768px) {
            .verification-methods {
                grid-template-columns: 1fr;
            }
        }
        
        .method-card {
            background: white;
            padding: 2rem;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            text-align: center;
            transition: var(--transition);
            cursor: pointer;
        }
        
        .method-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(0,0,0,0.12);
        }
        
        .method-icon {
            font-size: 3rem;
            color: var(--primary);
            margin-bottom: 1rem;
        }
        
        .method-title {
            font-weight: 600;
            color: var(--dark-color);
            margin-bottom: 0.5rem;
        }
        
        .method-description {
            color: #6c757d;
            margin-bottom: 1.5rem;
        }
        
        /* File upload styles */
        .file-upload-container {
            background: white;
            padding: 2rem;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            margin-bottom: 2rem;
            text-align: center;
        }
        
        .file-upload-area {
            border: 2px dashed #dee2e6;
            border-radius: var(--border-radius);
            padding: 3rem 2rem;
            margin-bottom: 1rem;
            background: #f8f9fa;
            transition: var(--transition);
            cursor: pointer;
        }
        
        .file-upload-area:hover {
            border-color: var(--primary);
            background: #f0f8ff;
        }
        
        .file-upload-area.dragover {
            border-color: var(--primary);
            background: #e3f2fd;
        }
        
        .upload-icon {
            font-size: 4rem;
            color: var(--primary);
            margin-bottom: 1rem;
        }
        
        .file-input {
            display: none;
        }
        
        /* Alternative methods */
        .alternative-methods {
            margin-top: 2rem;
            padding-top: 2rem;
            border-top: 1px solid #e9ecef;
        }
        
        /* Responsive adjustments */
        @media (max-width: 768px) {
            .page-title {
                font-size: 1.8rem;
            }
            
            .student-image {
                width: 100px;
                height: 100px;
            }
            
            .info-row {
                flex-direction: column;
            }
            
            .info-label {
                min-width: auto;
                margin-bottom: 5px;
            }
            
            .verification-form, .scanner-container, .file-upload-container {
                padding: 1.5rem;
            }
            
            .method-card {
                padding: 1.5rem;
            }
            
            #reader {
                min-height: 250px;
            }
        }
        
        /* Animation for results */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .fade-in {
            animation: fadeIn 0.5s ease forwards;
        }
        
        /* Loading spinner */
        .spinner-border {
            width: 1.5rem;
            height: 1.5rem;
            display: none;
        }
    </style>
</head>
<body>
    <?php include "../include/nav.php"; ?>
<div class="content">
<div class="container">
    <h1 class="page-title">Certificate Verification Portal</h1>
    <p class="page-subtitle">Verify the authenticity of  certificates using multiple methods</p>

    <!-- Verification Methods -->
    <div class="verification-methods">
        <div class="method-card" onclick="showScanner()">
            <div class="method-icon">
                <i class="bi bi-qr-code-scan"></i>
            </div>
            <h3 class="method-title">Scan QR Code</h3>
            <p class="method-description">Use your camera to scan QR code for instant verification</p>
            <div class="btn btn-scan">
                <i class="bi bi-camera me-2"></i>Start Scanner
            </div>
        </div>
        
        <div class="method-card" onclick="showFileUpload()">
            <div class="method-icon">
                <i class="bi bi-upload"></i>
            </div>
            <h3 class="method-title">Upload Image</h3>
            <p class="method-description">Upload QR code image from your device</p>
            <div class="btn btn-scan secondary">
                <i class="bi bi-cloud-upload me-2"></i>Upload Image
            </div>
        </div>
        
        <div class="method-card" onclick="showManualEntry()">
            <div class="method-icon">
                <i class="bi bi-keyboard"></i>
            </div>
            <h3 class="method-title">Manual Entry</h3>
            <p class="method-description">Enter verification code manually</p>
            <div class="btn btn-scan secondary">
                <i class="bi bi-keyboard me-2"></i>Enter Code
            </div>
        </div>
    </div>

    <!-- Scanner Section -->
    <div class="scanner-section" id="scannerSection" style="display: none;">
        <div class="scanner-container">
            <h3 class="section-title mb-3">
                <i class="bi bi-qr-code-scan me-2"></i>QR Code Scanner
            </h3>
            
            <div id="reader">
                <div class="scanner-placeholder">
                    <i class="bi bi-camera"></i>
                    <p>Scanner will appear here</p>
                    <small class="text-muted">Click "Start Scanner" to begin</small>
                </div>
            </div>
            
            <div class="scanner-controls">
                <button class="btn btn-scan" id="startScanner">
                    <i class="bi bi-camera me-2"></i>Start Scanner
                </button>
                <button class="btn btn-scan secondary" id="stopScanner" style="display: none;">
                    <i class="bi bi-stop-circle me-2"></i>Stop Scanner
                </button>
                <button class="btn btn-scan secondary" onclick="showFileUpload()">
                    <i class="bi bi-upload me-2"></i>Upload Instead
                </button>
            </div>
            
            <div class="scanner-status scanner-ready" id="scannerStatus">
                <i class="bi bi-info-circle me-2"></i>Scanner is ready. Click "Start Scanner" to begin.
            </div>
            
            <!-- Alternative Methods -->
            <div class="alternative-methods">
                <p class="text-muted mb-2">Scanner not working? Try:</p>
                <div class="scanner-controls">
                    <button class="btn btn-scan secondary" onclick="showFileUpload()">
                        <i class="bi bi-upload me-2"></i>Upload QR Image
                    </button>
                    <button class="btn btn-scan secondary" onclick="showManualEntry()">
                        <i class="bi bi-keyboard me-2"></i>Enter Code Manually
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- File Upload Section -->
    <div class="file-upload-container" id="fileUploadSection" style="display: none;">
        <h3 class="section-title mb-3">
            <i class="bi bi-upload me-2"></i>Upload QR Code Image
        </h3>
        
        <div class="file-upload-area" id="fileUploadArea" onclick="document.getElementById('qrImageFile').click()">
            <div class="upload-icon">
                <i class="bi bi-cloud-arrow-up"></i>
            </div>
            <h5>Click to upload QR code image</h5>
            <p class="text-muted">or drag and drop image here</p>
            <small class="text-muted">Supported formats: JPG, PNG, GIF</small>
        </div>
        
        <input type="file" id="qrImageFile" class="file-input" accept="image/*" onchange="handleFileUpload(this.files)">
        
        <div id="uploadPreview" class="mt-3" style="display: none;">
            <img id="uploadedImage" src="#" alt="Uploaded QR Code" class="img-fluid rounded" style="max-height: 200px;">
            <div class="mt-2">
                <button class="btn btn-scan" onclick="processUploadedImage()">
                    <i class="bi bi-search me-2"></i>Scan Uploaded Image
                </button>
                <button class="btn btn-scan secondary" onclick="clearUpload()">
                    <i class="bi bi-x-circle me-2"></i>Choose Different
                </button>
            </div>
        </div>
        
        <div class="scanner-controls mt-3">
            <button class="btn btn-scan secondary" onclick="showScanner()">
                <i class="bi bi-camera me-2"></i>Use Camera Instead
            </button>
            <button class="btn btn-scan secondary" onclick="showManualEntry()">
                <i class="bi bi-keyboard me-2"></i>Enter Code Manually
            </button>
        </div>
    </div>

    <!-- Manual Entry Form -->
    <div class="verification-form" id="manualEntryForm">
        <h3 class="section-title mb-3">
            <i class="bi bi-keyboard me-2"></i>Manual Verification
        </h3>
        <form method="POST" id="verificationForm">
            <div class="mb-3">
                <label for="verification_code" class="form-label">
                    <i class="bi bi-search me-2"></i>Enter Verification Code or Document ID
                </label>
                <input type="text" name="verification_code" id="verification_code" class="form-control form-control-lg" placeholder="e.g. CLR-68D27819AA977" required>
                <div class="form-text">You can enter the code manually or use other methods above</div>
            </div>
            <div class="scanner-controls">
                <button type="submit" class="btn btn-verify w-100">
                    <span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                    Verify Certificate
                </button>
                <button type="button" class="btn btn-scan secondary" onclick="showScanner()">
                    <i class="bi bi-qr-code-scan me-2"></i>Use QR Scanner
                </button>
            </div>
        </form>
    </div>

    <?php if (!empty($message)): ?>
        <div class="alert alert-danger d-flex align-items-center fade-in" role="alert">
            <i class="bi bi-exclamation-triangle me-2"></i>
            <div><?= htmlspecialchars($message) ?></div>
        </div>
    <?php endif; ?>

    <?php if ($result): ?>
        <!-- Results display remains the same -->
        <div class="card card-verification fade-in">
            <div class="certificate-header">
                <i class="bi bi-patch-check me-2"></i>Certificate Verified Successfully
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4 text-center mb-3 mb-md-0">
                        <?php if (!empty($result['image'])): ?>
                            <img src="../../students/img/<?= htmlspecialchars($result['image']) ?>" alt="Student Image" class="student-image">
                        <?php else: ?>
                            <div class="student-image bg-light d-flex align-items-center justify-content-center">
                                <i class="bi bi-person-circle fa-3x text-muted"></i>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-8">
                        <div class="info-row">
                            <span class="info-label">Student Name:</span>
                            <span class="info-value"><?= htmlspecialchars($result['studentname']) ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Student ID:</span>
                            <span class="info-value"><?= htmlspecialchars($result['studentid']) ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Program:</span>
                            <span class="info-value"><?= htmlspecialchars($result['program']) ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Intake:</span>
                            <span class="info-value"><?= htmlspecialchars($result['intake']) ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Document ID:</span>
                            <span class="info-value"><?= htmlspecialchars($result['document_id']) ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Security Code:</span>
                            <span class="info-value"><?= htmlspecialchars($result['security_code']) ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Generated On:</span>
                            <span class="info-value"><?= htmlspecialchars($result['generated_on']) ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Expires On:</span>
                            <span class="info-value expiry-text"><?= $expiry_date ?></span>
                        </div>
                        
                        <div class="text-center mt-4">
                            <div class="authentic-badge">
                                <i class="bi bi-shield-check me-2"></i>This certificate is AUTHENTIC
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="text-center mt-3">
            <button class="btn btn-scan secondary me-2" onclick="window.print()">
                <i class="bi bi-printer me-2"></i>Print Verification
            </button>
            <button class="btn btn-scan" id="shareBtn">
                <i class="bi bi-share me-2"></i>Share Result
            </button>
        </div>
    <?php endif; ?>
</div>

<script>
    let html5QrcodeScanner = null;
    let isScanning = false;
    let scannerLibraryLoaded = false;
    let uploadedImage = null;

    // Method switching functions
    function showScanner() {
        document.getElementById('scannerSection').style.display = 'block';
        document.getElementById('fileUploadSection').style.display = 'none';
        document.getElementById('manualEntryForm').style.display = 'none';
        initializeScanner();
    }

    function showFileUpload() {
        document.getElementById('scannerSection').style.display = 'none';
        document.getElementById('fileUploadSection').style.display = 'block';
        document.getElementById('manualEntryForm').style.display = 'none';
        stopScanner();
    }

    function showManualEntry() {
        document.getElementById('scannerSection').style.display = 'none';
        document.getElementById('fileUploadSection').style.display = 'none';
        document.getElementById('manualEntryForm').style.display = 'block';
        stopScanner();
        setTimeout(() => {
            document.getElementById('verification_code').focus();
        }, 100);
    }

    // Try multiple CDNs for the scanner library
    async function loadScannerLibrary() {
        const cdns = [
            'https://cdn.jsdelivr.net/npm/html5-qrcode@2.3.8/minified/html5-qrcode.min.js',
            'https://unpkg.com/html5-qrcode@2.3.8/minified/html5-qrcode.min.js',
            'https://cdnjs.cloudflare.com/ajax/libs/html5-qrcode/2.3.8/html5-qrcode.min.js'
        ];

        for (let i = 0; i < cdns.length; i++) {
            try {
                await loadScript(cdns[i]);
                scannerLibraryLoaded = true;
                console.log('QR Scanner library loaded from:', cdns[i]);
                return;
            } catch (error) {
                console.warn('Failed to load from:', cdns[i], error);
                if (i === cdns.length - 1) {
                    throw new Error('All CDNs failed to load scanner library');
                }
            }
        }
    }

    function loadScript(src) {
        return new Promise((resolve, reject) => {
            if (typeof Html5QrcodeScanner !== 'undefined') {
                resolve();
                return;
            }

            const script = document.createElement('script');
            script.src = src;
            script.onload = resolve;
            script.onerror = reject;
            document.head.appendChild(script);
        });
    }

    // Initialize scanner
    function initializeScanner() {
        const scannerStatus = document.getElementById('scannerStatus');
        document.getElementById('startScanner').addEventListener('click', startScanner);
        document.getElementById('stopScanner').addEventListener('click', stopScanner);
        
        scannerStatus.innerHTML = '<i class="bi bi-info-circle me-2"></i>Scanner ready. Click "Start Scanner" to begin.';
        scannerStatus.className = 'scanner-status scanner-ready';
    }

    async function startScanner() {
        if (isScanning) return;

        const scannerStatus = document.getElementById('scannerStatus');
        const startBtn = document.getElementById('startScanner');
        
        try {
            startBtn.disabled = true;
            scannerStatus.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>Loading scanner library...';
            scannerStatus.className = 'scanner-status scanner-loading';

            // Try to load scanner library
            if (!scannerLibraryLoaded) {
                try {
                    await loadScannerLibrary();
                } catch (error) {
                    throw new Error('Scanner library failed to load. Please check your internet connection and try again, or use the upload/manual entry methods.');
                }
            }

            // Check camera support
            if (!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia)) {
                throw new Error('Camera not supported on this device/browser. Please use upload or manual entry methods.');
            }

            scannerStatus.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>Requesting camera access...';

            // Test camera access
            const stream = await navigator.mediaDevices.getUserMedia({ 
                video: { facingMode: "environment" } 
            });
            stream.getTracks().forEach(track => track.stop());

            // Initialize and start scanner
            html5QrcodeScanner = new Html5QrcodeScanner(
                "reader", 
                { 
                    fps: 10, 
                    qrbox: { width: 250, height: 250 },
                    aspectRatio: 1.0
                },
                false
            );

            await html5QrcodeScanner.render(onScanSuccess, onScanFailure);
            
            isScanning = true;
            scannerStatus.innerHTML = '<i class="bi bi-camera-video me-2"></i>Scanner active - Point camera at QR code';
            scannerStatus.className = 'scanner-status scanner-active';
            startBtn.style.display = 'none';
            document.getElementById('stopScanner').style.display = 'inline-block';
            
        } catch (err) {
            console.error('Scanner error:', err);
            let errorMessage = err.message || 'Failed to start scanner';
            
            scannerStatus.innerHTML = `<i class="bi bi-exclamation-triangle me-2"></i>${errorMessage}`;
            scannerStatus.className = 'scanner-status scanner-inactive';
            startBtn.disabled = false;
        }
    }

    async function stopScanner() {
        if (html5QrcodeScanner && isScanning) {
            try {
                await html5QrcodeScanner.clear();
                isScanning = false;
                const scannerStatus = document.getElementById('scannerStatus');
                scannerStatus.innerHTML = '<i class="bi bi-pause-circle me-2"></i>Scanner stopped';
                scannerStatus.className = 'scanner-status scanner-inactive';
                document.getElementById('startScanner').style.display = 'inline-block';
                document.getElementById('startScanner').disabled = false;
                document.getElementById('stopScanner').style.display = 'none';
            } catch (err) {
                console.error('Error stopping scanner:', err);
            }
        }
    }

    function onScanSuccess(decodedText, decodedResult) {
        console.log('Scan successful:', decodedText);
        stopScanner();
        document.getElementById('verification_code').value = decodedText;
        
        const scannerStatus = document.getElementById('scannerStatus');
        scannerStatus.innerHTML = '<i class="bi bi-check-circle me-2"></i>QR code scanned successfully! Submitting...';
        scannerStatus.className = 'scanner-status scanner-active';
        
        setTimeout(() => {
            document.getElementById('verificationForm').submit();
        }, 1500);
    }

    function onScanFailure(error) {
        // Silent failure for normal operation
    }

    // File upload handling
    function handleFileUpload(files) {
        if (files.length > 0) {
            const file = files[0];
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    uploadedImage = e.target.result;
                    document.getElementById('uploadedImage').src = uploadedImage;
                    document.getElementById('uploadPreview').style.display = 'block';
                };
                reader.readAsDataURL(file);
            } else {
                alert('Please select a valid image file (JPG, PNG, GIF)');
            }
        }
    }

    function processUploadedImage() {
        if (!uploadedImage) {
            alert('Please upload an image first');
            return;
        }

        if (!scannerLibraryLoaded) {
            alert('QR code processing requires internet connection. Please use manual entry or try again with internet.');
            return;
        }

        // This would require additional library for image processing
        // For now, we'll show a message and suggest manual entry
        alert('Image upload processing requires additional setup. Please use the manual entry method or try the camera scanner with internet connection.');
    }

    function clearUpload() {
        uploadedImage = null;
        document.getElementById('uploadPreview').style.display = 'none';
        document.getElementById('qrImageFile').value = '';
    }

    // Form submission
    document.getElementById('verificationForm').addEventListener('submit', function() {
        const submitBtn = this.querySelector('button[type="submit"]');
        const spinner = this.querySelector('.spinner-border');
        
        submitBtn.disabled = true;
        spinner.style.display = 'inline-block';
        submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span> Verifying...';
    });
    
    // Initialize with manual entry
    document.getElementById('verification_code').focus();
</script>
</body>
</html>