<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Amazon Product Lookup</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <!-- Add jQuery and SweetAlert libraries -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
</head>
<body class="bg-gray-100">
    <div class="container mx-auto px-4 py-8">
        <h1 class="text-2xl font-bold mb-6 text-center">VH-AI Barcode Scanner</h1>
        
        <div class="bg-white rounded-lg shadow-md overflow-hidden">
            <!-- <div class="p-4 bg-blue-500 text-white">
                <h2 class="text-lg font-semibold">Scan a Barcode</h2>
            </div> -->
            
            <div class="p-4">
                <!-- HTML5 QR Code Scanner Element -->
                <div id="reader" class="w-full h-48 mb-4"></div>
                
                <div class="flex justify-center space-x-4 mb-6">
                    <button id="start-button" class="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 focus:outline-none">
                        Start Scanner
                    </button>
                    <button id="stop-button" class="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600 focus:outline-none" disabled>
                        Stop Scanner
                    </button>
                </div>
                
                <div class="border rounded-lg p-4 bg-gray-50">
                    <h3 class="font-semibold mb-2">Scan Result:</h3>
                    <div id="scan-result" class="p-2 min-h-16 bg-white border rounded">
                        No barcode detected yet
                    </div>
                    
                    <div class="mt-4 flex justify-center">
                        <button id="search-amazon-button" class="px-4 py-2 bg-yellow-500 text-white rounded hover:bg-yellow-600 focus:outline-none hidden">
                            Search on Amazon
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Import HTML5-QRCode library -->
    <script src="https://unpkg.com/html5-qrcode"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const startButton = document.getElementById('start-button');
            const stopButton = document.getElementById('stop-button');
            const resultContainer = document.getElementById('scan-result');
            const searchAmazonButton = document.getElementById('search-amazon-button');
            let html5QrCode = null;
            let lastScannedBarcode = null;
            
            startButton.addEventListener('click', startScanner);
            stopButton.addEventListener('click', stopScanner);
            searchAmazonButton.addEventListener('click', function() {
                if (lastScannedBarcode) {
                    getScannedAmazonProductData(lastScannedBarcode);
                }
            });
            
            function startScanner() {
                html5QrCode = new Html5Qrcode("reader");
                const config = { 
                    fps: 10, 
                    qrbox: { width: 250, height: 350 },
                    preferredFacingMode: "environment"
                };
                
                html5QrCode.start(
                    { facingMode: "environment" },
                    config,
                    onScanSuccess,
                    onScanFailure
                ).then(() => {
                    startButton.disabled = true;
                    stopButton.disabled = false;
                }).catch((err) => {
                    alert(`Error starting scanner: ${err}`);
                    console.error(err);
                });
            }
            
            function stopScanner() {
                if (html5QrCode) {
                    html5QrCode.stop().then(() => {
                        startButton.disabled = false;
                        stopButton.disabled = true;
                    }).catch((err) => {
                        console.error(err);
                    });
                }
            }
            
            function onScanSuccess(decodedText, decodedResult) {
                // Store the scanned barcode
                lastScannedBarcode = decodedText;
                
                // Display the scanned barcode
                resultContainer.textContent = `Detected: ${decodedText}`;
                
                // Show the Amazon search button
                //searchAmazonButton.classList.remove('hidden');

                stopScanner();
                getScannedAmazonProductData(decodedText, 'A2NODI4BBRA1B1');
                
                // First check if the product exists in our database
                //sendBarcodeToServer(decodedText);
            }
            
            function onScanFailure(error) {
                // Handle scan failure, usually better to ignore and keep scanning
                // console.warn(`Code scan error = ${error}`);
            }
            
            function sendBarcodeToServer(barcode) {
                fetch('/api/barcode/process', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({ barcode: barcode })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.product) {
                        resultContainer.innerHTML = `
                            <div class="p-3 bg-green-100 border-l-4 border-green-500">
                                <p class="font-bold">Product Found: ${data.product.name}</p>
                                <p>Price: $${data.product.price}</p>
                                <p>SKU: ${data.product.sku}</p>
                            </div>
                        `;
                    } else {
                        resultContainer.innerHTML = `
                            <div class="p-3 bg-yellow-100 border-l-4 border-yellow-500">
                                <p>Product not found in database for barcode: ${barcode}</p>
                                <p>Click "Search on Amazon" to find this product.</p>
                            </div>
                        `;
                    }
                })
                .catch((error) => {
                    console.error('Error:', error);
                    resultContainer.innerHTML = `
                        <div class="p-3 bg-red-100 border-l-4 border-red-500">
                            <p>Error processing barcode: ${error}</p>
                        </div>
                    `;
                });
            }
            
            // Function to get Amazon product data
            function getScannedAmazonProductData(barcode, sellerId = 'A2NODI4BBRA1B1') {
                resultContainer.textContent = 'Fetching product details...';
                const url = `/amazon/getProductDetails/${barcode}/true/${sellerId}`;
                console.log(`Fetching Amazon data from: ${url}`);
                
                $.ajax({
                    method: 'GET',
                    url: url,
                    dataType: 'json',
                    success: function(result) {
                        var product = result;
                        
                        // Find the largest image
                        let largestImage = product.Images.reduce((largest, image) => {
                            return (image.width * image.height > largest.width * largest.height) ? image : largest;
                        }, product.Images[0]);

                        // Create HTML for the product details
                        var html = `
                            <div style="max-width: 100%; padding: 5px;">
                                <table style="width: 100%; border-collapse: collapse; font-family: Arial, sans-serif;">
                                    <tbody>
                                        <tr><th style="text-align: left; padding: 3px; background: #f2f2f2;">Barcode</th><td style="padding: 3px;">${barcode}</td></tr>
                                        <tr><th style="text-align: left; padding: 3px; background: #f2f2f2;">Title</th><td style="padding: 3px;">${product.Title}</td></tr>
                                        <tr><th style="text-align: left; padding: 3px; background: #f2f2f2;">Binding</th><td style="padding: 3px;">${product.Binding}</td></tr>
                                        <tr><th style="text-align: left; padding: 3px; background: #f2f2f2;">Publication</th><td style="padding: 3px;">${product.PublicationDate.substring(0, 10)}</td></tr>
                                        <tr><th style="text-align: left; padding: 3px; background: #f2f2f2;">Pages</th><td style="padding: 3px;">${product.Pages}</td></tr>
                                        <tr><th style="text-align: left; padding: 3px; background: #f2f2f2;">Audience</th><td style="padding: 3px;">${product.TargetAudience}</td></tr>
                                        <tr><th style="text-align: left; padding: 3px; background: #f2f2f2;">Price</th><td style="padding: 3px; color: green; font-weight: bold;">${product.Price}</td></tr>
                                        <tr><th style="text-align: left; padding: 3px; background: #f2f2f2;">Authors</th><td style="padding: 3px;">${product.Authors.join(', ')}</td></tr>
                                        <tr>
                                            <th style="text-align: left; padding: 3px; background: #f2f2f2;">Ranks</th>
                                            <td style="padding: 3px;">
                                                ${product.ClassificationRanks.map(rank => 
                                                    `<span style="display: block; font-size: 14px; color: #555;">
                                                        <a href="${rank.link}" target="_blank" style="color: #0073e6; text-decoration: none;">
                                                            <strong>${rank.title}</strong>
                                                        </a> (Rank: #${rank.rank})
                                                    </span>`).join('')}
                                            </td>
                                        </tr>
                                        <tr>
                                            <th style="text-align: left; padding: 3px; background: #f2f2f2;">Image</th>
                                            <td style="padding: 3px; text-align: center;">
                                                <a href="${largestImage.link}" target="_blank">
                                                    <img src="${largestImage.link}" style="max-width: auto; height: 200px; border-radius: 5px; box-shadow: 2px 2px 5px rgba(0,0,0,0.2); cursor: pointer;" title="Click to open in new tab">
                                                </a>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        `;

                        let existsInDbText = result.ExistsInDb ? '' : '\nThis product is not listed in your store!';

                        swal({
                            title: '📦 Product Details',
                            text: existsInDbText,
                            content: $(html)[0], // Ensures the HTML content is properly displayed
                            buttons: {
                                cancel: "Close",
                                ...(result.ExistsInDb ? {} : {
                                    listProduct: {
                                        text: "📋 List in My Store",
                                        value: "list",
                                        className: "swal-button--list"
                                    },
                                    addToWishList: {
                                        text: "⭐ Add to Wish List",
                                        value: "wish",
                                        className: "swal-button--wishlist"
                                    }
                                })
                            },
                            className: 'swal-wide' // Custom class to make the popup wider
                        }).then((value) => {
                            if (value === "list") {
                                listProductInStore(product);
                            } else if (value === "wish") {
                                addToWishList(product);
                            }
                        });

                        // Add custom styles to make the swal popup wider
                        var style = document.createElement('style');
                        style.innerHTML = `
                            .swal-wide {
                                width: 80% !important;
                                max-width: 800px !important;
                            }
                            .swal-button--list {
                                background-color: #0073e6 !important;
                                color: white !important;
                            }
                            .swal-button--wishlist {
                                background-color: #00b7ff !important;
                                color: white !important;
                            }
                        `;
                        document.head.appendChild(style);
                    },
                    error: function(xhr, status, error) {
                        resultContainer.textContent = 'Product Not Found';
                        swal({
                            title: 'Product Not Found',
                            text: 'Unfortunately, we were unable to locate the product on Amazon.',
                            icon: 'error',
                            button: 'OK'
                        });
                    }
                });
            }
            
            // Placeholder functions for the list and wishlist functionality
            function listProductInStore(product) {
                // This function would be implemented based on your application's needs
                swal({
                    title: 'Adding to Store',
                    text: `Adding ${product.Title} to your store...`,
                    icon: 'info',
                    button: false,
                    closeOnClickOutside: false
                });
                
                // Here you would make an AJAX call to your backend to add the product
                // For demonstration, we'll just show a success message after a delay
                setTimeout(() => {
                    swal({
                        title: 'Success!',
                        text: `${product.Title} has been added to your store.`,
                        icon: 'success',
                        button: 'OK'
                    });
                }, 1500);
            }
            
            function addToWishList(product) {
                // This function would be implemented based on your application's needs
                swal({
                    title: 'Adding to Wishlist',
                    text: `Adding ${product.Title} to your wishlist...`,
                    icon: 'info',
                    button: false,
                    closeOnClickOutside: false
                });
                
                // Here you would make an AJAX call to your backend to add the product to wishlist
                // For demonstration, we'll just show a success message after a delay
                setTimeout(() => {
                    swal({
                        title: 'Success!',
                        text: `${product.Title} has been added to your wishlist.`,
                        icon: 'success',
                        button: 'OK'
                    });
                }, 1500);
            }
        });
    </script>
</body>
</html>