<?php
require_once '../../includes/header.php';
require_once '../../classes/MraEisOnboarding.php';

if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
    header('Location: ../../unauthorized.php');
    exit;
}

$eis      = new MraEisOnboarding($conn);
$branches  = $eis->branches();
$terminals = $eis->activatedTerminals();

$message     = null;
$messageType = 'success';

$selectedBranch   = $_GET['branch_id']   ?? '';
$selectedTerminal = $_GET['terminal_id'] ?? ($terminals[0]['id'] ?? '');
$search           = $_GET['search']      ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selectedBranch   = $_POST['branch_id']   ?? $selectedBranch;
    $selectedTerminal = $_POST['terminal_id'] ?? $selectedTerminal;
    $search           = $_POST['search']      ?? $search;
}

// POST: refresh live EIS barcodes and reconcile them into the terminal's IMS branch.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['calibrate_barcodes'])) {
    try {
        $terminalId = (int)($_POST['terminal_id'] ?? 0);
        $terminal = $terminalId > 0 ? $eis->find($terminalId) : null;
        if (!$terminal || ($terminal['status'] ?? '') !== 'activated' || trim((string)($terminal['jwt_token'] ?? '')) === '') {
            throw new RuntimeException('Select an activated EIS terminal with a stored token before calibrating barcodes.');
        }

        $calibrationBranchId = (int)($terminal['branch_id'] ?? 0);
        if ($calibrationBranchId <= 0) {
            throw new RuntimeException('The selected EIS terminal is not assigned to an IMS branch.');
        }

        $result = $eis->syncSiteTerminalProductsToBranch($terminalId, $calibrationBranchId);
        $branchLabel = trim((string)($terminal['branch_name'] ?? '')) ?: ('branch #' . $calibrationBranchId);
        $message = "EIS barcode calibration for {$branchLabel} completed: {$result['created']} item(s) created, {$result['removed']} removed, and {$result['unchanged']} barcode(s) unchanged.";
        if (!empty($result['flagged_variance'])) {
            $messageType = 'warning';
            $message .= ' ' . count($result['flagged_variance']) . ' barcode(s) still require manual review.';
        }
        if (!empty($result['flagged_fractional'])) {
            $messageType = 'warning';
            $message .= ' ' . count($result['flagged_fractional']) . ' barcode(s) reported fractional quantities.';
        }
        if (!empty($result['flagged_capped'])) {
            $messageType = 'danger';
            $message .= ' ' . count($result['flagged_capped']) . ' barcode(s) exceeded the safety cap.';
        }
    } catch (Throwable $e) {
        error_log('EIS barcode calibration failed: ' . $e->getMessage());
        $message = $e->getMessage();
        $messageType = 'danger';
    }
}

// POST: stamp several selected batches.
elseif (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && (isset($_POST['stamp_selected']) || isset($_POST['selected_batches']))
) {
    $startedTransaction = false;
    try {
        $selectedBatchPayloads = $_POST['selected_batches'] ?? [];
        if (!is_array($selectedBatchPayloads) || empty($selectedBatchPayloads)) {
            throw new RuntimeException('Select at least one stock batch to map.');
        }
        if (count($selectedBatchPayloads) > 200) {
            throw new RuntimeException('A maximum of 200 batches can be mapped at once.');
        }

        $selectedBatches = [];
        foreach ($selectedBatchPayloads as $payload) {
            $batch = json_decode((string)$payload, true);
            $productCode = trim((string)($batch['product_code'] ?? ''));
            $locationId = (int)($batch['location_id'] ?? 0);
            $siteProductId = (int)($batch['site_product_id'] ?? 0);
            if ($productCode === '' || $locationId === 0) {
                throw new RuntimeException('One selected stock batch is invalid. Refresh the page and try again.');
            }
            if ($siteProductId === 0) {
                throw new RuntimeException('Choose an EIS product for every selected stock batch.');
            }
            $selectedBatches[hash('sha256', $locationId . '|' . $productCode)] = [$productCode, $locationId, $siteProductId];
        }

        if (!$conn->inTransaction()) {
            $conn->beginTransaction();
            $startedTransaction = true;
        }
        $stampedItems = 0;
        foreach ($selectedBatches as [$productCode, $locationId, $siteProductId]) {
            $stampedItems += $eis->stampBatchEisSiteProduct(
                $productCode,
                $locationId,
                $siteProductId,
                $_SESSION['user_id'] ?? null
            );
        }
        if ($startedTransaction && $conn->inTransaction()) {
            $conn->commit();
        }

        $mappedBatchCount = count($selectedBatches);
        $message = "Bulk mapping completed. {$mappedBatchCount} batch(es) and {$stampedItems} unsold item(s) were mapped.";
    } catch (Throwable $e) {
        if ($startedTransaction && $conn->inTransaction()) {
            $conn->rollBack();
        }
        error_log('EIS bulk stock mapping failed: ' . $e->getMessage());
        $message = $e->getMessage();
        $messageType = 'danger';
    }
}

// POST: stamp one batch.
elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['stamp_batch'])) {
    try {
        $productCode   = trim((string)($_POST['product_code']    ?? ''));
        $locationId    = (int)($_POST['location_id']             ?? 0);
        $siteProductId = (int)($_POST['site_product_id']         ?? 0);

        if ($productCode === '') {
            throw new RuntimeException('The selected product batch is missing. Refresh the page and try again.');
        }
        if ($locationId === 0) {
            throw new RuntimeException('The selected stock branch is missing. Refresh the page and try again.');
        }
        if ($siteProductId === 0) {
            throw new RuntimeException('Please choose an EIS site product before clicking Assign.');
        }

        $stamped = $eis->stampBatchEisSiteProduct(
            $productCode,
            $locationId,
            $siteProductId,
            $_SESSION['user_id'] ?? null
        );

        $message = "Mapped successfully. {$stamped} item(s) stamped with the selected EIS site product.";
    } catch (Exception $e) {
        $message     = $e->getMessage();
        $messageType = 'danger';
    }
}

// ── Data for page ─────────────────────────────────────────────────────────────
$siteProducts  = $eis->siteProducts($selectedTerminal ?: null, null);
$unmappedBatches = $eis->unmappedItemBatches($selectedBranch ?: null, $search, 200);
$mappedBatches   = $eis->mappedItemBatches($search, 200);
?>

<style>
    body { background: #f4f6f8; }
    .bm-shell  { max-width: 1320px; margin: 30px auto; padding: 0 15px; }
    .bm-topbar { display: flex; justify-content: space-between; gap: 16px; align-items: flex-start; margin-bottom: 20px; }
    .bm-title  { font-weight: 800; color: #172033; }
    .bm-card   { border: 0; border-radius: 8px; box-shadow: 0 2px 12px rgba(15,23,42,.08); }
    .bm-card .card-header { background: #1f2937; color: #fff; border-radius: 8px 8px 0 0; }
    .meta      { color: #667085; font-size: .85rem; line-height: 1.5; }
    .table td, .table th { vertical-align: middle; }
    .badge-unsold  { background: #fef3c7; color: #92400e; }
    .badge-sold    { background: #d1fae5; color: #065f46; }
    .price-pill    { display: inline-block; background: #eff6ff; color: #1d4ed8;
                     border-radius: 999px; padding: 2px 10px; font-size: .8rem; font-weight: 600; }
    .bulk-map-bar  { background: #eef2ff; border: 1px solid #c7d2fe; border-radius: 8px; padding: 14px; }
    .batch-select-cell { width: 44px; text-align: center; }
    .batch-checkbox, #selectAllBatches { width: 18px; height: 18px; cursor: pointer; }
    #tblUnmapped tbody tr.bulk-selected { background: #eef2ff; }
    @media (max-width: 768px) { .bm-topbar { display: block; } }
</style>

<div class="bm-shell">

    <?php $eisNavCurrent = 'stock_batch_mapping'; require __DIR__ . '/../../includes/eis_admin_nav.php'; ?>

    <!-- ── Page header ──────────────────────────────────────────────────── -->
    <div class="bm-topbar">
        <div>
            <h2 class="bm-title mb-1">
                <i class="fas fa-boxes"></i> EIS Stock Batch Mapping
            </h2>
            <p class="text-muted mb-0">
                Assign each physical stock batch to the correct MRA EIS site product so
                sales can deduct EIS quantities accurately.
            </p>
        </div>
        <form method="POST" id="calibrateBarcodesForm" class="flex-shrink-0">
            <input type="hidden" name="calibrate_barcodes" value="1">
            <input type="hidden" name="terminal_id" value="<?php echo htmlspecialchars($selectedTerminal); ?>">
            <input type="hidden" name="branch_id" value="<?php echo htmlspecialchars($selectedBranch); ?>">
            <input type="hidden" name="search" value="<?php echo htmlspecialchars($search); ?>">
            <button type="submit"
                    id="calibrateBarcodesBtn"
                    class="btn btn-warning"
                    <?php echo empty($selectedTerminal) ? 'disabled' : ''; ?>
                    onclick="return confirm('Refresh live EIS quantities and calibrate the selected terminal’s IMS branch? This may create or remove EIS-synced unsold item rows.');">
                <i class="fas fa-barcode"></i> Calibrate EIS Barcodes
            </button>
            <div class="meta text-end mt-1">Uses the selected terminal</div>
        </form>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-<?php echo htmlspecialchars($messageType); ?> alert-dismissible fade show" role="alert">
            <?php echo htmlspecialchars($message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- ── Filters ──────────────────────────────────────────────────────── -->
    <div class="card bm-card mb-4">
        <div class="card-header"><h5 class="mb-0"><i class="fas fa-filter"></i> Filters</h5></div>
        <div class="card-body">
            <form method="GET">
                <div class="row g-3 align-items-end">
                    <div class="col-lg-3 col-md-6">
                        <label class="form-label">MRA Terminal (for EIS product list)</label>
                        <select name="terminal_id" class="form-select">
                            <?php foreach ($terminals as $t): ?>
                                <option value="<?php echo (int)$t['id']; ?>"
                                    <?php echo (string)$selectedTerminal === (string)$t['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($t['terminal_label'] . ' — ' . ($t['branch_name'] ?? '?')); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-lg-3 col-md-6">
                        <label class="form-label">Stock Branch (filter unmapped)</label>
                        <select name="branch_id" class="form-select">
                            <option value="">All branches</option>
                            <?php foreach ($branches as $b): ?>
                                <option value="<?php echo (int)$b['branch_id']; ?>"
                                    <?php echo (string)$selectedBranch === (string)$b['branch_id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($b['branch_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-lg-4 col-md-6">
                        <label class="form-label">Search</label>
                        <input type="text" name="search" class="form-control"
                               value="<?php echo htmlspecialchars($search); ?>"
                               placeholder="Product code, item name, or branch">
                    </div>
                    <div class="col-lg-2">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-search"></i> Apply
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- ── Unmapped batches ─────────────────────────────────────────────── -->
    <div class="card bm-card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-exclamation-triangle text-warning me-1"></i> Unmapped Batches</h5>
            <span class="badge bg-warning text-dark"><?php echo count($unmappedBatches); ?> batch(es)</span>
        </div>
        <div class="card-body">
            <?php if (empty($terminals)): ?>
                <div class="alert alert-warning mb-0">
                    No activated MRA EIS terminals found. Activate a terminal before mapping.
                </div>
            <?php elseif (empty($siteProducts)): ?>
                <div class="alert alert-warning mb-0">
                    No EIS site products available for the selected terminal.
                    <a href="mra_eis_site_products.php">Download site products</a> first.
                </div>
            <?php elseif (empty($unmappedBatches)): ?>
                <div class="alert alert-success mb-0">
                    <i class="fas fa-check-circle"></i>
                    All stock batches for the selected filter are mapped. Great work!
                </div>
            <?php else: ?>
                <p class="text-muted mb-3" style="font-size:.875rem;">
                    Each row below represents all unsold items sharing the same
                    <strong>product code</strong> at a given <strong>branch</strong>.
                    Select one or more batches for bulk mapping, or use <strong>Assign</strong> on a single row.
                </p>
                <form method="POST" id="bulkMappingForm" class="bulk-map-bar mb-3">
                    <input type="hidden" name="stamp_selected" value="1">
                    <input type="hidden" name="terminal_id" value="<?php echo htmlspecialchars($selectedTerminal); ?>">
                    <input type="hidden" name="branch_id" value="<?php echo htmlspecialchars($selectedBranch); ?>">
                    <input type="hidden" name="search" value="<?php echo htmlspecialchars($search); ?>">
                    <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
                        <div>
                            <div class="fw-semibold">Bulk mapping</div>
                            <div class="meta">Choose an EIS product in each row. Selecting a product also selects that row.</div>
                        </div>
                        <div class="d-flex align-items-center gap-2">
                            <span id="selectedBatchCount" class="badge bg-secondary">0 selected</span>
                            <button type="submit" id="mapSelectedBtn" class="btn btn-primary" disabled>
                                <i class="fas fa-layer-group"></i> Map Selected
                            </button>
                        </div>
                    </div>
                </form>
                <div class="table-responsive">
                    <table class="table table-bordered table-hover mb-0" id="tblUnmapped">
                        <thead class="table-dark">
                            <tr>
                                <th class="batch-select-cell">
                                    <input type="checkbox" id="selectAllBatches" aria-label="Select all unmapped batches">
                                </th>
                                <th>Product Batch</th>
                                <th>Branch</th>
                                <th>Items</th>
                                <th style="min-width:320px;">Assign to EIS Product</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($unmappedBatches as $batch):
                                $formId = 'f-' . md5($batch['product_code'] . '-' . $batch['branch_id']);
                            ?>
                                <tr>
                                    <td class="batch-select-cell">
                                        <input type="checkbox"
                                               class="batch-checkbox"
                                               data-batch="<?php echo htmlspecialchars(json_encode([
                                                   'product_code' => (string)$batch['product_code'],
                                                   'location_id' => (int)$batch['branch_id'],
                                               ], JSON_UNESCAPED_SLASHES), ENT_QUOTES, 'UTF-8'); ?>"
                                               aria-label="Select <?php echo htmlspecialchars($batch['item_name']); ?>">
                                    </td>
                                    <td>
                                        <strong><?php echo htmlspecialchars($batch['item_name']); ?></strong>
                                        <div class="meta">
                                            Product code: <code><?php echo htmlspecialchars($batch['product_code']); ?></code>
                                        </div>
                                    </td>
                                    <td><?php echo htmlspecialchars($batch['branch_name'] ?? '—'); ?></td>
                                    <td class="text-center">
                                        <span class="badge badge-unsold me-1">
                                            <?php echo (int)$batch['unsold_items']; ?> unsold
                                        </span>
                                        <?php if ((int)$batch['total_items'] > (int)$batch['unsold_items']): ?>
                                            <span class="badge badge-sold">
                                                <?php echo (int)$batch['total_items'] - (int)$batch['unsold_items']; ?> sold
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <select class="form-select form-select-sm single-site-product"
                                                data-form-id="<?php echo $formId; ?>"
                                                required>
                                            <option value="">— choose EIS product —</option>
                                            <?php foreach ($siteProducts as $sp): ?>
                                                <option value="<?php echo (int)$sp['id']; ?>">
                                                    <?php echo htmlspecialchars(
                                                        $sp['product_code'] . ' · ' .
                                                        $sp['product_name'] . ' · ' .
                                                        number_format((float)$sp['price'], 2) . ' MWK' .
                                                        ' (qty ' . number_format((float)$sp['quantity'], 0) . ')' .
                                                        ' — ' . ($sp['branch_name'] ?? $sp['site_id'])
                                                    ); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td>
                                        <form method="POST" id="<?php echo $formId; ?>">
                                            <input type="hidden" name="stamp_batch"   value="1">
                                            <input type="hidden" name="site_product_id" class="single-site-product-value" value="">
                                            <input type="hidden" name="product_code"  value="<?php echo htmlspecialchars($batch['product_code']); ?>">
                                            <input type="hidden" name="location_id"   value="<?php echo (int)$batch['branch_id']; ?>">
                                            <input type="hidden" name="terminal_id"   value="<?php echo htmlspecialchars($selectedTerminal); ?>">
                                            <input type="hidden" name="branch_id"     value="<?php echo htmlspecialchars($selectedBranch); ?>">
                                            <input type="hidden" name="search"        value="<?php echo htmlspecialchars($search); ?>">
                                            <button type="submit" class="btn btn-sm btn-primary">
                                                <i class="fas fa-check"></i> Assign
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- ── Mapped batches ───────────────────────────────────────────────── -->
    <div class="card bm-card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-check-circle text-success me-1"></i> Mapped Batches</h5>
            <span class="badge bg-success"><?php echo count($mappedBatches); ?> batch(es)</span>
        </div>
        <div class="card-body">
            <?php if (empty($mappedBatches)): ?>
                <div class="alert alert-info mb-0">No batches have been mapped yet.</div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped mb-0" id="tblMapped">
                        <thead class="table-dark">
                            <tr>
                                <th>IMS Product Batch</th>
                                <th>Branch</th>
                                <th class="text-center">Items</th>
                                <th>EIS Product</th>
                                <th class="text-center">EIS Price</th>
                                <th class="text-center">EIS Qty Remaining</th>
                                <th>Terminal</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($mappedBatches as $batch):
                                $formId = 're-' . md5($batch['product_code'] . '-' . $batch['branch_id']);
                            ?>
                                <tr>
                                    <td>
                                        <strong><?php echo htmlspecialchars($batch['item_name']); ?></strong>
                                        <div class="meta">
                                            <code><?php echo htmlspecialchars($batch['product_code']); ?></code>
                                        </div>
                                    </td>
                                    <td><?php echo htmlspecialchars($batch['branch_name'] ?? '—'); ?></td>
                                    <td class="text-center"><?php echo (int)$batch['total_items']; ?></td>
                                    <td>
                                        <?php if ($batch['eis_product_name']): ?>
                                            <?php echo htmlspecialchars($batch['eis_product_name']); ?>
                                        <?php else: ?>
                                            <span class="text-danger">EIS product not found</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <?php if ($batch['eis_price'] !== null): ?>
                                            <span class="price-pill">
                                                <?php echo number_format((float)$batch['eis_price'], 2); ?> MWK
                                            </span>
                                        <?php else: ?>
                                            —
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <?php
                                        $qty = (float)($batch['eis_quantity'] ?? 0);
                                        $cls = $qty > 0 ? 'text-success fw-bold' : 'text-danger fw-bold';
                                        echo '<span class="' . $cls . '">' . number_format($qty, 0) . '</span>';
                                        ?>
                                    </td>
                                    <td class="meta"><?php echo htmlspecialchars($batch['terminal_label'] ?? '—'); ?></td>
                                    <td>
                                        <?php if (!empty($siteProducts)): ?>
                                            <!-- Re-map button: opens inline form -->
                                            <button class="btn btn-sm btn-outline-secondary"
                                                    type="button"
                                                    data-bs-toggle="collapse"
                                                    data-bs-target="#<?php echo $formId; ?>">
                                                <i class="fas fa-edit"></i> Re-map
                                            </button>
                                            <div class="collapse mt-2" id="<?php echo $formId; ?>">
                                                <form method="POST" class="d-flex gap-2 align-items-center flex-wrap">
                                                    <input type="hidden" name="stamp_batch"  value="1">
                                                    <input type="hidden" name="product_code" value="<?php echo htmlspecialchars($batch['product_code']); ?>">
                                                    <input type="hidden" name="location_id"  value="<?php echo (int)$batch['branch_id']; ?>">
                                                    <input type="hidden" name="terminal_id"  value="<?php echo htmlspecialchars($selectedTerminal); ?>">
                                                    <input type="hidden" name="branch_id"    value="<?php echo htmlspecialchars($selectedBranch); ?>">
                                                    <input type="hidden" name="search"       value="<?php echo htmlspecialchars($search); ?>">
                                                    <select name="site_product_id" class="form-select form-select-sm" style="min-width:280px;" required>
                                                        <option value="">— choose new EIS product —</option>
                                                        <?php foreach ($siteProducts as $sp): ?>
                                                            <option value="<?php echo (int)$sp['id']; ?>"
                                                                <?php echo (int)$sp['id'] === (int)$batch['eis_site_product_id'] ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars(
                                                                    $sp['product_code'] . ' · ' . $sp['product_name'] .
                                                                    ' · ' . number_format((float)$sp['price'], 2) . ' MWK' .
                                                                    ' (qty ' . number_format((float)$sp['quantity'], 0) . ')'
                                                                ); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <button type="submit" class="btn btn-sm btn-warning">
                                                        <i class="fas fa-save"></i> Save
                                                    </button>
                                                </form>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

</div><!-- /.bm-shell -->

<script>
document.addEventListener('DOMContentLoaded', function () {
    const calibrationForm = document.getElementById('calibrateBarcodesForm');
    const calibrationButton = document.getElementById('calibrateBarcodesBtn');
    if (calibrationForm && calibrationButton) {
        calibrationForm.addEventListener('submit', function () {
            calibrationButton.disabled = true;
            calibrationButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Calibrating…';
        });
    }

    document.querySelectorAll('.single-site-product').forEach(function (select) {
        const form = document.getElementById(select.dataset.formId || '');
        if (!form) return;

        const hiddenValue = form.querySelector('.single-site-product-value');
        function syncSingleProduct() {
            if (hiddenValue) hiddenValue.value = select.value;
        }

        select.addEventListener('change', function () {
            syncSingleProduct();
            const checkbox = select.closest('tr').querySelector('.batch-checkbox');
            if (checkbox) {
                checkbox.checked = select.value !== '';
                refreshBulkSelection();
            }
        });
        form.addEventListener('submit', function (event) {
            syncSingleProduct();
            if (!select.value) {
                event.preventDefault();
                select.reportValidity();
            }
        });
    });

    const selectAll = document.getElementById('selectAllBatches');
    const checkboxes = Array.from(document.querySelectorAll('.batch-checkbox'));
    const selectedCount = document.getElementById('selectedBatchCount');
    const mapButton = document.getElementById('mapSelectedBtn');
    const bulkForm = document.getElementById('bulkMappingForm');

    if (!selectAll || !bulkForm) return;

    function refreshBulkSelection() {
        const checked = checkboxes.filter(function (checkbox) { return checkbox.checked; });
        const count = checked.length;
        selectedCount.textContent = count === 1 ? '1 batch selected' : count + ' batches selected';
        selectedCount.classList.toggle('bg-secondary', count === 0);
        selectedCount.classList.toggle('bg-primary', count > 0);
        mapButton.disabled = count === 0;
        selectAll.checked = count > 0 && count === checkboxes.length;
        selectAll.indeterminate = count > 0 && count < checkboxes.length;

        checkboxes.forEach(function (checkbox) {
            checkbox.closest('tr').classList.toggle('bulk-selected', checkbox.checked);
        });
    }

    selectAll.addEventListener('change', function () {
        checkboxes.forEach(function (checkbox) { checkbox.checked = selectAll.checked; });
        refreshBulkSelection();
    });
    checkboxes.forEach(function (checkbox) {
        checkbox.addEventListener('change', refreshBulkSelection);
    });
    bulkForm.addEventListener('submit', function (event) {
        const checked = checkboxes.filter(function (checkbox) { return checkbox.checked; });
        const count = checked.length;
        if (count === 0) {
            event.preventDefault();
            return;
        }

        bulkForm.querySelectorAll('.bulk-payload-input').forEach(function (input) { input.remove(); });
        for (const checkbox of checked) {
            const rowSelect = checkbox.closest('tr').querySelector('.single-site-product');
            if (!rowSelect || !rowSelect.value) {
                event.preventDefault();
                if (rowSelect) rowSelect.reportValidity();
                return;
            }

            let batch;
            try {
                batch = JSON.parse(checkbox.dataset.batch || '{}');
            } catch (error) {
                event.preventDefault();
                alert('One selected stock batch is invalid. Refresh the page and try again.');
                return;
            }
            batch.site_product_id = parseInt(rowSelect.value, 10);

            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'selected_batches[]';
            input.value = JSON.stringify(batch);
            input.className = 'bulk-payload-input';
            bulkForm.appendChild(input);
        }

        mapButton.disabled = true;
        mapButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Mapping ' + count + '…';
    });

    refreshBulkSelection();
});
</script>
