<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../vendor/autoload.php';

session_start();

require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/SystemSettings.php';
require_once __DIR__ . '/../../classes/Inventory.php';
require_once __DIR__ . '/../../classes/Shipment.php';
require_once __DIR__ . '/../../classes/Logger.php';
//require_once __DIR__ . '/../../classes/Category.php';


$db = new Database();
$conn = $db->getConnection();
$systemSettings = new SystemSettings();
$vatPercentage = $systemSettings->vatPercentage();
$vatRate = $systemSettings->vatRate();
$profitPercentageDefault = $systemSettings->profitPercentage();


$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);

$inventory = new Inventory($conn, $logger);


if (!isset($_SESSION['user_id'])) {
    die("You are not logged in. Please <a href='/path/to/login.php'>log in</a> to continue.");
}


if ($_SESSION['role'] != 'admin' && $_SESSION['role'] != 'warehouse') {
    header('Location: /IMS/unauthorized.php');
    exit;
}


$stmt = $conn->prepare("SELECT branch_id FROM branches WHERE branch_name LIKE '%warehouse%' LIMIT 1");
$stmt->execute();
$branch_id = $stmt->fetchColumn();

if (!$branch_id) {

    $branch_id = 7;
}


$stmt = $conn->prepare("SELECT branch_name FROM branches WHERE branch_id = ?");
$stmt->execute([$branch_id]);
$branch_name = $stmt->fetchColumn();
if (!$branch_name) {
    die("Warehouse branch not found in the system.");
}


if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['generate'])) {
    $itemName = trim($_POST['item_name'] ?? '');
    $codeMethod = trim($_POST['code_method'] ?? '');
    $category = trim($_POST['category'] ?? '');
    $preCode = trim($_POST['pre_code'] ?? '');
    $quantity = filter_input(INPUT_POST, 'quantity', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 1000]]);
    $conditionStatus = trim($_POST['condition_status'] ?? '');
    $landingPrice = filter_input(INPUT_POST, 'landing_price', FILTER_VALIDATE_FLOAT);
    $profitPercentage = filter_input(INPUT_POST, 'profit_percentage', FILTER_VALIDATE_FLOAT);


    if (empty($itemName)) die("Item name is required.");
    if (empty($codeMethod) || !in_array($codeMethod, ['auto', 'manual'])) die("Invalid code method.");
    if ($codeMethod === 'auto' && empty($preCode)) die("Pre-Universal Code is required for auto-generation.");
    if ($quantity === false) die("Invalid quantity (1-1000).");
    if (empty($conditionStatus)) die("Condition status is required.");
    if ($landingPrice === false || $landingPrice <= 0) die("Invalid landing price. Must be greater than 0.");
    if ($profitPercentage === false || $profitPercentage < 0) die("Invalid profit percentage. Must be 0 or greater.");


    $profitAmount = $landingPrice * ($profitPercentage / 100);
    $subtotal = $landingPrice + $profitAmount;
    $vatAmount = $subtotal * $vatRate;
    $unitPrice = round($subtotal + $vatAmount, 2);

    if ($codeMethod === 'auto') {
        $generatedCodes = $inventory->generateUniqueCodes($preCode, $quantity);
        if ($generatedCodes === false) die("Failed to generate unique codes.");
        $uniqueCodes = $generatedCodes;
    } else {
        $generatedCodes = [];
        $uniqueCodes = [];
    }
    $showDetailsForm = true;
}


elseif ($_SERVER["REQUEST_METHOD"] == "POST" && (isset($_POST['save']) || isset($_POST['print_save']))) {
    $itemName = trim($_POST['item_name'] ?? '');
    $category = trim($_POST['category'] ?? '');
    $codeMethod = trim($_POST['code_method'] ?? '');
    $uniqueCodes = array_map('trim', $_POST['unique_codes'] ?? []);
    $unitPrice = filter_input(INPUT_POST, 'unit_price', FILTER_VALIDATE_FLOAT);
    $quantity = filter_input(INPUT_POST, 'quantity', FILTER_VALIDATE_INT);
    $conditionStatus = trim($_POST['condition_status'] ?? '');


    if (empty($itemName) || $quantity === false || empty($codeMethod) || $unitPrice === false) {
        die("Missing required data.");
    }
    if (empty($conditionStatus)) die("Condition status is required.");

    if ($codeMethod === 'manual') {
        if (count($uniqueCodes) !== $quantity) die("Number of unique codes must match quantity.");
        if (in_array('', $uniqueCodes)) die("All unique codes must be provided.");
        if (count(array_unique($uniqueCodes)) !== count($uniqueCodes)) die("Duplicate codes detected.");


        $stmt = $conn->prepare("SELECT unique_code FROM items WHERE unique_code IN (" . implode(',', array_fill(0, count($uniqueCodes), '?')) . ")");
        $stmt->execute($uniqueCodes);
        $existingCodes = $stmt->fetchAll(PDO::FETCH_COLUMN);
        if (!empty($existingCodes)) die("Codes already exist: " . implode(', ', $existingCodes));
    }


    $items = [];
    for ($i = 0; $i < $quantity; $i++) {
        $items[] = [
            'unique_code' => $uniqueCodes[$i],
            'item_name' => $itemName,
            'category' => $category,
            'condition_status' => $conditionStatus,
            'unit_price' => $unitPrice,
        ];
    }

    
    $createdBy = $_SESSION['user_id'];
    try {

        $success = $inventory->addItemsToWarehouse($items, $createdBy, $branch_id);

        if (!$success) {
            throw new Exception("Failed to add items to warehouse: " . $inventory->getLastError());
        }


        $newlyAddedItems = [];
        if (!empty($uniqueCodes)) {
            $placeholders = implode(',', array_fill(0, count($uniqueCodes), '?'));
            $stmt = $conn->prepare("SELECT unique_code, barcode_image_path FROM items WHERE unique_code IN ($placeholders) ORDER BY item_id DESC");
            $stmt->execute($uniqueCodes);
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);


            foreach ($results as $row) {
                $newlyAddedItems[$row['unique_code']] = $row['barcode_image_path'];
            }

            error_log("Fetched barcode paths for " . count($newlyAddedItems) . " items: " . json_encode($newlyAddedItems));
        }


        if (isset($_POST['print_save']) && !empty($_POST['print_save'])) {
            $printNow = true;
        } else {
            $saved = true;
        }
    } catch (Exception $e) {

        error_log("Warehouse inventory addition error in warehouse_simple.php: " . $e->getMessage());
        die("Error saving data: " . $e->getMessage());
    }
}
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
<link rel="stylesheet" href="../../assets/css/simple.css">
    <style>
        .validation-message {
            margin-top: 5px;
            font-size: 0.9em;
        }
        input.error {
            border-color: red !important;
        }
        input.valid {
            border-color: green !important;
        }
        .back-link {
            display: inline-block;
            margin: 15px;
            padding: 10px 15px;
            background-color: #3498db;
            color: white;
            text-decoration: none;
            border-radius: 5px;
            transition: background-color 0.3s ease;
        }
        .back-link:hover {
            background-color: #2980b9;
            color: white;
        }
        .price-calculation {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            padding: 15px;
            border-radius: 5px;
            margin: 15px 0;
        }
        .price-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 10px 0;
            padding: 8px;
            background-color: #e9ecef;
            border-radius: 3px;
        }
        .price-info strong {
            color: #495057;
        }
        .calculated-price {
            font-size: 1.1em;
            font-weight: bold;
            color: #28a745;
        }
        .note {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .success-message {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }


        .print-preview {
            background-color: #f8f9fa;
            border: 2px solid #007bff;
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
        }

        .preview-header {
            text-align: center;
            background-color: #007bff;
            color: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .sticker-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 10px;
            margin: 20px 0;
        }

        .sticker-preview {
            border: 1px solid #6c757d;
            padding: 8px;
            text-align: center;
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            min-height: 80px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }

        .sticker-preview img {
            max-width: 100%;
            height: 25px;
            object-fit: contain;
            margin-bottom: 5px;
        }

        .sticker-code {
            font-weight: bold;
            font-size: 10px;
            color: #333;
            margin-top: 3px;
            word-break: break-all;
        }

        .print-controls {
            text-align: center;
            margin: 20px 0;
        }

        .print-controls button {
            background-color: #28a745;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
            margin: 0 10px;
        }

        .print-controls button:hover {
            background-color: #218838;
        }

        .print-controls .btn-secondary {
            background-color: #6c757d;
        }

        .print-controls .btn-secondary:hover {
            background-color: #5a6268;
        }

        .barcode-error {
            background-color: #f8d7da;
            color: #721c24;
            padding: 5px;
            border-radius: 3px;
            margin: 2px 0;
            font-size: 8px;
            border: 1px solid #f5c6cb;
        }

        @media print {
            body * {
                visibility: hidden;
            }
            .printable-area, .printable-area * {
                visibility: visible;
            }
            .printable-area {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
            }
            .sticker-grid {
                display: grid;
                grid-template-columns: repeat(6, 1fr);
                gap: 3mm;
                padding: 5mm;
            }
            .sticker-preview {
                border: 1px solid #000;
                padding: 2mm;
                page-break-inside: avoid;
                width: 25mm;
                height: 15mm;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                font-size: 8pt;
            }
            .sticker-preview img {
                max-width: 20mm;
                height: 8mm;
                margin-bottom: 1mm;
            }
            .sticker-code {
                font-size: 6pt;
                font-weight: bold;
                margin-top: 1mm;
            }
            .print-controls, .preview-header {
                display: none;
            }
            .barcode-error {
                display: none;
            }
        }
    </style>
    <script>
        const vatRate = <?php echo json_encode($vatRate); ?>;
document.addEventListener('DOMContentLoaded', () => {
            togglePreCode();
            toggleCategory();
            setupPriceCalculation();
            setupUniqueCodeValidation();


            const printButton = document.querySelector('button[onclick="printLabels()"]');
            if (printButton) {
                printButton.focus();
                console.log('Print preview ready. All barcodes should be visible.');
            }
        });

        function togglePreCode() {
            const method = document.getElementById('code_method').value;
            const preCodeGroup = document.getElementById('pre_code_group');
            preCodeGroup.style.display = method === 'auto' ? 'block' : 'none';
            document.getElementById('pre_code').required = method === 'auto';
        }
        function toggleCategory() {
            const category = document.getElementById('category').value;
        }

        function setupPriceCalculation() {
            const landingPriceInput = document.getElementById('landing_price');
            const profitPercentageInput = document.getElementById('profit_percentage');
            const calculationSection = document.getElementById('price_calculation_section');

            if (landingPriceInput && profitPercentageInput) {
                function calculatePrice() {
                    const landingPrice = parseFloat(landingPriceInput.value) || 0;
                    const profitPercentage = parseFloat(profitPercentageInput.value) || 0;

                    if (landingPrice > 0) {
                        const profitAmount = landingPrice * (profitPercentage / 100);
                        const subtotal = landingPrice + profitAmount;
                        const vatAmount = subtotal * vatRate;
                        const unitPrice = Math.round((subtotal + vatAmount) * 100) / 100;

                        if (calculationSection) {
                            calculationSection.style.display = 'block';
                            document.getElementById('display_landing_price').textContent = landingPrice.toFixed(2);
                            document.getElementById('display_profit_percentage').textContent = profitPercentage.toFixed(1) + '%';
                            document.getElementById('display_profit_amount').textContent = profitAmount.toFixed(2);
                            document.getElementById('display_subtotal').textContent = subtotal.toFixed(2);
                            document.getElementById('display_vat_amount').textContent = vatAmount.toFixed(2);
                            document.getElementById('display_unit_price').textContent = unitPrice.toFixed(2);
                        }
                    } else {
                        if (calculationSection) {
                            calculationSection.style.display = 'none';
                        }
                    }
                }

                landingPriceInput.addEventListener('input', calculatePrice);
                profitPercentageInput.addEventListener('input', calculatePrice);


                calculatePrice();
            }
        }

        function printLabels() {
            window.print();
        }

        function printSaveAndCodes() {

            document.getElementById('print_save_flag').value = 'true';
            document.getElementById('inventory_form').submit();
        }


        async function validateUniqueCode(uniqueCode) {
            try {
                const response = await fetch('../../api/inventory/validate-unique-code.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        unique_code: uniqueCode
                    })
                });

                const data = await response.json();
                return data;
            } catch (error) {
                console.error('Error validating unique code:', error);
                return { success: false, message: 'Error validating code. Please try again.' };
            }
        }


        function setupUniqueCodeValidation() {
            const codeMethod = document.getElementById('code_method')?.value;

            if (codeMethod === 'manual' || document.querySelector('input[name="unique_codes[]"]')) {
                const uniqueCodeInputs = document.querySelectorAll('input[name="unique_codes[]"]');

                uniqueCodeInputs.forEach(input => {
                    input.removeEventListener('blur', handleUniqueCodeValidation);
                    input.addEventListener('blur', handleUniqueCodeValidation);
                });
            }
        }

        async function handleUniqueCodeValidation(event) {
            const input = event.target;
            const uniqueCode = input.value.trim();

            if (!uniqueCode) return;

            const existingMessage = input.parentNode.querySelector('.validation-message');
            if (existingMessage) {
                existingMessage.remove();
            }

            input.style.borderColor = '';

            const result = await validateUniqueCode(uniqueCode);

            const messageElement = document.createElement('div');
            messageElement.className = 'validation-message';

            if (!result.success && result.exists) {
                messageElement.textContent = result.message;
                messageElement.style.color = 'red';
                input.style.borderColor = 'red';
            } else if (result.success) {
                messageElement.textContent = result.message;
                messageElement.style.color = 'green';
                input.style.borderColor = 'green';
            } else {
                messageElement.textContent = result.message;
                messageElement.style.color = 'orange';
            }

            input.parentNode.appendChild(messageElement);
        }
    </script>

    <a href="choose_warehouse_form.php" class="back-link">← Back to Form Selection</a>

    <h2>Add Simple Items to Warehouse: <?php echo htmlspecialchars($branch_name); ?></h2>

    <?php if (!isset($showDetailsForm) && !isset($saved) && !isset($printNow)) { ?>
        <div class="note">
            <strong>Note:</strong> This form is specifically designed for adding simple items to the warehouse inventory. Simple items are basic products that do not require:
            <ul>
                <li>Warranty information</li>
                <li>Serial numbers</li>
                <li>Technical specifications</li>
                <li>Detailed product attributes</li>
            </ul>
            Examples: cables, adapters, basic accessories, consumables, etc.
        </div>

        <form method="post" action="">
            <input type="hidden" name="branch_id" value="<?php echo $branch_id; ?>">

            <div class="form-group">
                <label for="item_name">Item Name:</label>
                <input type="text" name="item_name" id="item_name" required
                       placeholder="Enter simple item name (e.g., USB Cable, Power Adapter)">
            </div>

           <div class="form-group">
                <label for="category">Category: <a href="add_category_form.php"> + </a></label>
                <select name="category" id="category" required onchange="toggleCategory()">
				 <?php
                    $branchObj = new Inventory($conn);
                    $branches = $branchObj->getAllCategories();
                    while ($branch = $branches->fetch(PDO::FETCH_ASSOC)) {
                        echo '<option value="' . htmlspecialchars($branch['category_name']) . '">' .
                             htmlspecialchars($branch['category_name']) . '</option>';
                    }
                    ?>

				    </select>
            </div>

            <div class="form-group">
                <label for="code_method">Code Assignment Method:</label>
                <select name="code_method" id="code_method" required onchange="togglePreCode()">
                    <option value="auto">Auto-generate codes</option>
                    <option value="manual">Enter codes manually</option>
                </select>
            </div>

            <div class="form-group" id="pre_code_group" style="display: none;">
                <label for="pre_code">Pre-Universal Code:</label>
                <input type="text" name="pre_code" id="pre_code" placeholder="e.g., CBL/ for cables, PWR/ for power items">
                <small>This prefix will be used to generate unique codes automatically</small>
            </div>

            <div class="form-group">
                <label for="quantity">Quantity:</label>
                <input type="number" name="quantity" id="quantity" required min="1" max="1000"
                       placeholder="Number of items to add">
            </div>

            <div class="form-group">
                <label for="condition_status">Condition Status:</label>
                <select name="condition_status" id="condition_status" required>
                    <option value="">Select Condition</option>
                    <option value="NEW">NEW</option>
                    <option value="OPEN_BOX">OPEN_BOX</option>
                    <option value="USED">USED</option>
                </select>
            </div>

            <div class="form-group">
                <label for="landing_price">Landing Price (Cost Price):</label>
                <input type="number" step="0.01" name="landing_price" id="landing_price" required min="0.01"
                       placeholder="Enter the cost price per item">

            </div>

            <div class="form-group">
                <label for="profit_percentage">Profit Percentage (%):</label>
                <input type="number" step="0.1" name="profit_percentage" id="profit_percentage"
                       value="20" min="0" max="1000"
                       placeholder="Enter profit percentage">

            </div>

            <div id="price_calculation_section" class="price-calculation" style="display: none;">
                <h4>Price Calculation Preview:</h4>
                <div class="price-info">
                    <span>Landing Price (Cost):</span>
                    <strong>MWK<span id="display_landing_price">0.00</span></strong>
                </div>
                <div class="price-info">
                    <span>Profit Percentage:</span>
                    <strong><span id="display_profit_percentage">0.0%</span></strong>
                </div>
                <div class="price-info">
                    <span>Profit Amount:</span>
                    <strong>MWK<span id="display_profit_amount">0.00</span></strong>
                </div>
                <div class="price-info">
                    <span>Subtotal (Cost + Profit):</span>
                    <strong>MWK<span id="display_subtotal">0.00</span></strong>
                </div>
                <div class="price-info">
                    <span>VAT (<?php echo htmlspecialchars(number_format($vatPercentage, 2)); ?>%):</span>
                    <strong>MWK<span id="display_vat_amount">0.00</span></strong>
                </div>
                <div class="price-info">
                    <span>Selling Price (Unit Price):</span>
                    <strong class="calculated-price">MWK<span id="display_unit_price">0.00</span></strong>
                </div>
            </div>

            <input type="submit" name="generate" value="Continue to Review">
        </form>

    <?php } elseif (isset($showDetailsForm)) { ?>
        <h3>Review and Confirm Simple Items</h3>
        <p><strong>Item:</strong> <?php echo htmlspecialchars($itemName); ?></p>
        <p><strong>Quantity:</strong> <?php echo $quantity; ?> items</p>
        <p><strong>Warehouse:</strong> <?php echo htmlspecialchars($branch_name); ?></p>

        <div class="price-calculation">
            <h4>Pricing Information:</h4>
            <div class="price-info">
                <span>Landing Price (Cost):</span>
                <strong>MWK<?php echo number_format($landingPrice, 2); ?></strong>
            </div>
            <div class="price-info">
                <span>Profit Percentage:</span>
                <strong><?php echo number_format($profitPercentage, 1); ?>%</strong>
            </div>
            <div class="price-info">
                <span>Profit Amount:</span>
                <strong>MWK<?php echo number_format($profitAmount, 2); ?></strong>
            </div>
            <div class="price-info">
                <span>Subtotal (Cost + Profit):</span>
                <strong>MWK<?php echo number_format($subtotal, 2); ?></strong>
            </div>
            <div class="price-info">
                <span>VAT (<?php echo htmlspecialchars(number_format($vatPercentage, 2)); ?>%):</span>
                <strong>MWK<?php echo number_format($vatAmount, 2); ?></strong>
            </div>
            <div class="price-info">
                <span>Selling Price (Unit Price):</span>
                <strong class="calculated-price">MWK<?php echo number_format($unitPrice, 2); ?></strong>
            </div>
            <div class="price-info">
                <span>Total Value (<?php echo $quantity; ?> items):</span>
                <strong class="calculated-price">MWK<?php echo number_format($unitPrice * $quantity, 2); ?></strong>
            </div>
        </div>

        <form method="post" action="" id="inventory_form">
            <input type="hidden" name="branch_id" value="<?php echo $branch_id; ?>">
            <input type="hidden" name="item_name" value="<?php echo htmlspecialchars($itemName); ?>">
            <input type="hidden" name="category" value="<?php echo htmlspecialchars($category); ?>">
            <input type="hidden" name="code_method" value="<?php echo htmlspecialchars($codeMethod); ?>">
            <input type="hidden" name="quantity" value="<?php echo htmlspecialchars($quantity); ?>">
            <input type="hidden" name="condition_status" value="<?php echo htmlspecialchars($conditionStatus); ?>">
            <input type="hidden" name="unit_price" value="<?php echo htmlspecialchars($unitPrice); ?>">
            <input type="hidden" name="print_save" id="print_save_flag" value="">

            <table>
                <thead>
                    <tr>
                        <th>Item #</th>
                        <th>Unique Code</th>
                        <th>Condition</th>
                        <th>Unit Price</th>
                    </tr>
                </thead>
                <tbody>
                    <?php for ($i = 0; $i < $quantity; $i++) { ?>
                        <tr>
                            <td><?php echo $i + 1; ?></td>
                            <td>
                                <?php if ($codeMethod === 'auto') { ?>
                                    <input type="hidden" name="unique_codes[]" value="<?php echo htmlspecialchars($uniqueCodes[$i]); ?>">
                                    <strong><?php echo htmlspecialchars($uniqueCodes[$i]); ?></strong>
                                <?php } else { ?>
                                    <input type="text" name="unique_codes[]" required placeholder="Enter unique code">
                                    <div class="validation-message"></div>
                                <?php } ?>
                            </td>
                            <td><?php echo htmlspecialchars($conditionStatus); ?></td>
                            <td>MWK<?php echo number_format($unitPrice, 2); ?></td>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>

            <div style="margin-top: 20px;">
                <input type="submit" name="save" value="Save Items to Warehouse" style="background-color: #28a745; color: white; padding: 10px 20px; border: none; border-radius: 5px; margin-right: 10px;">
                <button type="submit" name="print_save" value="true" style="background-color: #17a2b8; color: white; padding: 10px 20px; border: none; border-radius: 5px;">Save & Print Labels</button>
            </div>
        </form>

    <?php } elseif (isset($saved)) { ?>
        <div class="success-message">
            <h3>✅ Success!</h3>
            <p><strong><?php echo $quantity; ?> simple items</strong> have been successfully added to the warehouse inventory.</p>
            <p><strong>Total Value:</strong> MWK<?php echo number_format($unitPrice * $quantity, 2); ?></p>
            <p>All barcodes have been generated and items are now available in the system.</p>
        </div>

        <div style="text-align: center; margin: 20px 0;">
            <a href="choose_warehouse_form.php" class="back-link">← Add More Items</a>
            <a href="../../inventory/view_inventory.php" class="back-link" style="background-color: #28a745;">View Inventory</a>
        </div>

    <?php } elseif (isset($printNow)) { ?>
        <div class="print-preview">
            <div class="preview-header">
                <h2>🏷️ Item Labels Preview</h2>
                <p><?php echo $quantity; ?> simple items have been added to the warehouse inventory.</p>
                <p><strong>Total Value:</strong> MWK<?php echo number_format($unitPrice * $quantity, 2); ?></p>
            </div>

            <div class="print-controls">
                <button onclick="printLabels()" title="Print all labels for items">
                    🖨️ Print All Labels
                </button>
                <button onclick="window.location.href='choose_warehouse_form.php'" class="btn-secondary">
                    ← Back to Form Selection
                </button>
            </div>

            <div class="printable-area">
                <div class="sticker-grid">
                    <?php
                    $counter = 1;
                    $barcode_errors = 0;
                    $barcode_success = 0;

                    foreach ($uniqueCodes as $code) {
                        ?>
                        <div class="sticker-preview">
                            <?php

                            if (isset($newlyAddedItems[$code]) && !empty($newlyAddedItems[$code])) {

                                $barcodePath = '/IMS/' . $newlyAddedItems[$code];


                                $fullServerPath = $_SERVER['DOCUMENT_ROOT'] . $barcodePath;

                                if (file_exists($fullServerPath)) {
                                    $barcode_success++;
                                    ?>
                                    <img src="<?php echo htmlspecialchars($barcodePath); ?>"
                                         alt="Barcode for <?php echo htmlspecialchars($code); ?>"
                                         onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">
                                    <div style="display: none; color: red; font-size: 8px;">
                                        No Barcode
                                    </div>
                                    <?php
                                } else {
                                    $barcode_errors++;
                                    ?>
                                    <div class="barcode-error">File Missing</div>
                                    <?php
                                }
                            } else {
                                $barcode_errors++;
                                ?>
                                <div class="barcode-error">No Barcode</div>
                                <?php
                            }
                            ?>

                            <div class="sticker-code"><?php echo htmlspecialchars($code); ?></div>
                        </div>
                        <?php
                        $counter++;
                    } ?>
                </div>
            </div>

            <?php

            if ($barcode_errors > 0 || $barcode_success > 0) { ?>
                <div style="background-color: #f8f9fa; border: 1px solid #dee2e6; padding: 15px; border-radius: 5px; margin: 20px 0;">
                    <h4>Barcode Generation Summary:</h4>
                    <div style="display: flex; justify-content: space-around; text-align: center;">
                        <div style="color: #28a745;">
                            <strong><?php echo $barcode_success; ?></strong><br>
                            <small>Successful</small>
                        </div>
                        <div style="color: #dc3545;">
                            <strong><?php echo $barcode_errors; ?></strong><br>
                            <small>Errors</small>
                        </div>
                        <div style="color: #6c757d;">
                            <strong><?php echo count($uniqueCodes); ?></strong><br>
                            <small>Total Items</small>
                        </div>
                    </div>
                    <?php if ($barcode_errors > 0) { ?>
                        <div style="margin-top: 15px; padding: 10px; background-color: #fff3cd; border: 1px solid #ffeaa7; border-radius: 5px;">
                            <strong>⚠️ Note:</strong> Some barcodes could not be displayed, but all items have been saved to the database successfully.
                            The barcode generation process may take a moment. You can refresh this page in a few seconds to see updated results.
                        </div>
                    <?php } ?>
                </div>
            <?php } ?>

            <div style="text-align: center; margin: 30px 0;">
                <a href="choose_warehouse_form.php" class="back-link">← Add More Items</a>
                <a href="../../inventory/view_inventory.php" class="back-link" style="background-color: #28a745;">View Inventory</a>
            </div>
        </div>

    <?php } ?>
<?php include __DIR__ . '/../../includes/footer.php'; ?>