<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Branch.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'] != 'branch' && $_SESSION['role'] != 'branch') {
    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']);
?>

<?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; }
    </style>

    <div class="container">
        <div class="page-header">
            <a href="add_items_dashboard3.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" role="alert"><i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($success_message); ?></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="branch_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="filter-container mb-3 mt-3">
                    <div class="row align-items-end">
                        <div class="col-md-10"><label for="filterSearch">Search</label><input type="text" id="filterSearch" class="form-control" placeholder="Search by item name, 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"><input type="checkbox" id="selectAllItems" title="Select All (current page)"></th>
                                        <th>Item Name</th><th>Item Details</th><th>Unique ID</th><th>Unit Price</th><th>Condition</th>
                                        <th>Serial No.</th><th>Warranty (M)</th><th>Specs</th><th>Date Entered</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 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>
    </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 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,
                ordering: false,
                lengthChange: false,
                pageLength: 50,
                dom: 'rtip',
                ajax: { url: '../../ajax/inventory/ship_items_data.php', type: 'GET' },
                columns: [
                    {
                        data: null, orderable: false, className: 'text-center',
                        render: (data) => `<input type="checkbox" class="item-checkbox" data-item-id="${data.item_id}">`
                    },
                    { data: 'item_name' },
                    { data: 'item_details', render: (data) => data || 'N/A' },
                    { data: 'unique_code' },
                    { data: 'unit_price', render: (data) => parseFloat(data).toFixed(2) },
                    { data: 'condition_status' },
                    { data: 'serial_number' },
                    { data: 'warranty_months' },
                    { data: 'technical_specs' },
                    { data: 'date_entered' }
                ],
                language: { emptyTable: <?php echo json_encode('No items are currently available in the ' . $source_branch_name . ' inventory.'); ?> },
                rowCallback: function(row, data) {
                    const checkbox = row.querySelector('.item-checkbox');
                    if (checkbox) checkbox.checked = selectedManualItems.has(String(data.item_id));
                },
                drawCallback: updateSelectAllState
            });

            $('#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) {
                    selectedManualItems.set(id, {
                        name: rowData.item_name, item_details: rowData.item_details, unique_id: rowData.unique_code,
                        unit_price: 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
                    });
                } else {
                    selectedManualItems.delete(id);
                }
                updateSelectAllState();
            });

            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() {
                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;
            }

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


        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 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 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');
                    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: 'N/A', 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(event) {
            event.preventDefault();
            if (currentMode === 'manual') {
                const container = document.getElementById('manualSelectedInputs');
                container.innerHTML = '';
                selectedManualItems.forEach((data, id) => {
                    container.insertAdjacentHTML('beforeend', `<input type="hidden" name="selected_item_ids[]" value="${id}">`);
                });
            }
            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">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;
        }
    });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
