<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../classes/Shipment.php';
require_once __DIR__ . '/../../classes/MraEisCompliance.php';

$database = new Database();
$conn = $database->getConnection();

$auth = new Auth($conn);
if (!isset($_SESSION['user_id'])) {
    header('Location: /IMS/login.php');
    exit();
}

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


$destination_branch_id = filter_input(INPUT_GET, 'branch_id', FILTER_VALIDATE_INT);
if (!$destination_branch_id) {
    die("Invalid destination branch ID.");
}


$mode = filter_input(INPUT_GET, 'mode', FILTER_SANITIZE_STRING) ?: 'manual';

$branch = new Branch($conn);
$destination_branch = $branch->getBranchById($destination_branch_id);
if (!$destination_branch) { die("Destination branch not found."); }
$destination_branch_name = $destination_branch['branch_name'];


$source_branch_id = ($_SESSION['role'] == 'admin') ? 7 : $auth->getUserBranch($_SESSION['user_id']);
if (!$source_branch_id) { die("Error: Your account is not assigned to a branch."); }

$source_branch = $branch->getBranchById($source_branch_id);
if (!$source_branch) { die("Source branch details could not be found."); }
$source_branch_name = $source_branch['branch_name'];

if ($destination_branch_id == $source_branch_id) { die("Cannot ship items from a branch to itself."); }


$success_message = $_SESSION['success'] ?? '';
$error_message = $_SESSION['error'] ?? '';
unset($_SESSION['success'], $_SESSION['error']);

$last_shipment_id = $_SESSION['last_shipment_id'] ?? null;
unset($_SESSION['last_shipment_id']);

$last_shipment = null;
$last_shipment_can_undo = false;
if ($last_shipment_id) {
    $shipmentModel = new Shipment($conn);
    $last_shipment = $shipmentModel->getShipmentById($last_shipment_id);
    if ($last_shipment && $last_shipment['status'] === 'pending') {
        $eisCompliance = new MraEisCompliance($conn);
        $last_shipment_can_undo = !$eisCompliance->transferAlreadySubmitted($last_shipment_id);
    }
}

$transfer_receipt_shipment_id = $_SESSION['transfer_receipt_shipment_id'] ?? null;
unset($_SESSION['transfer_receipt_shipment_id']);

$transfer_receipt_summary = null;
if ($transfer_receipt_shipment_id) {
    $eisCompliance = $eisCompliance ?? new MraEisCompliance($conn);
    $transfer_receipt_summary = $eisCompliance->transferReceiptSummary($transfer_receipt_shipment_id);
}
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
<style>

        body { background-color: #f8f9fa; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .container { max-width: 1200px; padding: 20px; }
        .card { margin-top: 20px; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); border: none; }
        .card-header { background-color: #f8f9fa; border-bottom: 1px solid rgba(0,0,0,0.125); padding: 15px 20px; border-radius: 10px 10px 0 0 !important; }
        .table thead th { background-color: #f1f5f9; }
        .back-link { display: inline-block; margin: 15px 0; padding: 10px 15px; background-color: #6c757d; color: white; text-decoration: none; border-radius: 5px; }
        .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
        .badge { font-size: 85%; font-weight: 500; padding: 5px 10px; border-radius: 30px; }
        .bottom-action-bar { position: sticky; bottom: 0; background-color: #ffffff; padding: 15px 20px; border-top: 1px solid #dee2e6; box-shadow: 0 -2px 10px rgba(0,0,0,0.1); z-index: 1000; text-align: center; }
        .shipment-summary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 10px; margin-bottom: 20px; }
        .modal-xl { max-width: 1140px; }
        .filter-container { background-color: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .sr-only { display: none; }
        .shipment-group-panel { background: #f8fafc; border: 1px solid #d7dee8; border-radius: 8px; margin: 8px 12px; padding: 12px; overflow-x: auto; }
        .shipment-group-toggle { border-radius: 50%; height: 34px; padding: 0; width: 34px; }
    </style>

    <div class="container">
        <div class="page-header">
            <a href="add_items_dashboard2.php" class="back-link"><i class="fas fa-arrow-left"></i> Back to Branch Selection</a>
            <div>
                <h4><span class="badge bg-secondary me-2">Source: <?php echo htmlspecialchars($source_branch_name); ?></span></h4>
                <h4><span class="badge bg-info">Destination: <?php echo htmlspecialchars($destination_branch_name); ?></span></h4>
            </div>
        </div>

        <h2 class="text-center mb-3">Create Shipment: <?php echo htmlspecialchars($source_branch_name); ?> <i class="fas fa-arrow-right mx-2"></i> <?php echo htmlspecialchars($destination_branch_name); ?></h2>

        <?php if ($success_message): ?>
            <div class="alert alert-success d-flex justify-content-between align-items-center flex-wrap gap-2" role="alert">
                <span><i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($success_message); ?></span>
                <?php if ($last_shipment): ?>
                    <div class="d-flex gap-2">
                        <a href="../shipments/view_shipment.php?id=<?php echo (int)$last_shipment_id; ?>" class="btn btn-sm btn-outline-primary">
                            <i class="fas fa-eye me-1"></i>View Transfer
                        </a>
                        <?php if ($last_shipment_can_undo): ?>
                            <form action="../shipments/delete_pending_shipment.php" method="POST" class="d-inline" onsubmit="return confirm('Undo this transfer and return its items to <?php echo htmlspecialchars(addslashes($source_branch_name)); ?>?');">
                                <input type="hidden" name="shipment_id" value="<?php echo (int)$last_shipment_id; ?>">
                                <input type="hidden" name="redirect_to" value="../inventory/ship_items_form.php?branch_id=<?php echo (int)$destination_branch_id; ?>&mode=<?php echo urlencode($mode); ?>">
                                <button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-undo me-1"></i>Undo Transfer</button>
                            </form>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
        <?php if ($error_message): ?>
            <div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle me-2"></i><?php echo htmlspecialchars($error_message); ?></div>
        <?php endif; ?>

        <form action="process_shipment.php" method="POST" id="shipmentForm">
            <input type="hidden" name="destination_branch_id" value="<?php echo $destination_branch_id; ?>">
            <input type="hidden" name="source_branch_id" value="<?php echo $source_branch_id; ?>">
            <input type="hidden" name="mode" value="<?php echo htmlspecialchars($mode); ?>">

            <div id="manual-selection-mode" <?php if ($mode !== 'manual') echo 'style="display:none;"'; ?>>
                <div class="card mt-3">
                    <div class="card-body">
                        <div class="row align-items-end g-2">
                            <div class="col-md-7">
                                <label for="shipmentExcelFile" class="form-label"><strong>Import Excel Transfer</strong></label>
                                <input type="file" id="shipmentExcelFile" class="form-control" accept=".xlsx,.xls,.csv">
                                <div class="form-text">The file must contain only <strong>unique_code</strong> and <strong>selling_price</strong>.</div>
                            </div>
                            <div class="col-md-5 d-flex gap-2">
                                <a href="download_shipment_transfer_template.php" class="btn btn-outline-success w-100">
                                    <i class="fas fa-file-excel me-1"></i>Template
                                </a>
                                <button type="button" id="importShipmentExcelBtn" class="btn btn-success w-100">
                                    <i class="fas fa-file-import me-1"></i>Import
                                </button>
                            </div>
                        </div>
                        <div id="shipmentExcelResult" class="mt-2"></div>
                    </div>
                </div>
                <div class="filter-container mb-3 mt-3">
                    <div class="row align-items-end">
                        <div class="col-md-10"><label for="filterSearch">Live Product Search</label><input type="search" id="filterSearch" class="form-control" autocomplete="off" placeholder="Search by product name, product code, unique ID, or serial number..."></div>
                        <div class="col-md-2"><button type="button" id="clearFilters" class="btn btn-secondary w-100" title="Clear Filters"><i class="fas fa-times"></i> Clear</button></div>
                    </div>
                </div>
                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="manualItemsTable" class="table table-bordered table-hover w-100">
                                <thead>
                                    <tr>
                                        <th class="text-center">Details</th>
                                        <th>Item Name</th><th>Item Details</th><th>Available Qty</th><th>Price Range</th>
                                        <th>Category</th><th>Condition</th><th>Specs</th>
                                    </tr>
                                </thead>
                                <tbody id="inventoryTableBody"></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div id="scanner-mode" <?php if ($mode !== 'scanner') echo 'style="display:none;"'; ?>>
                <div class="card"><div class="card-body"><div class="form-group"><label for="barcodeInput"><strong>Scan Barcode Here:</strong></label><div class="input-group"><div class="input-group-prepend"><span class="input-group-text"><i class="fas fa-barcode"></i></span></div><input type="text" id="barcodeInput" class="form-control form-control-lg" placeholder="Scanner is ready..." autofocus></div><div id="scanFeedback" class="mt-2"></div></div></div></div>
                <div class="card mt-4"><div class="card-header"><h5 class="mb-0">Scanned Items (<span id="scannedItemCount">0</span>)</h5></div><div class="card-body"><div class="table-responsive"><table class="table table-bordered table-hover"><thead><tr><th>Item Name</th><th>Item Details</th><th>Unique ID</th><th>Condition</th><th>Serial No.</th><th>Selling Price</th><th class="text-center">Action</th></tr></thead><tbody id="scannedItemsTableBody"></tbody></table></div></div></div>
            </div>

            <div id="manualSelectedInputs" style="display:none;"></div>

            <div class="bottom-action-bar">
                <button type="button" class="btn btn-primary btn-lg" id="previewShipmentBtn"><i class="fas fa-eye me-2"></i>Preview Shipment</button>
            </div>

            <div class="modal fade" id="shipmentPreviewModal" tabindex="-1" role="dialog" aria-hidden="true">
                <div class="modal-dialog modal-xl" role="document">
                    <div class="modal-content"><div class="modal-header"><h5 class="modal-title">Shipment Preview</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div><div class="modal-body" id="shipmentPreviewContent"></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-success" id="createShipmentBtn"><i class="fas fa-shipping-fast me-2"></i>Confirm & Create Shipment</button></div></div>
                </div>
            </div>
        </form>

        <?php if ($transfer_receipt_summary): ?>
        <div class="modal fade" id="transferReceiptModal" tabindex="-1" role="dialog" aria-hidden="true" data-bs-backdrop="static">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title"><i class="fas fa-warehouse me-2"></i>Confirm Stock Received at <?php echo htmlspecialchars($transfer_receipt_summary['to_branch_name']); ?></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <p class="text-muted">Shipment #<?php echo (int)$transfer_receipt_summary['shipment_id']; ?> was submitted to MRA EIS as a stock transfer. The following unique codes account for the stock increase MRA now reports at the destination site:</p>
                        <div class="table-responsive">
                            <table class="table table-bordered table-sm">
                                <thead><tr><th>Product</th><th>Qty Sent</th><th>Unique Codes</th></tr></thead>
                                <tbody>
                                    <?php foreach ($transfer_receipt_summary['lines'] as $line): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($line['eis_product_name'] ?? ''); ?><div class="text-muted small"><?php echo htmlspecialchars($line['eis_product_code'] ?? ''); ?></div></td>
                                            <td><?php echo (int)($line['quantity_sent_to_eis'] ?? 0); ?></td>
                                            <td class="small"><?php echo htmlspecialchars(implode(', ', $line['ims_unique_codes'] ?? [])); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <div id="transferReceiptResult"></div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Skip for now</button>
                        <button type="button" class="btn btn-primary" id="confirmTransferReceiptBtn" data-shipment-id="<?php echo (int)$transfer_receipt_summary['shipment_id']; ?>">
                            <i class="fas fa-sync me-2"></i>Confirm &amp; Verify with MRA
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', function() {

        const currentMode = <?php echo json_encode($mode); ?>;
        const shipmentForm = document.getElementById('shipmentForm');
        const createShipmentBtn = document.getElementById('createShipmentBtn');
        const previewBtn = document.getElementById('previewShipmentBtn');


        const selectAllCheckbox = document.getElementById('selectAllItems');
        const filterSearch = document.getElementById('filterSearch');
        const clearFiltersBtn = document.getElementById('clearFilters');
        const selectedManualItems = new Map();
        const MAX_SHIPMENT_ITEMS = 10000;
        const shipmentExcelFile = document.getElementById('shipmentExcelFile');
        const importShipmentExcelBtn = document.getElementById('importShipmentExcelBtn');
        const shipmentExcelResult = document.getElementById('shipmentExcelResult');


        const barcodeInput = document.getElementById('barcodeInput');
        const scanFeedback = document.getElementById('scanFeedback');
        const scannedItemsTableBody = document.getElementById('scannedItemsTableBody');
        const scannedItemCount = document.getElementById('scannedItemCount');
        const sourceBranchId = '<?php echo $source_branch_id; ?>';
        let scannedItems = new Set();


        let manualTable = null;
        if (document.getElementById('manual-selection-mode').style.display !== 'none') {
            manualTable = $('#manualItemsTable').DataTable({
                serverSide: true,
                processing: true,
                deferRender: true,
                ordering: false,
                lengthChange: false,
                pageLength: 10000,
                dom: 'rtip',
                ajax: { url: '../../ajax/inventory/ship_items_data.php', type: 'GET' },
                columns: [
                    {
                        data: 'group_key', orderable: false, className: 'text-center',
                        render: () => '<button type="button" class="btn btn-sm btn-outline-primary shipment-group-toggle" aria-label="Show unique codes" aria-expanded="false"><i class="fas fa-plus"></i></button>'
                    },
                    {
                        data: 'item_name',
                        render: (data, type, row) => data + (row.product_code ? '<div class="text-muted small">' + row.product_code + '</div>' : '')
                    },
                    {
                        data: 'item_details',
                        defaultContent: 'N/A',
                        render: (data) => data ? data : 'N/A'
                    },
                    {
                        data: 'available_quantity',
                        className: 'text-center',
                        render: (data) => '<span class="badge bg-success">' + (parseInt(data, 10) || 0) + '</span>'
                    },
                    { data: 'unit_price' },
                    { data: 'category' },
                    { data: 'condition_status' },
                    { data: 'technical_specs' }
                ],
                language: { emptyTable: <?php echo json_encode('No items are currently available in the ' . $source_branch_name . ' inventory.'); ?> }
            });

            $('#inventoryTableBody').on('click', '.shipment-group-toggle', async function() {
                const button = this;
                const row = manualTable.row($(button).closest('tr'));
                if (row.child.isShown()) {
                    row.child.hide();
                    button.setAttribute('aria-expanded', 'false');
                    button.querySelector('i').className = 'fas fa-plus';
                    return;
                }
                const panel = document.createElement('div');
                panel.className = 'shipment-group-panel';
                panel.textContent = 'Loading unique-coded items...';
                row.child(panel).show();
                button.setAttribute('aria-expanded', 'true');
                button.querySelector('i').className = 'fas fa-minus';
                try {
                    const response = await fetch('../../ajax/inventory/ship_item_group_codes.php?group_key=' + encodeURIComponent(row.data().group_key), {
                        headers: { 'Accept': 'application/json' }
                    });
                    const responseText = await response.text();
                    let payload;
                    try { payload = JSON.parse(responseText); }
                    catch (parseError) { throw new Error('The server returned an invalid response.'); }
                    if (!response.ok || !payload.success) throw new Error(payload.message || 'Unable to load item group.');
                    renderShipmentGroup(panel, payload.items);
                } catch (error) {
                    panel.textContent = error.message || 'Unable to load item group.';
                    panel.classList.add('text-danger');
                }
            });

            $('#inventoryTableBody').on('change', '.item-checkbox', function() {
                const tr = $(this).closest('tr');
                const rowData = manualTable.row(tr).data();
                const id = String(rowData.item_id);
                if (this.checked) {
                    const priceInput = tr.find('.price-override-input');
                    let priceOverride = null;
                    if (priceInput.length) {
                        const entered = parseFloat(priceInput.val());
                        if (!entered || entered <= 0) {
                            alert('This item has no selling price on file. Please enter one before adding it to the shipment.');
                            this.checked = false;
                            return;
                        }
                        priceOverride = entered;
                    }
                    selectedManualItems.set(id, {
                        name: rowData.item_name, item_details: rowData.item_details || '', unique_id: rowData.unique_code,
                        unit_price: priceOverride ? priceOverride.toFixed(2) : parseFloat(rowData.unit_price).toFixed(2),
                        condition: rowData.condition_status, serial_number: rowData.serial_number,
                        warranty_months: rowData.warranty_months, date_entered: rowData.date_entered,
                        price_override: priceOverride
                    });
                } else {
                    selectedManualItems.delete(id);
                }
                updateSelectAllState();
            });

            $('#inventoryTableBody').on('input', '.price-override-input', function() {
                const tr = $(this).closest('tr');
                const checkbox = tr.find('.item-checkbox')[0];
                if (checkbox && checkbox.checked) {
                    const rowData = manualTable.row(tr).data();
                    const id = String(rowData.item_id);
                    const entered = parseFloat(this.value) || 0;
                    if (selectedManualItems.has(id)) {
                        const existing = selectedManualItems.get(id);
                        existing.price_override = entered > 0 ? entered : null;
                        existing.unit_price = entered > 0 ? entered.toFixed(2) : existing.unit_price;
                    }
                }
            });

            if (selectAllCheckbox) selectAllCheckbox.addEventListener('change', function() {
                const checked = this.checked;
                document.querySelectorAll('#inventoryTableBody .item-checkbox').forEach(cb => {
                    cb.checked = checked;
                    cb.dispatchEvent(new Event('change'));
                });
            });

            function updateSelectAllState() {
                if (!selectAllCheckbox) return;
                const boxes = document.querySelectorAll('#inventoryTableBody .item-checkbox');
                if (boxes.length === 0) { selectAllCheckbox.checked = false; selectAllCheckbox.indeterminate = false; return; }
                const checkedCount = Array.from(boxes).filter(cb => cb.checked).length;
                selectAllCheckbox.checked = checkedCount === boxes.length;
                selectAllCheckbox.indeterminate = checkedCount > 0 && checkedCount < boxes.length;
            }

            function renderShipmentGroup(panel, items) {
                panel.replaceChildren();
                const table = document.createElement('table');
                table.className = 'table table-sm table-bordered mb-0';
                table.innerHTML = '<thead><tr><th>Select</th><th>Unique Code</th><th>Item Details</th><th>Serial No.</th><th>Condition</th><th>Unit Price</th><th>Warranty</th><th>Date Entered</th></tr></thead>';
                const body = document.createElement('tbody');
                items.forEach((item) => {
                    const tr = document.createElement('tr');
                    const selectCell = document.createElement('td');
                    selectCell.className = 'text-center';
                    const checkbox = document.createElement('input');
                    checkbox.type = 'checkbox';
                    checkbox.className = 'group-item-checkbox';
                    checkbox.checked = selectedManualItems.has(String(item.item_id));
                    selectCell.appendChild(checkbox);
                    tr.appendChild(selectCell);

                    [item.unique_code, item.item_details || 'N/A', item.serial_number || 'N/A', item.condition_status || 'N/A'].forEach((value) => {
                        const td = document.createElement('td');
                        td.textContent = value;
                        tr.appendChild(td);
                    });

                    const priceCell = document.createElement('td');
                    let priceInput = null;
                    if ((parseFloat(item.unit_price) || 0) > 0) {
                        priceCell.textContent = parseFloat(item.unit_price).toFixed(2);
                    } else {
                        priceInput = document.createElement('input');
                        priceInput.type = 'number';
                        priceInput.step = '0.01';
                        priceInput.min = '0.01';
                        priceInput.className = 'form-control form-control-sm group-price-input';
                        priceInput.placeholder = 'Enter selling price';
                        const selected = selectedManualItems.get(String(item.item_id));
                        if (selected && selected.price_override) priceInput.value = selected.price_override;
                        priceCell.appendChild(priceInput);
                    }
                    tr.appendChild(priceCell);

                    [String(item.warranty_months || 0), item.date_entered || 'N/A'].forEach((value) => {
                        const td = document.createElement('td');
                        td.textContent = value;
                        tr.appendChild(td);
                    });

                    checkbox.addEventListener('change', function() {
                        const id = String(item.item_id);
                        if (!this.checked) {
                            selectedManualItems.delete(id);
                            return;
                        }
                        if (!selectedManualItems.has(id) && selectedManualItems.size >= MAX_SHIPMENT_ITEMS) {
                            alert('A shipment can contain at most 10,000 items.');
                            this.checked = false;
                            return;
                        }
                        const price = priceInput ? parseFloat(priceInput.value) || 0 : parseFloat(item.unit_price) || 0;
                        if (price <= 0) {
                            alert('Please enter a selling price before selecting this item.');
                            this.checked = false;
                            if (priceInput) priceInput.focus();
                            return;
                        }
                        selectedManualItems.set(id, {
                            name: item.item_name, item_details: item.item_details, unique_id: item.unique_code, unit_price: price.toFixed(2),
                            condition: item.condition_status, serial_number: item.serial_number,
                            warranty_months: item.warranty_months, date_entered: item.date_entered,
                            price_override: priceInput ? price : null
                        });
                    });
                    if (priceInput) priceInput.addEventListener('input', function() {
                        const id = String(item.item_id);
                        const entered = parseFloat(this.value) || 0;
                        if (checkbox.checked && selectedManualItems.has(id) && entered > 0) {
                            const selected = selectedManualItems.get(id);
                            selected.unit_price = entered.toFixed(2);
                            selected.price_override = entered;
                        }
                    });
                    body.appendChild(tr);
                });
                table.appendChild(body);
                panel.appendChild(table);
            }

            let searchDebounce;
            filterSearch.addEventListener('input', function() {
                clearTimeout(searchDebounce);
                const value = this.value;
                searchDebounce = setTimeout(() => manualTable.search(value).draw(), 250);
            });
            clearFiltersBtn.addEventListener('click', () => {
                filterSearch.value = '';
                manualTable.search('').draw();
            });

            importShipmentExcelBtn.addEventListener('click', async function() {
                const file = shipmentExcelFile.files[0];
                if (!file) {
                    shipmentExcelResult.innerHTML = '<div class="alert alert-warning mb-0">Select an Excel or CSV file first.</div>';
                    return;
                }

                const formData = new FormData();
                formData.append('excel_file', file);
                this.disabled = true;
                this.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Importing...';
                shipmentExcelResult.innerHTML = '';

                try {
                    const response = await fetch('../../ajax/inventory/import_shipment_transfer.php', {
                        method: 'POST',
                        body: formData,
                        headers: { 'Accept': 'application/json' }
                    });
                    const responseText = await response.text();
                    let payload;
                    try {
                        payload = JSON.parse(responseText);
                    } catch (parseError) {
                        throw new Error('The server returned an invalid response.');
                    }
                    if (!response.ok || !payload.success) {
                        throw new Error(payload.message || 'Unable to import the transfer file.');
                    }

                    const combinedItemIds = new Set([...selectedManualItems.keys(), ...payload.items.map((item) => String(item.item_id))]);
                    if (combinedItemIds.size > MAX_SHIPMENT_ITEMS) {
                        throw new Error('A shipment can contain at most 10,000 items.');
                    }
                    payload.items.forEach((item) => {
                        const price = parseFloat(item.selling_price);
                        selectedManualItems.set(String(item.item_id), {
                            name: item.item_name,
                            item_details: item.item_details,
                            unique_id: item.unique_code,
                            unit_price: price.toFixed(2),
                            condition: item.condition_status,
                            serial_number: item.serial_number,
                            warranty_months: item.warranty_months,
                            date_entered: item.date_entered,
                            price_override: price
                        });
                    });

                    const issues = Array.isArray(payload.errors) ? payload.errors : [];
                    const result = document.createElement('div');
                    result.className = 'alert alert-' + (issues.length ? 'warning' : 'success') + ' mb-0';
                    result.textContent = payload.selected_count + ' item(s) selected for transfer.' +
                        (issues.length ? ' ' + issues.join(' ') : ' Review them in the shipment preview before confirming.');
                    shipmentExcelResult.replaceChildren(result);
                    manualTable.draw(false);
                } catch (error) {
                    const result = document.createElement('div');
                    result.className = 'alert alert-danger mb-0';
                    result.textContent = error.message || 'Unable to import the transfer file.';
                    shipmentExcelResult.replaceChildren(result);
                } finally {
                    this.disabled = false;
                    this.innerHTML = '<i class="fas fa-file-import me-1"></i>Import';
                }
            });
        }


        if (document.getElementById('scanner-mode').style.display !== 'none') {
            barcodeInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    const barcode = this.value.trim();
                    if (barcode) handleBarcodeScan(barcode);
                    this.value = '';
                }
            });
        }
        function handleBarcodeScan(barcode) {
            if (scannedItems.has(barcode)) {
                showFeedback('This item has already been scanned.', 'warning'); return;
            }
            showFeedback('Looking up barcode...', 'info');
            $.ajax({
                url: 'get_item_by_barcode.php', type: 'POST', data: { barcode, source_branch_id: sourceBranchId }, dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        showFeedback(`Success: ${response.item.item_name} added.`, 'success');
                        addItemToTable(response.item);
                        scannedItems.add(barcode);
                    } else { showFeedback(response.message, 'danger'); }
                },
                error: function() { showFeedback('Server error.', 'danger'); }
            });
        }
        function addItemToTable(item) {
            const price = parseFloat(item.unit_price) || 0;
            const priceCell = price > 0
                ? price.toFixed(2)
                : `<input type="number" step="0.01" min="0.01" class="form-control form-control-sm price-override-input" name="items[${item.item_id}][price_override]" placeholder="Enter selling price" required>`;
            const row = scannedItemsTableBody.insertRow();
            row.dataset.itemId = item.item_id;
            row.innerHTML = `
                <td>${item.item_name}<input type="checkbox" class="item-checkbox" name="items[${item.item_id}][selected]" value="1" checked style="display:none;"><input type="hidden" name="items[${item.item_id}][item_id]" value="${item.item_id}"></td>
                <td>${item.item_details || 'N/A'}</td><td>${item.unique_code || 'N/A'}</td><td>${item.condition_status || 'N/A'}</td><td>${item.serial_number || 'N/A'}</td>
                <td>${priceCell}</td>
                <td class="text-center"><button type="button" class="btn btn-sm btn-danger remove-item-btn"><i class="fas fa-trash"></i></button></td>
            `;
            updateScannedItemCount();
            row.querySelector('.remove-item-btn').addEventListener('click', function() {
                scannedItems.delete(item.unique_code); row.remove(); updateScannedItemCount();
            });
        }
        function updateScannedItemCount() { scannedItemCount.textContent = scannedItemsTableBody.rows.length; }
        function showFeedback(message, type) { scanFeedback.innerHTML = `<div class="alert alert-${type}">${message}</div>`; setTimeout(() => { scanFeedback.innerHTML = ''; }, 4000); }


        previewBtn.addEventListener('click', function() {
            let itemsData = [];
            if (currentMode === 'manual') {
                itemsData = Array.from(selectedManualItems.values());
            } else {
                document.querySelectorAll('#scannedItemsTableBody .item-checkbox:checked').forEach(checkbox => {
                    const row = checkbox.closest('tr');
                    const priceInput = row.querySelector('.price-override-input');
                    const unitPrice = priceInput ? (parseFloat(priceInput.value) || 0).toFixed(2) : row.cells[5].textContent.trim();
                    itemsData.push({
                        name: row.cells[0].textContent.trim(), item_details: row.cells[1].textContent, unique_id: row.cells[2].textContent, condition: row.cells[3].textContent,
                        serial_number: row.cells[4].textContent, unit_price: unitPrice, warranty_months: 'N/A', date_entered: 'N/A'
                    });
                });
            }
            if (itemsData.length === 0) {
                alert('Please select or scan at least one item.'); return;
            }
            generatePreviewContent(itemsData);
            bootstrap.Modal.getOrCreateInstance(document.getElementById('shipmentPreviewModal')).show();
        });

        createShipmentBtn.addEventListener('click', function() {
            if (currentMode === 'manual') {
                const container = document.getElementById('manualSelectedInputs');
                container.innerHTML = '';
                const payload = [];
                selectedManualItems.forEach((data, id) => {
                    payload.push({
                        item_id: parseInt(id, 10),
                        price_override: data.price_override || null
                    });
                });
                if (payload.length > MAX_SHIPMENT_ITEMS) {
                    alert('A shipment can contain at most 10,000 items.');
                    return;
                }
                const payloadInput = document.createElement('input');
                payloadInput.type = 'hidden';
                payloadInput.name = 'items_payload';
                payloadInput.value = JSON.stringify(payload);
                container.appendChild(payloadInput);
            } else {
                // form.submit() skips native "required" validation, so scanner-mode price inputs
                // (shown only for items with no price on file) must be checked explicitly here.
                const missingPrice = Array.from(document.querySelectorAll('#scannedItemsTableBody .item-checkbox:checked'))
                    .some(checkbox => {
                        const priceInput = checkbox.closest('tr').querySelector('.price-override-input');
                        return priceInput && !(parseFloat(priceInput.value) > 0);
                    });
                if (missingPrice) {
                    alert('Please enter a selling price for every scanned item that has none on file.');
                    return;
                }
            }
            this.disabled = true; this.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Creating...'; shipmentForm.submit();
        });

        function generatePreviewContent(itemsData) {
            let totalValue = 0;
            let itemsHtml = itemsData.map((item, index) => {
                let price = parseFloat(item.unit_price.replace(/[^0-9.-]+/g, '')) || 0;
                totalValue += price;
                return `<div class="card mb-2"><div class="card-body p-3"><h6><span class="badge bg-info me-2">#${index + 1}</span>${item.name}</h6><p class="mb-0 small text-muted">Details: ${item.item_details || 'N/A'} | ID: ${item.unique_id} | Condition: ${item.condition} | Serial: ${item.serial_number}</p></div></div>`;
            }).join('');

            let summaryHtml = `<div class="shipment-summary"><h5>Shipment Summary</h5><p class="mb-1"><strong>From:</strong> <?php echo htmlspecialchars($source_branch_name); ?> &rarr; <strong>To:</strong> <?php echo htmlspecialchars($destination_branch_name); ?></p><p class="mb-0"><strong>Total Items:</strong> ${itemsData.length} | <strong>Total Value:</strong> K${totalValue.toFixed(2)}</p></div>`;
            document.getElementById('shipmentPreviewContent').innerHTML = summaryHtml + '<h6>Items to Ship</h6>' + itemsHtml;
        }

        <?php if ($transfer_receipt_summary): ?>
        const transferReceiptModalEl = document.getElementById('transferReceiptModal');
        bootstrap.Modal.getOrCreateInstance(transferReceiptModalEl).show();

        document.getElementById('confirmTransferReceiptBtn').addEventListener('click', function() {
            const btn = this;
            const action = btn.dataset.action || 'verify';
            if (action === 'close') {
                bootstrap.Modal.getOrCreateInstance(transferReceiptModalEl).hide();
                return;
            }
            if (action === 'calibrate' && !window.confirm('Calibrate the destination IMS inventory to the live EIS quantities for the mismatched products? IMS may create or remove EIS-synced item rows.')) {
                return;
            }
            const shipmentId = btn.dataset.shipmentId;
            const resultEl = document.getElementById('transferReceiptResult');
            btn.disabled = true;
            btn.innerHTML = action === 'calibrate'
                ? '<i class="fas fa-spinner fa-spin me-2"></i>Calibrating IMS Inventory...'
                : '<i class="fas fa-spinner fa-spin me-2"></i>Verifying with MRA...';
            $.ajax({
                url: '../../ajax/inventory/confirm_transfer_receipt.php',
                type: 'POST',
                data: { shipment_id: shipmentId, action: action },
                dataType: 'json',
                timeout: 200000,
                success: function(response) {
                    if (!response.success) {
                        resultEl.innerHTML = `<div class="alert alert-danger mt-3">${response.message || 'Verification failed.'}</div>`;
                        btn.disabled = false;
                        btn.innerHTML = '<i class="fas fa-sync me-2"></i>Retry';
                        return;
                    }
                    if (response.action === 'calibrate') {
                        const variances = Array.isArray(response.flagged_variance) ? response.flagged_variance.length : 0;
                        const alertEl = document.createElement('div');
                        alertEl.className = 'alert alert-' + (variances ? 'warning' : 'success') + ' mt-3';
                        alertEl.textContent = response.already_matched
                            ? 'EIS and IMS inventory already match; no calibration was needed.'
                            : (variances
                                ? 'Calibration completed, but ' + variances + ' product(s) still need manual review because non-EIS IMS items cannot be removed automatically.'
                                : 'IMS inventory was calibrated successfully to the live EIS stock quantities.');
                        const detailEl = document.createElement('p');
                        detailEl.className = 'small text-muted';
                        detailEl.textContent = 'IMS items created: ' + (response.created || 0) +
                            ' | removed: ' + (response.removed || 0) +
                            ' | unchanged products: ' + (response.unchanged || 0);
                        resultEl.replaceChildren(alertEl, detailEl);
                        btn.dataset.action = 'close';
                        btn.className = 'btn btn-primary';
                        btn.textContent = 'OK';
                        btn.disabled = false;
                        return;
                    }
                    let rows = response.lines.map(line => {
                        const badge = line.matched ? '<span class="badge bg-success">Match</span>' : '<span class="badge bg-warning text-dark">Mismatch</span>';
                        return `<tr><td>${line.product_name} <div class="text-muted small">${line.product_code}</div></td><td>${line.quantity_sent}</td><td>${line.quantity_before ?? 'N/A'}</td><td>${line.quantity_after ?? 'N/A'}</td><td>${badge}</td></tr>`;
                    }).join('');
                    resultEl.innerHTML = `<div class="alert alert-${response.matched ? 'success' : 'warning'} mt-3">${response.matched ? 'EIS site stock matches the transferred unique codes.' : 'EIS site stock does not match for one or more products - review manually.'}</div>` +
                        `<table class="table table-sm table-bordered"><thead><tr><th>Product</th><th>Sent</th><th>Before</th><th>After</th><th>Result</th></tr></thead><tbody>${rows}</tbody></table>`;
                    btn.dataset.action = response.matched ? 'close' : 'calibrate';
                    btn.className = response.matched ? 'btn btn-primary' : 'btn btn-warning';
                    btn.textContent = response.matched ? 'OK' : 'Calibrate IMS Inventory';
                    btn.disabled = false;
                },
                error: function(xhr, textStatus) {
                    let message = xhr.responseJSON ? xhr.responseJSON.message : '';
                    if (!message && textStatus === 'timeout') {
                        message = 'MRA verification timed out. Please check the MRA connection and retry.';
                    }
                    if (!message) {
                        message = 'Server error while verifying with MRA' + (xhr.status ? ' (HTTP ' + xhr.status + ')' : '') + '.';
                    }
                    resultEl.innerHTML = '<div class="alert alert-danger mt-3"></div>';
                    resultEl.firstElementChild.textContent = message;
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fas fa-sync me-2"></i>Retry';
                }
            });
        });
        <?php endif; ?>
    });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
