<?php

// Bootstrap configuration and autoloading
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/session.php';
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/vendor/autoload.php';

use App\Core\Database;
use App\Models\ProductModel;

SessionManager::init();

$productId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$token = $_GET['token'] ?? '';
$hasPayload = $productId > 0 && !empty($token);
$errorMessage = '';
$product = null;
$inventory = [];

if ($hasPayload) {
    $expected = hash_hmac('sha256', $productId, SECURE_AUTH_KEY);
    if (!hash_equals($expected, $token)) {
        $errorMessage = 'Invalid or expired scan token.';
    } else {
        try {
            $db = Database::getInstance()->getConnection();
            $productModel = new ProductModel($db);
            $product = $productModel->getProductDetails($productId);
            if ($product && empty($product['deleted_at'])) {
                $inventory = $productModel->getProductInventory($productId);
            } else {
                $errorMessage = 'Product not found or unavailable.';
            }
        } catch (\Exception $e) {
            $errorMessage = 'Database unavailable.';
        }
    }
}

function h($value): string
{
    return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scan</title>
    <script src="<?php echo APP_URL; ?>/public/vendor/tailwind-3.4.16.js"></script>
    <link rel="stylesheet" href="<?php echo APP_URL; ?>/public/vendor/fontawesome-6.4.0.min.css">
</head>
<body class="min-h-screen bg-gradient-to-b from-indigo-50 via-white to-purple-50 text-gray-900 relative overflow-hidden overflow-y-auto">
    <div class="pointer-events-none absolute inset-0 opacity-60">
        <div class="absolute -left-16 top-10 h-64 w-64 rounded-full bg-indigo-200 blur-3xl"></div>
        <div class="absolute right-0 top-32 h-64 w-64 rounded-full bg-purple-200 blur-3xl"></div>
        <div class="absolute left-10 bottom-10 h-52 w-52 rounded-full bg-sky-200 blur-3xl"></div>
    </div>
    <div class="max-w-6xl mx-auto px-4 py-10 space-y-6">
        <?php if ($errorMessage): ?>
            <div class="bg-red-50 border border-red-200 text-red-700 rounded-2xl p-4 shadow">
                <p class="font-semibold">Notice</p>
                <p class="text-sm"><?php echo h($errorMessage); ?></p>
            </div>
        <?php endif; ?>

        <?php if ($product): ?>
            <div class="bg-gradient-to-r from-indigo-500 via-purple-500 to-sky-500 rounded-3xl p-6 shadow-xl flex items-center justify-between text-white">
                <div>
                    <p class="text-sm uppercase tracking-widest text-white/80">Scan verified</p>
                    <h1 class="text-3xl font-bold mt-1"><?php echo h($product['part_number']); ?></h1>
                    <p class="text-white/80 mt-1"><?php echo h($product['description'] ?? ''); ?></p>
                    <div class="mt-3 flex space-x-2">
                        <span class="px-3 py-1 rounded-full bg-white/20 text-white text-xs font-semibold border border-white/30"><?php echo h($product['type_name'] ?? 'Type'); ?></span>
                        <span class="px-3 py-1 rounded-full bg-white/20 text-white text-xs font-semibold border border-white/30"><?php echo h($product['category_name'] ?? 'Category'); ?></span>
                    </div>
                </div>
                <div class="text-right">
                    <p class="text-white/80 text-sm">Total Stock</p>
                    <p class="text-4xl font-black"><?php echo h($product['total_stock'] ?? 0); ?></p>
                </div>
            </div>
        <?php else: ?>
            <div class="bg-gradient-to-r from-indigo-500 via-purple-500 to-blue-500 rounded-2xl p-6 shadow-lg text-white">
                <p class="text-sm uppercase tracking-widest text-white/80">Ready</p>
                <h1 class="text-3xl font-bold mt-1">Scan a product QR</h1>
                <p class="text-white/80 mt-2">Tap “Start scanning” to open your camera, then point at the QR code from a product detail page.</p>
            </div>
        <?php endif; ?>

        <div class="bg-white border border-gray-200 rounded-3xl shadow p-6 space-y-3">
            <button id="openScanner"
                    class="w-full px-4 py-3 rounded-xl bg-gradient-to-r from-indigo-500 via-purple-500 to-sky-500 hover:from-indigo-600 hover:via-purple-600 hover:to-sky-600 text-white font-semibold shadow flex items-center justify-center space-x-2 transition">
                <i class="fas fa-camera text-lg"></i><span><?php echo $product ? 'Scan another' : 'Start scanning'; ?></span>
            </button>
            <div id="scannerArea" class="hidden bg-gray-50 border border-gray-200 rounded-xl p-4 space-y-3">
                <div id="videoContainer" class="w-full aspect-square bg-gray-200 border border-gray-300 rounded-lg overflow-hidden flex items-center justify-center text-gray-500">
                    <video id="qrVideo" class="w-full h-full object-cover hidden" muted playsinline></video>
                    <div id="cameraPlaceholder" class="text-sm">Camera preview</div>
                </div>
                <div id="scannerStatus" class="text-xs text-gray-600"></div>
                <button id="closeScanner" class="w-full px-4 py-3 rounded-xl bg-red-100 hover:bg-red-200 text-red-700 border border-red-200 text-sm font-semibold">Close Scanner</button>
            </div>
        </div>

        <?php if ($product): ?>
        <div class="text-center">
            <h2 class="text-xl font-semibold text-gray-900 flex items-center justify-center space-x-2 mb-4">
                <span class="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-blue-100 text-blue-600">
                    <i class="fas fa-warehouse"></i>
                </span>
                <span>Stock Info</span>
            </h2>

            <?php
            $byLocation = [];
            foreach ($inventory as $row) {
                $locKey = $row['location_id'] ?? $row['location_name'];
                if (!isset($byLocation[$locKey])) {
                    $byLocation[$locKey] = [
                        'name' => $row['location_name'],
                        'location_id' => $row['location_id'] ?? null,
                        'rows' => []
                    ];
                }
                $byLocation[$locKey]['rows'][] = $row;
            }
            ?>

            <?php if (empty($byLocation)) : ?>
                <p class="text-gray-500 text-sm">No inventory records for this product.</p>
            <?php else : ?>
                <div class="grid gap-4 md:grid-cols-2">
                    <?php foreach ($byLocation as $loc): ?>
                        <div class="rounded-2xl bg-white border border-gray-200 p-4 space-y-3 shadow-sm">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-sm text-gray-500">Location</p>
                                    <p class="text-lg font-semibold text-gray-900"><?php echo h($loc['name']); ?></p>
                                </div>
                            </div>

                            <div class="grid gap-2 sm:grid-cols-2">
                                <?php foreach ($loc['rows'] as $idx => $row): ?>
                                    <?php $rowId = 'row-' . md5($loc['name'] . ($row['size'] ?? '') . $idx); ?>
                                    <div class="rounded-xl bg-white border border-gray-200 shadow-sm">
                                        <button type="button"
                                                class="w-full flex items-center justify-between px-3 py-2 text-left"
                                                onclick="toggleActions('<?php echo $rowId; ?>')">
                                            <div>
                                                <p class="text-xs text-gray-500">Size</p>
                                                <p class="text-sm font-semibold text-gray-900"><?php echo h($row['size'] ?? 'N/A'); ?></p>
                                            </div>
                                            <div class="text-right">
                                                <p class="text-xs text-gray-500">Qty</p>
                                                <p class="text-xl font-bold text-gray-900"><?php echo h($row['quantity']); ?></p>
                                            </div>
                                        </button>
                                        <div id="<?php echo $rowId; ?>" class="hidden border-t border-gray-100 bg-gray-50 px-3 py-2 grid grid-cols-3 gap-3 w-full">
                                            <?php
                                            $locParam = $loc['location_id'] ? '&location_id=' . $loc['location_id'] : '';
                                            $sizeParam = $row['size_id'] ? '&size_id=' . $row['size_id'] : '';
                                            ?>
                                            <a href="<?php echo APP_URL; ?>/stock/add?product_id=<?php echo h($productId); ?><?php echo $locParam; ?><?php echo $sizeParam; ?>"
                                               class="h-12 rounded-xl bg-gradient-to-br from-blue-500 to-indigo-500 text-white flex items-center justify-center shadow-md hover:shadow-lg transition">
                                                <i class="fas fa-plus text-2xl"></i>
                                                <span class="sr-only">Stock In</span>
                                            </a>
                                            <a href="<?php echo APP_URL; ?>/stock/out?product_id=<?php echo h($productId); ?><?php echo $locParam; ?><?php echo $sizeParam; ?>"
                                               class="h-12 rounded-xl bg-gradient-to-br from-emerald-500 to-green-500 text-white flex items-center justify-center shadow-md hover:shadow-lg transition">
                                                <i class="fas fa-minus text-2xl"></i>
                                                <span class="sr-only">Stock Out</span>
                                            </a>
                                            <a href="<?php echo APP_URL; ?>/stock/transfer?product_id=<?php echo h($productId); ?><?php echo $locParam; ?><?php echo $sizeParam; ?>"
                                               class="h-12 rounded-xl bg-gradient-to-br from-pink-500 to-rose-500 text-white flex items-center justify-center shadow-md hover:shadow-lg transition">
                                                <i class="fas fa-exchange-alt text-2xl"></i>
                                                <span class="sr-only">Transfer</span>
                                            </a>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.js"></script>
    <script>
        const scannerArea = document.getElementById('scannerArea');
        const openScanner = document.getElementById('openScanner');
        const closeScanner = document.getElementById('closeScanner');
        const video = document.getElementById('qrVideo');
        const placeholder = document.getElementById('cameraPlaceholder');
        const statusEl = document.getElementById('scannerStatus');
        let stream = null;
        let scanInterval = null;

        function toggleActions(id) {
            const panel = document.getElementById(id);
            if (panel) {
                panel.classList.toggle('hidden');
            }
        }

        async function startScanner() {
            stopScanner();
            scannerArea?.classList.remove('hidden');
            statusEl.textContent = 'Requesting camera access...';

            if (location.protocol !== 'https:') {
                statusEl.textContent = 'Camera requires HTTPS. Please use a secure connection.';
                return;
            }

            if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                statusEl.textContent = 'Camera not supported on this device/browser.';
                return;
            }

            try {
                stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } });
                video.srcObject = stream;
                video.setAttribute('autoplay', '');
                video.setAttribute('playsinline', '');
                video.muted = true;
                video.classList.remove('hidden');
                placeholder.classList.add('hidden');
                await video.play();
                statusEl.textContent = '';
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');

                scanInterval = setInterval(() => {
                    if (video.readyState === video.HAVE_ENOUGH_DATA) {
                        canvas.width = video.videoWidth;
                        canvas.height = video.videoHeight;
                        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                        const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                        const code = jsQR(imageData.data, canvas.width, canvas.height);
                        if (code && code.data) {
                            clearInterval(scanInterval);
                            statusEl.textContent = 'QR detected, redirecting...';
                            stopScanner();
                            window.location.href = code.data;
                        }
                    }
                }, 300);
            } catch (err) {
                statusEl.textContent = 'Unable to access camera: ' + err.message;
            }
        }

        function stopScanner() {
            if (scanInterval) {
                clearInterval(scanInterval);
                scanInterval = null;
            }
            if (stream) {
                stream.getTracks().forEach(t => t.stop());
                stream = null;
            }
            video.pause();
            video.srcObject = null;
            video.classList.add('hidden');
            placeholder.classList.remove('hidden');
            scannerArea?.classList.add('hidden');
        }

        openScanner?.addEventListener('click', () => {
            if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                statusEl.textContent = 'Camera access not supported in this browser.';
                scannerArea?.classList.remove('hidden');
                return;
            }
            startScanner();
        });

        closeScanner?.addEventListener('click', stopScanner);
        window.addEventListener('beforeunload', stopScanner);
    </script>
</body>
</html>
