<?php $__env->startSection('content'); ?>
<div class="min-h-screen py-8 bg-gray-50 flex items-center justify-center px-4">
    <div class="verification-box bg-white w-full max-w-4xl mx-auto">
        <div class="p-6 sm:p-8">_
            <div class="bg-gradient-to-r from-primary to-purple-700 text-white p-6 text-center rounded-t-lg -m-6 sm:-m-8 mb-8">
                <h1 class="text-2xl md:text-3xl font-bold">Product Authenticity Report</h1>
            </div>

            <!-- Verification Form (shown if no result is present) -->
            <?php if(!session('error') && !isset($error) && !isset($product)): ?>
                <div class="verification-form-section mt-6">
                    <h2 class="text-xl sm:text-2xl font-bold text-gray-800 text-center mb-4">Verify Your Product</h2>
                    <p class="text-gray-600 text-center mb-6">Enter the serial number or IMEI found on your product to check its authenticity.</p>

                    <form id="verification-form" action="<?php echo e(route('products.verify.post')); ?>" method="POST" class="max-w-lg mx-auto">
                        <?php echo csrf_field(); ?>
                        <div class="relative group">
                            <input type="text" id="serial_no" name="serial_no" placeholder="Enter Serial Number or IMEI..." class="w-full bg-gray-50 border-2 border-gray-300 rounded-full py-3 pl-5 pr-32 text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary transition-colors" required value="<?php echo e(old('serial_no')); ?>">
                            <button type="submit" class="absolute inset-y-0 right-0 flex items-center justify-center bg-primary hover:bg-primary/90 text-white font-bold px-6 rounded-full m-1.5 transition-all duration-300 group-focus-within:shadow-lg">
                                <i class="fas fa-search sm:mr-2"></i>
                                <span class="hidden sm:inline">Verify</span>
                            </button>
                        </div>
                    </form>

                    <!-- OR Separator -->
                    <div class="flex items-center justify-center my-6">
                        <span class="h-px bg-gray-300 flex-1"></span>
                        <span class="px-4 text-sm font-semibold text-gray-500">OR</span>
                        <span class="h-px bg-gray-300 flex-1"></span>
                    </div>

                    <!-- Scan Button and Camera View -->
                    <div class="text-center pb-4 space-y-4">
                        <button type="button" id="scan-qr-btn" class="bg-secondary hover:bg-secondary/90 text-white font-bold py-2 px-8 rounded-full transition duration-300 w-full sm:w-auto">
                            <i class="fas fa-qrcode mr-2"></i> Scan with Camera
                        </button>
                        <div id="scanner-section" class="mt-4 max-w-sm mx-auto hidden">
                            <div id="reader" class="w-full border-2 border-dashed border-gray-300 rounded-lg p-2" style="min-height: 250px;"></div>
                            <div id="scanner-message" class="text-sm mt-2 text-center p-2 rounded"></div>
                            <div id="scanner-loading" class="text-primary text-sm mt-2 text-center hidden">
                                <i class="fas fa-spinner fa-spin mr-2"></i> Starting camera...
                            </div>
                            <div class="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
                                <p class="text-xs text-yellow-800 text-center">
                                    <strong>Browser Support:</strong> Chrome, Firefox, Edge, Safari (iOS 15+), Samsung Internet
                                    <br>
                                    <a href="https://support.google.com/chrome/answer/2693767" target="_blank" class="text-primary hover:underline">How to enable camera access</a>
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Error Result Section -->
            <?php if(session('error') || isset($error)): ?>
                <div class="result-section mt-6 border-t pt-8">
                    <div class="text-center p-4">
                        <div class="mx-auto flex items-center justify-center h-16 w-16 rounded-full bg-red-100 mb-4">
                            <i class="fas fa-times text-red-600 text-3xl"></i>
                        </div>
                        <h2 class="text-2xl font-bold text-gray-800">Verification Failed</h2>
                        <p class="text-gray-600 mt-2 max-w-md mx-auto"><?php echo e(session('error') ?? $error); ?></p>
                        <a href="<?php echo e(route('verify')); ?>" class="mt-6 inline-flex items-center bg-primary text-white font-semibold py-2 px-6 rounded-lg hover:bg-primary/90 transition-colors">
                            <i class="fas fa-arrow-left mr-1"></i> Try Again
                        </a>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Success Result Section -->
            <?php if(isset($product)): ?>
                <div class="result-section mt-6 border-t pt-8">
                    <div class="text-center mb-8">
                        <div class="mx-auto flex items-center justify-center h-16 w-16 rounded-full bg-green-100 mb-4">
                            <i class="fas fa-check-circle text-green-600 text-3xl"></i>
                        </div>
                        <h2 class="text-2xl sm:text-3xl font-bold text-gray-800">Product Verified</h2>
                        <p class="text-gray-600 mt-1">This is an authentic product from our database.</p>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                        <div class="flex justify-center items-center">
                            <div class="product-image w-48 h-48 bg-gray-100 border border-gray-200 rounded-lg flex items-center justify-center p-2 overflow-hidden">
                                <?php if($product->image): ?>
                                    <img src="<?php echo e(asset('storage/' . $product->image)); ?>" alt="<?php echo e($product->product_name); ?>" class="w-full h-full object-cover">
                                <?php else: ?>
                                    <i class="fas fa-mobile-alt text-6xl text-gray-400"></i>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="md:col-span-2">
                            <div class="detail-card border border-gray-200 bg-white p-4 rounded-lg mb-4">
                                <p class="text-gray-500 text-sm font-medium">Product Name</p>
                                <p class="font-semibold text-lg text-gray-800"><?php echo e($product->product_name); ?></p>
                            </div>
                            <div class="detail-card border border-gray-200 bg-white p-4 rounded-lg mb-4">
                                <p class="text-gray-500 text-sm font-medium">Serial No</p>
                                <p class="font-semibold text-lg text-gray-800 font-mono"><?php echo e($product->serial_no); ?></p>
                            </div>
                            <div class="grid grid-cols-2 gap-4">
                                <div class="detail-card border border-gray-200 bg-white p-4 rounded-lg">
                                    <p class="text-gray-500 text-sm font-medium">Condition</p>
                                    <p class="font-semibold text-gray-800"><?php echo e($product->condition); ?></p>
                                </div>
                                <div class="detail-card border border-gray-200 bg-white p-4 rounded-lg">
                                    <p class="text-gray-500 text-sm font-medium">Quality</p>
                                    <p class="font-semibold text-gray-800"><?php echo e($product->quality); ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
                        <div class="detail-card border border-gray-200 bg-white p-4 rounded-lg">
                            <p class="text-gray-500 text-sm font-medium">Status</p>
                            <p class="font-semibold text-gray-800"><?php echo e($product->status); ?></p>
                        </div>
                        <div class="detail-card border border-gray-200 bg-white p-4 rounded-lg">
                            <p class="text-gray-500 text-sm font-medium">IMEI</p>
                            <p class="font-semibold text-gray-800 font-mono"><?php echo e($product->imei ?? 'N/A'); ?></p>
                        </div>
                        <div class="detail-card border border-gray-200 bg-white p-4 rounded-lg">
                            <p class="text-gray-500 text-sm font-medium">Color</p>
                            <p class="font-semibold text-gray-800"><?php echo e($product->color); ?></p>
                        </div>
                    </div>
                    <div class="text-center pt-4 border-t">
                        <button onclick="generateReport('<?php echo e($product->id); ?>')" class="download-btn bg-primary hover:bg-primary/90 text-white py-3 px-6 rounded-lg font-semibold inline-flex items-center transition duration-200">
                            <i class="fas fa-download mr-2"></i> Download Report PDF Copy
                        </button>
                        <a href="<?php echo e(route('verify')); ?>" class="mt-4 sm:mt-0 sm:ml-4 inline-block text-primary hover:underline">Verify Another Product</a>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<!-- Load html5-qrcode library (local if installed, else CDN) -->
<?php if(file_exists(public_path('js/html5-qrcode.min.js'))): ?>
    <script src="<?php echo e(asset('js/html5-qrcode.min.js')); ?>"></script>
<?php else: ?>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html5-qrcode/2.3.8/html5-qrcode.min.js"></script>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const scanButton = document.getElementById('scan-qr-btn');
    const scannerSection = document.getElementById('scanner-section');
    const serialInput = document.getElementById('serial_no');
    const verificationForm = document.getElementById('verification-form');
    const scannerMessage = document.getElementById('scanner-message');
    const scannerLoading = document.getElementById('scanner-loading');
    const reader = document.getElementById('reader');

    let html5QrCode = null;
    let isScannerActive = false;

    // Check for required DOM elements
    if (!scanButton || !scannerSection || !serialInput || !verificationForm || !scannerMessage || !scannerLoading || !reader) {
        console.error('Required DOM elements are missing.');
        showMessage('Error: Page elements not found. Please refresh the page.', 'error');
        return;
    }

    // Check for getUserMedia support
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        console.error('getUserMedia is not supported.');
        showMessage('Error: Your browser does not support camera access. Please use Chrome, Firefox, Edge, Safari (iOS 15+), or Samsung Internet.', 'error');
        scanButton.disabled = true;
        return;
    }

    // Check for HTTPS or localhost
    if (window.location.protocol !== 'https:' && window.location.hostname !== 'localhost') {
        console.error('Camera access requires HTTPS.');
        showMessage('Error: Camera access requires a secure connection (HTTPS). Please access this page via a secure URL.', 'error');
        scanButton.disabled = true;
        return;
    }

    // Check if Html5Qrcode is available
    if (typeof Html5Qrcode === 'undefined') {
        console.error('html5-qrcode library not loaded.');
        showMessage('Error: QR code scanner library failed to load. Please check your internet connection or server configuration.', 'error');
        scanButton.disabled = true;
        return;
    }

    scanButton.addEventListener('click', toggleScanner);

    async function toggleScanner() {
        if (isScannerActive) {
            await stopScanner();
        } else {
            await startScanner();
        }
    }_

    async function startScanner() {
        scannerLoading.classList.remove('hidden');
        scannerMessage.classList.add('hidden');
        scanButton.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Starting...';
        scanButton.disabled = true;

        try {
            html5QrCode = new Html5Qrcode('reader');
            const cameras = await Html5Qrcode.getCameras();
            if (!cameras || cameras.length === 0) {
                showMessage('Error: No cameras found on this device.', 'error');
                scannerLoading.classList.add('hidden');
                stopScanner();
                return;
            }

            const config = {
                fps: 10,
                qrbox: { width: 250, height: 250 },
                aspectRatio: 1.0,
                rememberLastUsedCamera: true
            };

            // Try cameras in order: environment, user, default
            const cameraConstraints = [
                { facingMode: "environment" },
                { facingMode: "user" },
                cameras[0].id // Fallback to first available camera
            ];

            let cameraStarted = false;
            let errorMessage = '';

            for (const constraint of cameraConstraints) {
                try {
                    await html5QrCode.start(
                        constraint,
                        config,
                        onScanSuccess,
                        (error) => {
                            // Suppress frequent scan errors
                            // console.warn(`Scan error: ${error}`);
                        }
                    );
                    cameraStarted = true;
                    break;
                } catch (err) {
                    console.warn(`Failed to start camera with constraint ${JSON.stringify(constraint)}: ${err}`);
                    errorMessage = err.name || err.message;
                }
            }

            if (!cameraStarted) {
                console.error('Failed to start any camera:', errorMessage);
                let message = 'Error: Unable to access camera.';
                if (errorMessage.includes('NotAllowedError')) {
                    message = 'Error: Camera permission denied. Please allow camera access in your browser settings.';
                } else if (errorMessage.includes('NotFoundError')) {
                    message = 'Error: No cameras found on this device.';
                } else if (errorMessage.includes('NotReadableError')) {
                    message = 'Error: Camera is already in use by another application.';
                } else if (errorMessage.includes('OverconstrainedError')) {
                    message = 'Error: No suitable camera found for the requested settings.';
                } else if (errorMessage.includes('NotSupportedError')) {
                    message = 'Error: Camera not supported in this browser. Try Chrome, Firefox, or Edge.';
                }
                showMessage(message, 'error');
                scannerLoading.classList.add('hidden');
                stopScanner();
                return;
            }

            scannerSection.classList.remove('hidden');
            scannerLoading.classList.add('hidden');
            scanButton.innerHTML = '<i class="fas fa-stop mr-2"></i> Stop Scanner';_
            scanButton.classList.replace('bg-secondary', 'bg-red-600');
            scanButton.classList.replace('hover:bg-secondary/90', 'hover:bg-red-700');
            scanButton.disabled = false;
            isScannerActive = true;
            showMessage('Scanning for QR code...', 'info');

        } catch (err) {
            console.error('Scanner initialization failed:', err);
            scannerLoading.classList.add('hidden');
            showMessage('Error: Unable to initialize scanner. Please try again or use a different browser.', 'error');
            stopScanner();
        }
    }

    async function stopScanner() {
        if (html5QrCode && html5QrCode.isScanning) {
            try {
                await html5QrCode.stop();
                await html5QrCode.clear();
                console.log('Scanner stopped successfully');
            } catch (error) {
                console.error('Failed to stop scanner:', error);
            }
        }
        scannerSection.classList.add('hidden');
        scanButton.innerHTML = '<i class="fas fa-qrcode mr-2"></i> Scan with Camera';_
        scanButton.classList.replace('bg-red-600', 'bg-secondary');
        scanButton.classList.replace('hover:bg-red-700', 'hover:bg-secondary/90');
        scanButton.disabled = false;
        isScannerActive = false;
        showMessage('', '');
        scannerLoading.classList.add('hidden');
    }

    function onScanSuccess(decodedText, decodedResult) {
        if (!isScannerActive) return;

        console.log('QR Scan Success:', decodedText);
        let serial = decodedText.trim();

        // Try to extract serial from various formats
        try {
            // Check if it's a URL
            const url = new URL(decodedText);
            serial = url.searchParams.get('serial') ||
                     url.searchParams.get('serial_no') ||
                     url.searchParams.get('code') ||
                     url.searchParams.get('id') ||
                     url.pathname.split('/').pop();
        } catch (e) {
            // Not a URL, try JSON
            try {
                const json = JSON.parse(decodedText);
                serial = json.serial || json.serial_no || json.code || json.id || serial;
            } catch (jsonErr) {
                // Not JSON, use raw text
            }
        }

        // Clean serial number, allow alphanumeric, hyphens, and underscores
        serial = serial.replace(/[^a-zA-Z0-9\-_]/g, '');

        if (serial.length > 0) {
            serialInput.value = serial;
            showMessage('✅ QR code scanned successfully! Submitting...', 'success');
            stopScanner().then(() => {
                verificationForm.submit();
            });
        } else {
            showMessage('Error: Invalid QR code. Please scan a valid product QR code.', 'error');
        }
    }

    function showMessage(message, type = 'info') {
        scannerMessage.innerHTML = message;
        scannerMessage.className = 'text-sm mt-2 text-center p-2 rounded';
        if (type === 'success') {
            scannerMessage.classList.add('bg-green-50', 'text-green-700');
            scannerMessage.classList.remove('bg-red-50', 'text-red-700', 'bg-blue-50', 'text-blue-700');
        } else if (type === 'error') {
            scannerMessage.classList.add('bg-red-50', 'text-red-700');
            scannerMessage.classList.remove('bg-green-50', 'text-green-700', 'bg-blue-50', 'text-blue-700');
            setTimeout(() => showMessage('', ''), 8000); // Hide error after 8 seconds
        } else if (type === 'info') {
            scannerMessage.classList.add('bg-blue-50', 'text-blue-700');
            scannerMessage.classList.remove('bg-green-50', 'text-green-700', 'bg-red-50', 'text-red-700');
        } else {
            scannerMessage.classList.remove('bg-green-50', 'text-green-700', 'bg-red-50', 'text-red-700', 'bg-blue-50', 'text-blue-700');
        }
    }

    // Make generateReport globally accessible
    window.generateReport = function(productId) {
        window.open(`/products/${productId}/report`, '_blank');
    };

    // Cleanup on page unload
    window.addEventListener('beforeunload', () => {
        if (html5QrCode && html5QrCode.isScanning) {
            html5QrCode.stop().catch(error => console.error('Stop error on unload:', error));
            html5QrCode.clear();
        }
    });

    // Cleanup on page hide (for mobile browsers)
    window.addEventListener('pagehide', () => {
        if (html5QrCode && html5QrCode.isScanning) {
            html5QrCode.stop().catch(error => console.error('Stop error on pagehide:', error));
            html5QrCode.clear();
        }
    });
});
</script>

<style>
    .verification-box {
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
        border-radius: 1rem;
        overflow: hidden;
    }

    #reader {
        position: relative;
        width: 100%;
        max-width: 400px;
        margin: 0 auto;
    }

    #reader video {
        width: 100% !important;
        height: auto !important;
        border-radius: 8px;
        border: 2px dashed #cbd5e1;
        object-fit: cover;
    }

    @media (max-width: 640px) {
        .verification-box {
            margin: 10px;
        }
        #scanner-section {
            max-width: 100%;
        }
        #reader {
            min-height: 200px !important;
        }
        #reader video {
            width: 100% !important;
            height: 200px !important;
        }
    }

    .bg-green-50 {
        background-color: #f0fdf4;
    }
    .text-green-700 {
        color: #15803d;
    }
    .bg-red-50 {
        background-color: #fef2f2;
    }
    .text-red-700 {
        color: #b91c1c;
    }
    .bg-blue-50 {
        background-color: #eff6ff;
    }
    .text-blue-700 {
        color: #1e40af;
    }

    .bg-yellow-50 {
        background-color: #fffbeb;
    }
    .text-yellow-800 {
        color: #a16207;
    }

    .fa-spinner {
        animation: spin 1s linear infinite;
    }
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
</style>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('frontend.layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\E-Product-Verify-Auth-Application-5\resources\views\products\verify.blade.php ENDPATH**/ ?>