<?php
session_start();
include_once('includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}

$userId = $_SESSION['uid'];
$userType = $_SESSION['usertype'];
$msg = "";

// Initialize cart if not exists
if (!isset($_SESSION['packing_cart'])) {
    $_SESSION['packing_cart'] = [];
}

// Function to get available quantity (inventory - already packed)
function getAvailableQuantity($con, $productId) {
    // Get original inventory quantity
    $invQuery = mysqli_query($con, "SELECT Qty FROM tblinventory WHERE ID='$productId'");
    if (mysqli_num_rows($invQuery) == 0) {
        return 0;
    }
    $invRow = mysqli_fetch_assoc($invQuery);
    $originalQty = $invRow['Qty'];
    
    // Get total packed quantity for this product
    $packedQuery = mysqli_query($con, "SELECT COALESCE(SUM(PackedQty), 0) as TotalPacked FROM tblpacked WHERE ProductId='$productId'");
    $packedRow = mysqli_fetch_assoc($packedQuery);
    $totalPacked = $packedRow['TotalPacked'];
    
    return max(0, $originalQty - $totalPacked);
}

// Function to get available weight (inventory - already packed)
function getAvailableWeight($con, $productId) {
    // Get original inventory weight
    $invQuery = mysqli_query($con, "SELECT Weight FROM tblinventory WHERE ID='$productId'");
    if (mysqli_num_rows($invQuery) == 0) {
        return 0;
    }
    $invRow = mysqli_fetch_assoc($invQuery);
    $originalWeight = $invRow['Weight'];
    
    // Get total packed weight for this product
    $packedQuery = mysqli_query($con, "SELECT COALESCE(SUM(PackedWeight), 0) as TotalPackedWeight FROM tblpacked WHERE ProductId='$productId'");
    $packedRow = mysqli_fetch_assoc($packedQuery);
    $totalPackedWeight = $packedRow['TotalPackedWeight'];
    
    return max(0, $originalWeight - $totalPackedWeight);
}

// Function to get next package number for a project
function getNextPackageNumber($con, $projectName) {
    $projectName = mysqli_real_escape_string($con, $projectName);
    
    // Check if project exists in package numbers table
    $checkQuery = mysqli_query($con, "SELECT LastPackageNumber FROM tblpackagenumbers WHERE ProjectName='$projectName'");
    
    if (mysqli_num_rows($checkQuery) > 0) {
        // Project exists, increment the number
        $row = mysqli_fetch_assoc($checkQuery);
        $nextNumber = $row['LastPackageNumber'] + 1;
        
        // Update the number
        mysqli_query($con, "UPDATE tblpackagenumbers SET LastPackageNumber='$nextNumber', UpdatedDate=NOW() WHERE ProjectName='$projectName'");
    } else {
        // New project, start with 1
        $nextNumber = 1;
        mysqli_query($con, "INSERT INTO tblpackagenumbers (ProjectName, LastPackageNumber) VALUES ('$projectName', '$nextNumber')");
    }
    
    return $nextNumber;
}

// Handle barcode scan
if (isset($_POST['scan_product'])) {
    $barcode = mysqli_real_escape_string($con, trim($_POST['barcode']));
    
    if (!empty($barcode)) {
        // Debug: Log the scanned barcode
        error_log("Scanned barcode: '$barcode'");
        
        // Try multiple approaches to find the product
        // First try exact match
        $productQuery = mysqli_query($con, "SELECT * FROM tblinventory WHERE TRIM(Barcode)='$barcode' LIMIT 1");
        
        // If no exact match, try with CAST to handle data type issues
        if (mysqli_num_rows($productQuery) == 0) {
            $productQuery = mysqli_query($con, "SELECT * FROM tblinventory WHERE CAST(TRIM(Barcode) AS CHAR)='$barcode' LIMIT 1");
        }
        
        // If still no match, try numeric comparison if barcode is numeric
        if (mysqli_num_rows($productQuery) == 0 && is_numeric($barcode)) {
            $productQuery = mysqli_query($con, "SELECT * FROM tblinventory WHERE CAST(TRIM(Barcode) AS UNSIGNED)=" . intval($barcode) . " LIMIT 1");
        }
        
        if (mysqli_num_rows($productQuery) > 0) {
            $product = mysqli_fetch_assoc($productQuery);
            $productId = $product['ID'];
            
            // Get available quantities
            $availableQty = getAvailableQuantity($con, $productId);
            $availableWeight = getAvailableWeight($con, $productId);
            
            // Check current cart quantities
            $cartQty = 0;
            $cartWeight = 0;
            if (isset($_SESSION['packing_cart'][$productId])) {
                $cartQty = $_SESSION['packing_cart'][$productId]['qty'];
                $cartWeight = $_SESSION['packing_cart'][$productId]['weight'];
            }
            
            // Calculate unit weight - handle division by zero
            $unitWeight = 0;
            if ($product['Qty'] > 0 && $product['Weight'] > 0) {
                $unitWeight = $product['Weight'] / $product['Qty'];
            } elseif ($product['Qty'] > 0) {
                // If no weight specified, assume 1kg per unit as default
                $unitWeight = 1;
            }
            
            // Check if we can add more
            $newCartQty = $cartQty + 1;
            $newCartWeight = $cartWeight + $unitWeight;

            // Use whole number weight checking (floor values)
            $newCartWeightFloor = floor($newCartWeight);
            $availableWeightFloor = floor($availableWeight);

            if ($newCartQty <= $availableQty && $newCartWeightFloor <= $availableWeightFloor) {
                if (isset($_SESSION['packing_cart'][$productId])) {
                    $_SESSION['packing_cart'][$productId]['qty']++;
                    $_SESSION['packing_cart'][$productId]['weight'] = $newCartWeight;
                } else {
                    $_SESSION['packing_cart'][$productId] = [
                        'barcode' => $product['Barcode'],
                        'product_name' => $product['ProductName'],
                        'room_no' => $product['RoomNo'],
                        'project_name' => $product['ProjectName'],
                        'max_qty' => $availableQty,
                        'max_weight' => $availableWeight,
                        'unit_weight' => $unitWeight,
                        'qty' => 1,
                        'weight' => $unitWeight
                    ];
                }
                $_SESSION['scan_msg'] = "Product added to cart successfully! (Available: $availableQty qty, " . number_format($availableWeight, 4) . " kg)";
            } else {
                if ($newCartQty > $availableQty) {
                    $_SESSION['scan_msg'] = "Error: Insufficient quantity! Available: $availableQty qty, Cart has: $cartQty qty";
                } else {
                    $_SESSION['scan_msg'] = "Error: Insufficient weight! Available: " . floor($availableWeight) . " kg (whole), Would need: " . floor($newCartWeight) . " kg (whole)";
                }
            }
        } else {
            // Enhanced error message with debugging info
            $debugQuery = mysqli_query($con, "SELECT Barcode FROM tblinventory LIMIT 5");
            $sampleBarcodes = [];
            while ($row = mysqli_fetch_assoc($debugQuery)) {
                $sampleBarcodes[] = "'" . $row['Barcode'] . "'";
            }
            $_SESSION['scan_msg'] = "Error: Product not found! Scanned: '$barcode'. Sample DB barcodes: " . implode(", ", $sampleBarcodes);
        }
    } else {
        $_SESSION['scan_msg'] = "Error: Please enter a barcode!";
    }
    
    // Redirect to prevent resubmission on refresh
    header('Location: packing-module.php');
    exit();
}

// Display message from session and clear it
if (isset($_SESSION['scan_msg'])) {
    $msg = $_SESSION['scan_msg'];
    unset($_SESSION['scan_msg']);
}

// Handle quantity update
if (isset($_POST['update_qty'])) {
    $productId = intval($_POST['product_id']);
    $newQty = intval($_POST['new_qty']);
    
    if (isset($_SESSION['packing_cart'][$productId]) && $newQty > 0) {
        // Recalculate available quantities (fresh from database)
        $availableQty = getAvailableQuantity($con, $productId);
        $availableWeight = getAvailableWeight($con, $productId);
        $unitWeight = $_SESSION['packing_cart'][$productId]['unit_weight'];
        $newWeight = $newQty * $unitWeight;

        // Update max values in cart
        $_SESSION['packing_cart'][$productId]['max_qty'] = $availableQty;
        $_SESSION['packing_cart'][$productId]['max_weight'] = $availableWeight;

        // Use whole number weight checking (floor values)
        $newWeightFloor = floor($newWeight);
        $availableWeightFloor = floor($availableWeight);

        if ($newQty <= $availableQty && $newWeightFloor <= $availableWeightFloor) {
            $_SESSION['packing_cart'][$productId]['qty'] = $newQty;
            $_SESSION['packing_cart'][$productId]['weight'] = $newWeight;
            $msg = "Quantity updated successfully!";
        } else {
            if ($newQty > $availableQty) {
                $msg = "Error: Quantity exceeds available stock! Available: $availableQty";
            } else {
                $msg = "Error: Weight exceeds available stock! Max weight: " . floor($availableWeight) . " kg (whole), Requested: " . floor($newWeight) . " kg (whole)";
            }
        }
    } else {
        $msg = "Error: Invalid quantity or item not found in cart!";
    }
}

// Handle remove from cart
if (isset($_GET['remove_item'])) {
    $productId = intval($_GET['remove_item']);
    if (isset($_SESSION['packing_cart'][$productId])) {
        unset($_SESSION['packing_cart'][$productId]);
        $msg = "Item removed from cart!";
    }
}

// Handle clear cart
if (isset($_POST['clear_cart'])) {
    $_SESSION['packing_cart'] = [];
    $msg = "Cart cleared!";
}

// Handle save package
if (isset($_POST['save_package'])) {
    if (!empty($_SESSION['packing_cart'])) {
        // Get project name from first item
        $firstItem = reset($_SESSION['packing_cart']);
        $projectName = $firstItem['project_name'];
        
        // Get next package number for this project
        $bundleNumber = getNextPackageNumber($con, $projectName);
        
        // Generate simple package ID and bundle name
        $packageId = 'PKG_' . date('YmdHis') . '_' . $userId;
        $bundleName = $bundleNumber; // Simple bundle number like 1, 2, 3
        
        $success = true;
        $errorDetails = [];
        
        // Start transaction
        mysqli_autocommit($con, FALSE);
        
        try {
            foreach ($_SESSION['packing_cart'] as $productId => $item) {
                $barcode = mysqli_real_escape_string($con, $item['barcode']);
                $productName = mysqli_real_escape_string($con, $item['product_name']);
                $roomNo = mysqli_real_escape_string($con, $item['room_no']);
                $projectName = mysqli_real_escape_string($con, $item['project_name']);
                $qty = intval($item['qty']);
                $weight = floatval($item['weight']);
                
                $insertQuery = "INSERT INTO tblpacked (PackageId, PackageName, ProductId, Barcode, ProductName, RoomNo, ProjectName, PackedQty, PackedWeight, PackedBy, PackedDate) 
                               VALUES ('$packageId', '$bundleName', '$productId', '$barcode', '$productName', '$roomNo', '$projectName', '$qty', '$weight', '$userId', NOW())";
                
                if (!mysqli_query($con, $insertQuery)) {
                    throw new Exception("Failed to insert packed item: " . mysqli_error($con));
                }
            }
            
            // Commit transaction
            mysqli_commit($con);
            $success = true;
        } catch (Exception $e) {
            // Rollback transaction
            mysqli_rollback($con);
            $success = false;
            $errorDetails[] = $e->getMessage();
        }
        
        // Re-enable autocommit
        mysqli_autocommit($con, TRUE);
        
        if ($success) {
            $_SESSION['packing_cart'] = [];
            $msg = "Bundle #$bundleName saved successfully! Package ID: $packageId";
        } else {
            $msg = "Error: Failed to save bundle!";
        }
    } else {
        $msg = "Error: Cart cannot be empty!";
    }
}

// Calculate totals and project info
$totalItems = count($_SESSION['packing_cart']);
$totalQty = 0;
$totalWeight = 0;
$projectBundles = [];

foreach ($_SESSION['packing_cart'] as $item) {
    $totalQty += $item['qty'];
    $totalWeight += $item['weight'];
    $projectName = $item['project_name'];
    
    if (!isset($projectBundles[$projectName])) {
        // Get current package count for this project
        $projectName_escaped = mysqli_real_escape_string($con, $projectName);
        $packageCountQuery = mysqli_query($con, "SELECT LastPackageNumber FROM tblpackagenumbers WHERE ProjectName='$projectName_escaped'");
        $currentPackageCount = 0;
        if (mysqli_num_rows($packageCountQuery) > 0) {
            $row = mysqli_fetch_assoc($packageCountQuery);
            $currentPackageCount = $row['LastPackageNumber'];
        }
        
        $projectBundles[$projectName] = [
            'items' => 0,
            'qty' => 0,
            'weight' => 0,
            'next_bundle' => $currentPackageCount + 1
        ];
    }
    
    $projectBundles[$projectName]['items']++;
    $projectBundles[$projectName]['qty'] += $item['qty'];
    $projectBundles[$projectName]['weight'] += $item['weight'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Ihita Industries | Packing Module</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <!-- Remove QuaggaJS, add html5-qrcode for QR/barcode scanning -->
    <script src="https://unpkg.com/html5-qrcode"></script>
    <style>
        .cart-summary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .project-bundle { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; margin-bottom: 10px; }
        .scan-section { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; }
        .cart-item { transition: all 0.3s ease; }
        .cart-item:hover { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
        .barcode-input { font-size: 1.2rem; font-weight: bold; }
        .camera-btn {
            position: absolute;
            right: 5px;
            top: 50%;
            transform: translateY(-50%);
            border: none;
            background: #28a745;
            color: white;
            border-radius: 3px;
            padding: 5px 8px;
            cursor: pointer;
        }
        .barcode-container {
            position: relative;
        }
        .alert-auto-hide {
            animation: fadeOut 0.5s ease-in-out 1.5s forwards;
        }
        @keyframes fadeOut {
            0% { opacity: 1; }
            100% { opacity: 0; display: none; }
        }
        @media (max-width: 768px) {
            .table-responsive table, .table-responsive thead, .table-responsive tbody, .table-responsive th, .table-responsive td, .table-responsive tr {
                display: block;
            }
            .table-responsive thead tr { position: absolute; top: -9999px; left: -9999px; }
            .table-responsive tr { border: 1px solid #ccc; margin-bottom: 10px; }
            .table-responsive td {
                border: none; position: relative; padding-left: 50% !important;
            }
            .table-responsive td:before {
                content: attr(data-label) ": "; position: absolute; left: 6px; width: 45%;
                padding-right: 10px; white-space: nowrap; font-weight: bold;
            }
        }
        #scanner-container {
            position: relative;
            width: 100%;
            max-width: 400px;
            height: 300px;
            margin: 0 auto;
        }
        #scanner-container video {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .scanner-overlay {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 200px;
            height: 100px;
            border: 2px solid #00ff00;
            background: transparent;
            pointer-events: none;
        }
        .scanner-line {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 2px;
            background: #00ff00;
            animation: scanLine 2s linear infinite;
        }
        @keyframes scanLine {
            0% { top: 0; }
            100% { top: 96px; }
        }
        #qr-reader {
            width: 100% !important;
            max-width: 400px;
            margin: 0 auto;
        }
    </style>
</head>
<body id="page-top">
    <div id="wrapper">
       
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                 
                <div class="container-fluid mt-3 mb-3">
                    
                    <?php if($msg) { ?>
                        <div class="alert alert-info text-center alert-auto-hide" id="alertMsg"><?php echo $msg; ?></div>
                    <?php } ?>

                    <!-- Barcode Scanner Section -->
                    <div class="card shadow mb-4">
                        <div class="card-body">
                            <form method="post" autocomplete="off">
                                <div class="row">
                                    <div class="col-md-8">
                                        <div class="barcode-container">
                                            <input type="text" name="barcode" id="barcodeInput" class="form-control barcode-input" placeholder="Scan or enter barcode..." required autofocus>
                                            <button type="button" class="camera-btn" onclick="startBarcodeScanner()" title="Open Camera Scanner">
                                                <i class="fas fa-camera"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <button type="submit" name="scan_product" class="btn btn-success btn-block">
                                            <i class="fas fa-plus"></i> Add to Cart
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Project Bundle Summary -->
                    <?php if (!empty($projectBundles)) { ?>
                    <div class="row mb-4">
                        <?php foreach ($projectBundles as $projectName => $bundleInfo) { ?>
                        <div class="col-md-12 mb-2">
                            <div class="card shadow project-bundle">
                                <div class="card-body text-center py-2">
                                    <h6 class="mb-1"><i class="fas fa-box"></i> <?php echo htmlspecialchars($projectName); ?></h6>
                                    <div class="row">
                                        <div class="col-4">
                                            <small>Items: <?php echo $bundleInfo['items']; ?></small>
                                        </div>
                                        <div class="col-4">
                                            <small>Qty: <?php echo $bundleInfo['qty']; ?></small>
                                        </div>
                                        <div class="col-4">
                                            <small>Weight: <?php echo number_format($bundleInfo['weight'], 4); ?> kg</small>
                                        </div>
                                        <div class="col-4">
                                            <small>Bundle #: <?php echo $bundleInfo['next_bundle']; ?></small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php } ?>
                    </div>
                    <?php } ?>

                    <!-- Packing Cart -->
                    <div class="card shadow mb-4">
                        <div class="card-header bg-primary text-white">
                            <div class="row align-items-center">
                                <div class="col">
                                    <h5 class="mb-0"><i class="fas fa-list"></i> Packing Cart</h5>
                                </div>
                                <div class="col-auto">
                                    <?php if (!empty($_SESSION['packing_cart'])) { ?>
                                        <form method="post" style="display: inline;">
                                            <button type="submit" name="clear_cart" class="btn btn-warning btn-sm" onclick="return confirm('Clear entire cart?');">
                                                <i class="fas fa-trash"></i> Clear Cart
                                            </button>
                                        </form>
                                    <?php } ?>
                                </div>
                            </div>
                        </div>
                        <div class="card-body p-2">
                            <?php if (empty($_SESSION['packing_cart'])) { ?>
                                <div class="text-center text-muted py-4">
                                    <i class="fas fa-shopping-cart fa-3x mb-3"></i>
                                    <h5>Cart is empty</h5>
                                    <p>Scan products to add them to the cart</p>
                                </div>
                            <?php } else { ?>
                                <div class="table-responsive">
                                    <table class="table table-bordered table-sm mb-0">
                                        <thead class="thead-light">
                                            <tr>
                                                <th>Barcode</th>
                                                <th>Product Name</th>
                                                <th>Room</th>
                                                <th>Project</th>
                                                <th>Qty</th>
                                                <th>Weight</th>
                                                <th>Available</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($_SESSION['packing_cart'] as $productId => $item) { ?>
                                                <tr class="cart-item">
                                                    <td data-label="Barcode"><?php echo htmlspecialchars($item['barcode']); ?></td>
                                                    <td data-label="Product Name"><?php echo htmlspecialchars($item['product_name']); ?></td>
                                                    <td data-label="Room"><?php echo htmlspecialchars($item['room_no']); ?></td>
                                                    <td data-label="Project"><?php echo htmlspecialchars($item['project_name']); ?></td>
                                                    <td data-label="Qty">
                                                        <form method="post" style="display: inline;">
                                                            <input type="hidden" name="product_id" value="<?php echo $productId; ?>">
                                                            <input type="number" name="new_qty" value="<?php echo $item['qty']; ?>" min="1" max="<?php echo $item['max_qty']; ?>" style="width: 60px;" onchange="this.form.submit();">
                                                            <input type="hidden" name="update_qty" value="1">
                                                        </form>
                                                    </td>
                                                    <td data-label="Weight"><?php echo number_format($item['weight'], 4); ?> kg</td>
                                                    <td data-label="Available"><?php echo $item['max_qty']; ?> qty / <?php echo number_format($item['max_weight'], 4); ?> kg</td>
                                                    <td data-label="Actions">
                                                        <a href="packing-module.php?remove_item=<?php echo $productId; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Remove this item from cart?');" title="Remove">
                                                            <i class="fas fa-trash"></i>
                                                        </a>
                                                    </td>
                                                </tr>
                                            <?php } ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php } ?>
                        </div>
                    </div>

                    <!-- Save Package -->
                    <?php if (!empty($_SESSION['packing_cart'])) { ?>
                    <div class="card shadow mb-4">
                        <div class="card-header bg-primary text-white text-center">
                            <h4 class="mb-0"><i class="fas fa-save"></i> Save Package</h4>
                        </div>
                        <div class="card-body text-center">
                            <form method="post" autocomplete="off">
                                <?php 
                                $firstItem = reset($_SESSION['packing_cart']);
                                $projectName = $firstItem['project_name'];
                                $projectName_escaped = mysqli_real_escape_string($con, $projectName);
                                $packageCountQuery = mysqli_query($con, "SELECT LastPackageNumber FROM tblpackagenumbers WHERE ProjectName='$projectName_escaped'");
                                $nextBundleNumber = 1;
                                if (mysqli_num_rows($packageCountQuery) > 0) {
                                    $row = mysqli_fetch_assoc($packageCountQuery);
                                    $nextBundleNumber = $row['LastPackageNumber'] + 1;
                                }
                                ?>
                                <p class="mb-3">Bundle will be saved as: <strong><?php echo htmlspecialchars($projectName); ?> - Bundle #<?php echo $nextBundleNumber; ?></strong></p>
                                <button type="submit" name="save_package" class="btn btn-success btn-lg">
                                    <i class="fas fa-save"></i> Save Bundle
                                </button>
                            </form>
                        </div>
                    </div>
                    <?php } ?>

                    <!-- Cart Summary -->
                    <div class="row mb-4">
                        <div class="col-md-12">
                            <div class="card shadow cart-summary">
                                <div class="card-body text-center">
                                    <h4><i class="fas fa-shopping-cart"></i> Packing Cart Summary</h4>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <h5>Total Items: <?php echo $totalItems; ?></h5>
                                        </div>
                                        <div class="col-md-6">
                                            <h5>Total Quantity: <?php echo $totalQty; ?></h5>
                                        </div>
                                        <div class="col-md-6">
                                            <h5>Total Weight: <?php echo number_format($totalWeight, 4); ?> kg</h5>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <a href="dashboard.php" class="btn btn-secondary btn-block">
                                <i class="fas fa-arrow-left"></i> Back to Dashboard
                            </a>
                        </div>
                        <div class="col-md-6">
                            <a href="packed-packages.php" class="btn btn-info btn-block">
                                <i class="fas fa-box"></i> View Packed Packages
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <?php include_once('includes/footer.php');?>
        </div>
    </div>
    <?php include_once('includes/footer2.php');?>
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>
    
    <script>
        // Auto-hide alert messages
        document.addEventListener('DOMContentLoaded', function() {
            const alertMsg = document.getElementById('alertMsg');
            if (alertMsg) {
                setTimeout(() => {
                    alertMsg.style.display = 'none';
                }, 2000);
            }
            
            const barcodeInput = document.querySelector('input[name="barcode"]');
            if (barcodeInput) {
                barcodeInput.focus();
            }
        });

        // Use html5-qrcode for QR and barcode scanning
        function startBarcodeScanner() {
            // Modal setup
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
                background: rgba(0,0,0,0.9); z-index: 9999; display: flex;
                align-items: center; justify-content: center; flex-direction: column;
            `;

            const content = document.createElement('div');
            content.style.cssText = `
                background: white; padding: 20px; border-radius: 10px;
                text-align: center; max-width: 90vw; max-height: 90vh;
            `;

            const title = document.createElement('h4');
            title.textContent = 'Scan QR Code or Barcode';
            title.style.marginBottom = '15px';

            const qrReaderDiv = document.createElement('div');
            qrReaderDiv.id = 'qr-reader';

            const controlsDiv = document.createElement('div');
            controlsDiv.style.cssText = 'margin-top: 15px;';

            const flashBtn = document.createElement('button');
            flashBtn.innerHTML = '<i class="fas fa-lightbulb"></i> Flash: ON';
            flashBtn.className = 'btn btn-warning mr-2';
            flashBtn.id = 'flashToggle';

            const closeBtn = document.createElement('button');
            closeBtn.innerHTML = '<i class="fas fa-times"></i> Close Scanner';
            closeBtn.className = 'btn btn-danger';

            controlsDiv.appendChild(flashBtn);
            controlsDiv.appendChild(closeBtn);

            content.appendChild(title);
            content.appendChild(qrReaderDiv);
            content.appendChild(controlsDiv);
            modal.appendChild(content);
            document.body.appendChild(modal);

            const html5QrCode = new Html5Qrcode("qr-reader");
            let isScanning = true;
            let isFlashOn = false;

            async function toggleFlash() {
                try {
                    if (html5QrCode.getState() === Html5QrcodeScannerState.SCANNING) {
                        if (isFlashOn) {
                            await html5QrCode.applyVideoConstraints({
                                advanced: [{ torch: false }]
                            });
                            flashBtn.innerHTML = '<i class="fas fa-lightbulb"></i> Flash: OFF';
                            flashBtn.className = 'btn btn-secondary mr-2';
                            isFlashOn = false;
                        } else {
                            await html5QrCode.applyVideoConstraints({
                                advanced: [{ torch: true }]
                            });
                            flashBtn.innerHTML = '<i class="fas fa-lightbulb"></i> Flash: ON';
                            flashBtn.className = 'btn btn-warning mr-2';
                            isFlashOn = true;
                        }
                    }
                } catch (err) {
                    console.log('Flash control not supported:', err);
                }
            }

            function stopScanner() {
                if (isScanning) {
                    isScanning = false; // Prevent re-entry
                    html5QrCode.stop().then(() => {
                        if (modal.parentNode) document.body.removeChild(modal);
                    }).catch(() => {
                        if (modal.parentNode) document.body.removeChild(modal);
                    });
                }
            }

            flashBtn.onclick = toggleFlash;
            closeBtn.onclick = stopScanner;
            modal.onclick = (e) => {
                if (e.target === modal) stopScanner();
            };

            const onScanSuccess = (decodedText, decodedResult) => {
                if (!isScanning) return;
                
                // Set value in barcode input
                document.getElementById('barcodeInput').value = decodedText;
                
                // Find the submit button
                const submitButton = document.querySelector('button[name="scan_product"]');
                
                // Stop the scanner
                stopScanner();
                
                // Click the button to submit the form, which includes the button's name/value
                if (submitButton) {
                    submitButton.click();
                }
            };

            html5QrCode.start(
                { facingMode: "environment" },
                {
                    fps: 10,
                    qrbox: 250,
                    formatsToSupport: [
                        Html5QrcodeSupportedFormats.QR_CODE,
                        Html5QrcodeSupportedFormats.CODE_128,
                        Html5QrcodeSupportedFormats.EAN_13,
                        Html5QrcodeSupportedFormats.EAN_8,
                        Html5QrcodeSupportedFormats.UPC_A,
                        Html5QrcodeSupportedFormats.UPC_E,
                        Html5QrcodeSupportedFormats.CODE_39,
                        Html5QrcodeSupportedFormats.CODE_93,
                        Html5QrcodeSupportedFormats.CODABAR
                    ]
                },
                onScanSuccess,
                (errorMessage) => {
                    // ignore scan errors, keep frame open
                }
            ).then(() => {
                // Automatically turn on flashlight when camera starts
                setTimeout(async () => {
                    try {
                        await html5QrCode.applyVideoConstraints({
                            advanced: [{ torch: true }]
                        });
                        flashBtn.innerHTML = '<i class="fas fa-lightbulb"></i> Flash: ON';
                        flashBtn.className = 'btn btn-warning mr-2';
                        isFlashOn = true;
                    } catch (err) {
                        console.log('Auto-flash not supported:', err);
                        flashBtn.style.display = 'none'; // Hide button if flash not supported
                    }
                }, 1000); // Wait 1 second for camera to initialize
            }).catch(err => {
                alert('Camera initialization failed: ' + err);
                stopScanner();
            });
        }
    </script>
</body>
</html>
</html>
