<?php
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }

    require_once __DIR__ . '/../../classes/Database.php';
    require_once __DIR__ . '/../../includes/auth.php';
    require_once __DIR__ . '/../../classes/MraEisOnboarding.php';

    $database = new Database();
    $conn = $database->getConnection();
    $auth = new Auth($conn);
    $auth->requireLogin();
    $isSuperAdmin = $auth->isSuperAdmin($_SESSION['user_id']);
    $isBranchUser = $auth->isBranchManager($_SESSION['user_id']) || $auth->isSalesAssistant($_SESSION['user_id']);
    if (!$isSuperAdmin && !$isBranchUser) {
        http_response_code(403);
        exit('Unauthorized');
    }

    $warehouseOnly = isset($_GET['warehouse_stock']) && $_GET['warehouse_stock'] === '1';
    if ($warehouseOnly && !$isSuperAdmin) {
        http_response_code(403);
        exit('Unauthorized');
    }
    $branchId = $warehouseOnly ? 7 : ($isSuperAdmin ? ($_GET['branch_id'] ?? null) : $auth->getUserBranch($_SESSION['user_id']));

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . ($warehouseOnly ? 'mra_eis_warehouse_stock_' : 'mra_eis_site_products_') . date('Ymd_His') . '.csv"');
    $out = fopen('php://output', 'w');

    try {
        $eis = new MraEisOnboarding($conn);
    } catch (Throwable $e) {
        fputcsv($out, ['Error']);
        fputcsv($out, [$e->getMessage()]);
        fclose($out);
        exit;
    }

    if ($warehouseOnly) {
        try {
            $terminalId = $_GET['terminal_id'] ?? null;
            $itemBranchId = (int)($_GET['item_branch_id'] ?? 7);
            $rows = $eis->warehouseInventoryCombined($branchId, $terminalId, $itemBranchId);
        } catch (Throwable $e) {
            fputcsv($out, ['Error']);
            fputcsv($out, [$e->getMessage()]);
            fclose($out);
            exit;
        }

        fputcsv($out, ['Barcode', 'Product Name', 'Description', 'Product Tax Category', 'Live EIS Quantity', 'Linked IMS Items', 'Synced At']);
        foreach ($rows as $row) {
            fputcsv($out, [
                $row['barcode'],
                $row['product_name'],
                $row['product_description'],
                $row['tax_category'] ?? '',
                $row['live_quantity'] === null ? 'Not in live feed' : $row['live_quantity'],
                $row['ims_item_count'],
                $row['synced_at'] ?? 'Not synced yet',
            ]);
        }
        fclose($out);
        exit;
    }

    try {
        $products = $eis->siteProducts($_GET['terminal_id'] ?? null, $_GET['site_id'] ?? null, $branchId);
    } catch (Throwable $e) {
        fputcsv($out, ['Error']);
        fputcsv($out, [$e->getMessage()]);
        fclose($out);
        exit;
    }

    fputcsv($out, ['Product Code', 'Product Name', 'Description', 'Quantity', 'Unit', 'Price', 'Site ID', 'Expiry Date', 'Minimum Stock', 'Tax Rate', 'Product Tax Category', 'Type', 'Terminal', 'Branch', 'Synced At']);
    foreach ($products as $product) {
        fputcsv($out, [
            $product['product_code'],
            $product['product_name'],
            $product['description'],
            $product['quantity'],
            $product['unit_of_measure'],
            $product['price'],
            $product['site_id'],
            $product['product_expiry_date'],
            $product['minimum_stock_level'],
            $product['tax_rate_id'],
            $product['tax_category'] ?? '',
            ((int)$product['is_product'] === 1 ? 'Product' : 'Service'),
            $product['terminal_label'],
            $product['branch_name'],
            $product['synced_at'],
        ]);
    }
    fclose($out);
    exit;
}

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

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

$warehouseOnly = isset($_GET['warehouse_stock']) && $_GET['warehouse_stock'] === '1';
if ($warehouseOnly && !$isSuperAdmin) {
    header('Location: ../../unauthorized.php');
    exit;
}
$branchId = $warehouseOnly ? 7 : ($isSuperAdmin ? ($_GET['branch_id'] ?? $_POST['branch_id'] ?? null) : $auth->getUserBranch($_SESSION['user_id']));
$showSiteProducts = $warehouseOnly && ($_GET['source'] ?? '') === 'site';
$eis = null;
$terminals = [];
$fetchTerminals = [];
$message = null;
$messageType = 'success';
if (!empty($_SESSION['eis_flash']) && is_array($_SESSION['eis_flash'])) {
    $message = (string)($_SESSION['eis_flash']['message'] ?? '');
    $messageType = ($_SESSION['eis_flash']['type'] ?? '') === 'danger' ? 'danger' : 'success';
    unset($_SESSION['eis_flash']);
}

try {
    $eis = new MraEisOnboarding($conn);
    $terminals = $eis->activatedTerminals($branchId);
    $fetchTerminals = ($warehouseOnly && $isSuperAdmin) ? $eis->activatedTerminals() : $terminals;
} catch (Throwable $e) {
    $message = $e->getMessage();
    $messageType = 'danger';
}

$pureWarehouseView = $warehouseOnly && !$showSiteProducts;
$selectionTerminals = ($showSiteProducts || $pureWarehouseView) ? $fetchTerminals : $terminals;
$productionTerminals = array_values(array_filter($fetchTerminals, function ($terminal) {
    return strtolower(trim((string)($terminal['environment'] ?? ''))) === 'production';
}));
usort($productionTerminals, function ($left, $right) {
    $updatedComparison = strcmp((string)($right['updated_at'] ?? ''), (string)($left['updated_at'] ?? ''));
    return $updatedComparison !== 0 ? $updatedComparison : ((int)$right['id'] <=> (int)$left['id']);
});
$requestedTerminalId = $_POST['terminal_id'] ?? $_GET['terminal_id'] ?? '';
if ($pureWarehouseView) {
    $selectedTerminalId = $productionTerminals[0]['id'] ?? '';
    foreach ($productionTerminals as $productionTerminal) {
        if ((string)$productionTerminal['id'] === (string)$requestedTerminalId) {
            $selectedTerminalId = $productionTerminal['id'];
            break;
        }
    }
} else {
    $selectedTerminalId = $requestedTerminalId !== ''
        ? $requestedTerminalId
        : ($isSuperAdmin ? ($selectionTerminals[0]['id'] ?? '') : '');
}
$selectedTerminal = null;

// Scopes the Warehouse Stock table's "Linked IMS Items" count/modal to one branch at a time -
// the same barcode can have items in several branches (each sync writes to whichever branch was
// chosen as destination), so this must never default to an unscoped, cross-branch count.
$itemBranches = [];
$itemBranchId = 7;
if ($pureWarehouseView) {
    try {
        $itemBranches = $eis ? $eis->branches() : [];
    } catch (Throwable $e) {
        $itemBranches = [];
    }
    $itemBranchId = (int)($_GET['item_branch_id'] ?? $_POST['item_branch_id'] ?? 7);
}

foreach ($selectionTerminals as $terminal) {
    if ((string)$terminal['id'] === (string)$selectedTerminalId) {
        $selectedTerminal = $terminal;
        break;
    }
}
if ($selectedTerminalId !== '' && !$selectedTerminal) {
    $selectedTerminalId = '';
    $selectedTerminal = null;
}

$tin = $_POST['tin'] ?? $_GET['tin'] ?? ($selectedTerminal['taxpayer_tin'] ?? '');
$siteId = $_POST['site_id'] ?? $_GET['site_id'] ?? '';
if ($selectedTerminal) {
    if (trim((string)$tin) === '') {
        $tin = $selectedTerminal['taxpayer_tin'] ?? '';
    }
    if (($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sync_products'])) || trim((string)$siteId) === '') {
        $siteId = $selectedTerminal['site_id'] ?? '';
    }
}
$warehouseCombined = [];
$syncResult = null;
// Live-refresh is opt-in (GET ?live=1 only) since it pages through the live EIS API - up to 25
// sequential HTTP requests with a 30s timeout each. Every other path (default load, after a sync,
// after a unique-code save) reads the persisted mra_eis_warehouse_stock snapshot instead, which is
// DB-only and fast. This is what was making the page hang.
$liveRequested = $warehouseOnly && $_SERVER['REQUEST_METHOD'] !== 'POST' && ($_GET['live'] ?? '') === '1';

try {
    if (!$eis) {
        throw new RuntimeException($message ?: 'MRA EIS setup failed.');
    } elseif ($warehouseOnly) {
        if (
            $_SERVER['REQUEST_METHOD'] === 'POST'
            && (isset($_POST['sync_warehouse_stock']) || isset($_POST['calibrate_barcodes']))
        ) {
            if (!$isSuperAdmin) {
                throw new RuntimeException('Only admins can sync warehouse stock into IMS.');
            }
            $syncSource = trim((string)($_POST['sync_source'] ?? 'warehouse'));
            $syncTerminalIdRaw = trim((string)($_POST['sync_terminal_id'] ?? ''));
            if ($syncTerminalIdRaw === 'warehouse') {
                if ($syncSource === 'site') {
                    throw new RuntimeException('WAREHOUSE is only a valid destination for warehouse stock sync - select a real destination terminal to sync site products.');
                }
                $syncTerminalId = null;
                $syncBranchId = 7;
                $syncBranchName = 'WAREHOUSE';
            } else {
                $syncTerminalId = (int)$syncTerminalIdRaw;
                $syncTerminal = $eis->find($syncTerminalId);
                if (!$syncTerminal || $syncTerminal['status'] !== 'activated' || trim((string)($syncTerminal['jwt_token'] ?? '')) === '') {
                    throw new RuntimeException('Select an activated EIS terminal with a stored token before syncing to IMS.');
                }
                $syncBranchId = (int)($syncTerminal['branch_id'] ?? 0);
                if ($syncBranchId <= 0) {
                    throw new RuntimeException('The selected terminal is not assigned to a valid IMS branch.');
                }
                $syncBranchName = trim((string)($syncTerminal['branch_name'] ?? '')) ?: ('Branch ' . $syncBranchId);
            }
            $syncResult = $syncSource === 'site'
                ? $eis->syncSiteTerminalProductsToBranch($syncTerminalId, $syncBranchId)
                : $eis->syncWarehouseStock($syncBranchId, $syncTerminalId);
            $message = "EIS barcode calibration for {$syncBranchName} complete: {$syncResult['created']} item(s) created, {$syncResult['removed']} removed, {$syncResult['unchanged']} barcode(s) unchanged.";
            if (!empty($syncResult['flagged_variance'])) {
                $message .= ' ' . count($syncResult['flagged_variance']) . ' barcode(s) flagged for review (stock mismatch).';
            }
            if (!empty($syncResult['flagged_fractional'])) {
                $message .= ' ' . count($syncResult['flagged_fractional']) . ' barcode(s) have fractional quantities.';
            }
            if (!empty($syncResult['flagged_capped'])) {
                $messageType = 'danger';
                $message .= ' WARNING: ' . count($syncResult['flagged_capped']) . ' barcode(s) exceeded the safety cap and were capped — please review before trusting this sync.';
            }
        } elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_unique_code'])) {
            if (!$isSuperAdmin) {
                throw new RuntimeException('Only admins can edit item unique codes.');
            }
            $editItemId = (int)($_POST['item_id'] ?? 0);
            $newUniqueCode = trim((string)($_POST['unique_code'] ?? ''));
            $newItemDetails = trim((string)($_POST['item_details'] ?? ''));
            if ($editItemId <= 0 || $newUniqueCode === '') {
                throw new RuntimeException('A valid item and unique code are required.');
            }
            require_once '../../classes/Inventory.php';
            require_once '../../classes/Logger.php';
            $itemLogger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);
            $inventory = new Inventory($conn, $itemLogger);
            if (!$inventory->updateItem($editItemId, ['unique_code' => $newUniqueCode, 'item_details' => $newItemDetails])) {
                throw new RuntimeException($inventory->getLastError() ?: 'Failed to update the unique code.');
            }
            $message = "Updated unique code for item #{$editItemId} to \"{$newUniqueCode}\".";
        }
        if ($liveRequested && $selectedTerminalId === '') {
            throw new RuntimeException('No activated Production EIS terminal with a stored token is available. Activate and confirm a Production terminal first.');
        }
        $warehouseCombined = $liveRequested
            ? $eis->warehouseInventoryCombined($branchId, $selectedTerminalId, $itemBranchId)
            : $eis->warehouseStockSnapshot(500, $itemBranchId);
    } elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sync_products'])) {
        if (!$isSuperAdmin) {
            throw new RuntimeException('Only admins can sync products from MRA.');
        }
        $result = $eis->syncSiteProducts($selectedTerminalId, $tin, $siteId);
        if ($selectedTerminal) {
            $siteId = $selectedTerminal['site_id'] ?? $siteId;
        }
        $message = 'Downloaded and saved ' . $result['saved'] . ' site product' . ($result['saved'] === 1 ? '' : 's') . '.';
    }
} catch (Throwable $e) {
    $message = $e->getMessage();
    $messageType = 'danger';
}

$products = ((!$warehouseOnly || $showSiteProducts) && $eis) ? $eis->siteProducts($selectedTerminalId ?: null, $siteId ?: null, $showSiteProducts ? null : $branchId) : [];
$exportUrl = 'mra_eis_site_products.php?export=csv&terminal_id=' . urlencode((string)$selectedTerminalId) . '&site_id=' . urlencode((string)$siteId) . '&branch_id=' . urlencode((string)$branchId) . ($warehouseOnly && !$showSiteProducts ? '&warehouse_stock=1&item_branch_id=' . urlencode((string)$itemBranchId) : '');
?>

<style>
    body { background: #f4f6f8; }
    .eis-shell { max-width: 1280px; margin: 30px auto; padding: 0 15px; }
    .eis-topbar { display: flex; justify-content: space-between; gap: 16px; align-items: center; margin-bottom: 20px; }
    .eis-title { font-weight: 800; color: #172033; }
    .eis-card { border: 0; border-radius: 8px; box-shadow: 0 2px 12px rgba(15, 23, 42, 0.08); }
    .eis-card .card-header { background: #1f2937; color: #fff; border-radius: 8px 8px 0 0; }
    .product-meta { color: #667085; font-size: 0.875rem; line-height: 1.45; }
    .table td, .table th { vertical-align: middle; }
    @media (max-width: 768px) {
        .eis-topbar { display: block; }
        .eis-topbar .btn { width: 100%; margin-top: 10px; }
    }
</style>

<div class="eis-shell">
    <?php if ($isSuperAdmin): $eisNavCurrent = 'site_products'; require __DIR__ . '/../../includes/eis_admin_nav.php'; endif; ?>

    <div class="eis-topbar">
        <div>
            <h2 class="eis-title mb-1"><i class="fas fa-boxes"></i> <?php echo $warehouseOnly ? 'Warehouse EIS Stock' : 'EIS Stock'; ?></h2>
            <p class="text-muted mb-0">
                <?php
                if ($warehouseOnly) {
                    echo 'Read approved EIS products and services saved for warehouse terminals.';
                } else {
                    echo $isSuperAdmin ? 'Download approved products and services for a terminal site from MRA EIS.' : 'View approved EIS products and services saved for your branch terminals.';
                }
                ?>
            </p>
        </div>
        <div class="d-flex flex-wrap" style="gap: 8px;">
            <?php if (!$isSuperAdmin): ?>
                <a href="<?php echo htmlspecialchars(getDashboardLink()); ?>" class="btn btn-outline-primary">
                    <i class="fas fa-tachometer-alt"></i> Dashboard
                </a>
            <?php endif; ?>
            <a href="<?php echo htmlspecialchars($exportUrl); ?>" class="btn btn-outline-success">
                <i class="fas fa-file-csv"></i> Export CSV
            </a>
        </div>
    </div>

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

    <?php if ($isSuperAdmin && !$warehouseOnly): ?>
        <div class="card eis-card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-download"></i> Download From MRA</h5>
            </div>
            <div class="card-body">
                <?php if (empty($terminals)): ?>
                    <div class="alert alert-warning mb-0">No activated MRA EIS terminals with a stored token were found. Activate and confirm a terminal first.</div>
                <?php else: ?>
                    <form method="POST">
                        <input type="hidden" name="branch_id" value="<?php echo htmlspecialchars((string)$branchId); ?>">
                        <div class="row g-3 align-items-end">
                            <div class="col-lg-4 col-md-6">
                                <label for="terminal_id" class="form-label">Activated Terminal</label>
                                <select name="terminal_id" id="terminal_id" class="form-select" required>
                                    <?php foreach ($terminals as $terminal): ?>
                                        <option
                                            value="<?php echo htmlspecialchars($terminal['id']); ?>"
                                            data-tin="<?php echo htmlspecialchars((string)($terminal['taxpayer_tin'] ?? '')); ?>"
                                            data-site-id="<?php echo htmlspecialchars((string)($terminal['site_id'] ?? '')); ?>"
                                            <?php echo (string)$selectedTerminalId === (string)$terminal['id'] ? 'selected' : ''; ?>
                                        >
                                            <?php echo htmlspecialchars($terminal['terminal_label'] . ' - ' . ($terminal['branch_name'] ?? 'Unknown branch')); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-lg-3 col-md-6">
                                <label for="tin" class="form-label">TIN</label>
                                <input type="text" class="form-control" id="tin" name="tin" required value="<?php echo htmlspecialchars($tin); ?>" placeholder="2005000001" disabled >
                            </div>
                            <div class="col-lg-3 col-md-6">
                                <label for="site_id" class="form-label">Site ID</label>
                                <input type="text" class="form-control" id="site_id" name="site_id" required readonly value="<?php echo htmlspecialchars($siteId); ?>" placeholder="Select a terminal" disabled>
                            </div>
                            <div class="col-lg-2 col-md-6">
                                <button type="submit" name="sync_products" value="1" class="btn btn-primary w-100">
                                    <i class="fas fa-cloud-download-alt"></i> Sync
                                </button>
                            </div>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    <?php else: ?>
        <div class="card eis-card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-<?php echo $warehouseOnly ? 'cloud-download-alt' : 'filter'; ?>"></i> <?php echo $warehouseOnly ? 'Read From MRA EIS' : 'Filter EIS Stock'; ?></h5>
            </div>
            <div class="card-body">
                <?php if ($warehouseOnly): ?>
                    <div class="d-flex flex-wrap" style="gap: 8px;">
                        <a href="mra_eis_site_products.php?warehouse_stock=1" class="btn btn-outline-secondary">
                            <i class="fas fa-sync-alt"></i> Refresh (cached)
                        </a>
                        <form method="POST" action="../../ajax/admin/mra_eis_fetch_source.php" class="d-flex flex-wrap align-items-end" style="gap: 8px;">
                            <div>
                                <label for="eis_data_source" class="form-label mb-1">Data source</label>
                                <select name="data_source" id="eis_data_source" class="form-select" required>
                                    <option value="warehouse">EIS Warehouse</option>
                                    <optgroup label="EIS Site Terminal Products">
                                        <?php foreach ($fetchTerminals as $terminal): ?>
                                            <option value="site:<?php echo htmlspecialchars($terminal['id']); ?>" <?php echo $showSiteProducts && (string)$selectedTerminalId === (string)$terminal['id'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($terminal['terminal_label'] . ' - ' . ($terminal['branch_name'] ?? 'Unknown branch')); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-primary" onclick="return confirm('Fetch live data from the selected EIS source?');">
                                <i class="fas fa-cloud-download-alt"></i> Fetch Live EIS Data
                            </button>
                        </form>
                        <form method="POST" action="mra_eis_site_products.php?warehouse_stock=1<?php echo $showSiteProducts ? '&amp;source=site&amp;terminal_id=' . urlencode((string)$selectedTerminalId) . '&amp;site_id=' . urlencode((string)$siteId) : ''; ?>" class="d-flex flex-wrap align-items-end" style="gap: 8px;">
                            <input type="hidden" name="sync_source" value="<?php echo $showSiteProducts ? 'site' : 'warehouse'; ?>">
                            <div>
                                <label for="sync_terminal_id" class="form-label mb-1">Destination terminal / branch</label>
                                <select name="sync_terminal_id" id="sync_terminal_id" class="form-select" required>
                                    <option value="">Select terminal and branch</option>
                                    <option value="warehouse" <?php echo !$showSiteProducts ? 'selected' : ''; ?>>WAREHOUSE</option>
                                    <?php foreach ($fetchTerminals as $terminal): ?>
                                        <option value="<?php echo htmlspecialchars($terminal['id']); ?>" <?php echo $showSiteProducts && (string)$selectedTerminalId === (string)$terminal['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($terminal['terminal_label'] . ' - ' . ($terminal['branch_name'] ?? ('Branch ' . $terminal['branch_id']))); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </form>
                    </div>
                    <div class="product-meta mt-2 mb-0">
                        The table below shows the last synced snapshot (fast, no MRA call). Use <strong>Fetch Live EIS Data</strong> to compare it against MRA's current live quantities, or <strong>Calibrate EIS Barcodes</strong> to reconcile stock for the selected destination branch. Both call MRA directly and can take a while. Site selections use <code>/utilities/get-terminal-site-products</code>; warehouse reads use <code>/stock/warehouse-inventory</code>. Calibration targets only the selected destination and never touches sold items or items assigned to other branches.
                    </div>
                <?php elseif (empty($terminals)): ?>
                    <div class="alert alert-warning mb-0">No activated EIS terminals are available for your branch yet.</div>
                <?php else: ?>
                    <form method="GET">
                        <div class="row g-3 align-items-end">
                            <div class="col-lg-5 col-md-6">
                                <label for="terminal_id" class="form-label">Branch Terminal</label>
                                <select name="terminal_id" id="terminal_id" class="form-select">
                                    <option value=""><?php echo $warehouseOnly ? 'All warehouse terminals' : 'All branch terminals'; ?></option>
                                    <?php foreach ($terminals as $terminal): ?>
                                        <option value="<?php echo htmlspecialchars($terminal['id']); ?>" <?php echo (string)$selectedTerminalId === (string)$terminal['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($terminal['terminal_label']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-lg-5 col-md-6">
                                <label for="site_id" class="form-label">Site ID</label>
                                <input type="text" class="form-control" id="site_id" name="site_id" value="<?php echo htmlspecialchars($siteId); ?>" placeholder="Optional">
                            </div>
                            <div class="col-lg-2 col-md-12">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="fas fa-search"></i> View
                                </button>
                            </div>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>

    <?php if ($warehouseOnly && !$showSiteProducts): ?>
        <div class="card eis-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="fas fa-warehouse"></i> Warehouse Stock</h5>
                <span class="badge bg-light text-dark"><?php echo count($warehouseCombined); ?> barcode(s)</span>
            </div>
            <div class="card-body">
                <form method="GET" class="row g-2 align-items-end mb-3">
                    <input type="hidden" name="warehouse_stock" value="1">
                    <?php if ($liveRequested): ?><input type="hidden" name="live" value="1"><?php endif; ?>
                    <?php if ($selectedTerminalId !== ''): ?><input type="hidden" name="terminal_id" value="<?php echo htmlspecialchars((string)$selectedTerminalId); ?>"><?php endif; ?>
                    <div class="col-md-4">
                        <label for="item_branch_id" class="form-label mb-1">Linked IMS Items - Branch</label>
                        <select name="item_branch_id" id="item_branch_id" class="form-select form-select-sm" onchange="this.form.submit()">
                            <option value="7" <?php echo $itemBranchId === 7 ? 'selected' : ''; ?>>WAREHOUSE</option>
                            <?php foreach ($itemBranches as $branch): ?>
                                <?php if ((int)$branch['branch_id'] === 7) { continue; } ?>
                                <option value="<?php echo (int)$branch['branch_id']; ?>" <?php echo $itemBranchId === (int)$branch['branch_id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($branch['branch_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-8">
                        <div class="product-meta mb-0">Shows this table's Linked IMS Items count/edits for one branch at a time - never combined across branches.</div>
                    </div>
                </form>
                <?php if (empty($warehouseCombined)): ?>
                    <div class="alert alert-info mb-0">
                        No warehouse stock rows were returned from EIS. Use <strong>Troubleshoot</strong> above if this is unexpected.
                    </div>
                <?php else: ?>
                    <div class="product-meta mb-2">
                        Synced Qty is the quantity from the last sync/refresh (DB snapshot, fast).
                        <?php if ($liveRequested): ?>
                            Live EIS Qty is what MRA reports right now.
                        <?php endif; ?>
                        Linked IMS Items is how many matching items currently exist in the selected branch from the last sync; a mismatch usually means stock added outside the sync is blocking a reduction. Click a <strong>Linked IMS Items</strong> count to review or edit those items' unique codes.
                    </div>
                    <div class="table-responsive">
                        <table id="warehouseStockTable" class="table table-striped table-bordered mb-0" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th>Barcode</th>
                                    <th>Product Name</th>
                                    <th>Description</th>
                                    <th>Product Tax Category</th>
                                    <th>Synced Qty</th>
                                    <?php if ($liveRequested): ?>
                                        <th>Live EIS Qty</th>
                                    <?php endif; ?>
                                    <th>Linked IMS Items</th>
                                    <th>Synced At</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($warehouseCombined as $row): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($row['barcode']); ?></td>
                                        <td><?php echo htmlspecialchars($row['product_name']); ?></td>
                                        <td><?php echo htmlspecialchars($row['product_description']); ?></td>
                                        <td><?php echo htmlspecialchars($row['tax_category'] ?: 'N/A'); ?></td>
                                        <td><?php echo $row['synced_quantity'] !== null ? number_format((float)$row['synced_quantity'], 2) : '<span class="text-muted">Not synced yet</span>'; ?></td>
                                        <?php if ($liveRequested): ?>
                                            <td><?php echo $row['live_quantity'] === null ? '<span class="text-muted">Not in live feed</span>' : htmlspecialchars($row['live_quantity']); ?></td>
                                        <?php endif; ?>
                                        <td>
                                            <?php
                                            $syncedQty = $row['synced_quantity'] !== null ? (int)floor((float)$row['synced_quantity']) : null;
                                            $linked = (int)$row['ims_item_count'];
                                            $badgeClass = ($syncedQty === null || $linked !== $syncedQty) ? 'bg-warning text-dark' : 'bg-success';
                                            ?>
                                            <?php if ($linked > 0): ?>
                                                <button type="button" class="badge <?php echo $badgeClass; ?> border-0 linked-items-trigger" data-stock-id="<?php echo (int)$row['stock_id']; ?>" data-barcode="<?php echo htmlspecialchars($row['barcode']); ?>" data-branch-id="<?php echo (int)$itemBranchId; ?>" style="cursor: pointer;" title="Edit unique codes">
                                                    <?php echo $linked; ?> <i class="fas fa-pen ms-1"></i>
                                                </button>
                                            <?php else: ?>
                                                <span class="badge <?php echo $badgeClass; ?>"><?php echo $linked; ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo $row['synced_at'] ? htmlspecialchars($row['synced_at']) : '<span class="text-muted">Not synced yet</span>'; ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <div class="modal fade" id="linkedItemsModal" tabindex="-1" aria-hidden="true">
                        <div class="modal-dialog modal-lg modal-dialog-scrollable">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="linkedItemsModalTitle">IMS Items</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                    <div id="linkedItemsBulkSection" class="border rounded p-3 mb-3 bg-light d-none">
                                        <h6 class="mb-2"><i class="fas fa-file-excel"></i> Update Codes via Excel <span class="text-muted fw-normal">- <span id="linkedItemsBulkBranchName"></span></span></h6>
                                        <div class="row g-2 align-items-end">
                                            <div class="col-md-7">
                                                <label for="linkedItemsBulkFile" class="form-label mb-1">File (.xlsx, .xls, .csv)</label>
                                                <input type="file" id="linkedItemsBulkFile" class="form-control form-control-sm" accept=".xlsx,.xls,.csv">
                                            </div>
                                            <div class="col-md-5 d-flex" style="gap: 6px;">
                                                <button type="button" id="linkedItemsDownloadTemplate" class="btn btn-sm btn-outline-secondary w-100">Template</button>
                                                <button type="button" id="linkedItemsBulkUpload" class="btn btn-sm btn-primary w-100">Upload</button>
                                            </div>
                                        </div>
                                        <div class="product-meta mt-2 mb-0">
                                            Download the template, fill in <strong>unique_code</strong> and optionally <strong>item_details</strong>, then re-upload. Only this barcode's items in this branch are updated - other branches are never touched.
                                        </div>
                                        <div id="linkedItemsBulkResult" class="mt-2"></div>
                                    </div>
                                    <div id="linkedItemsModalBody">
                                        <div class="text-center text-muted py-4"><i class="fas fa-spinner fa-spin"></i> Loading...</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    <?php else: ?>
    <div class="card eis-card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-list"></i> Saved Site Products</h5>
            <span class="badge bg-light text-dark"><?php echo count($products); ?> total</span>
        </div>
        <div class="card-body">
            <?php if (empty($products)): ?>
                <div class="alert alert-info mb-0">No site products are saved for the current filter.</div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped table-bordered mb-0">
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th>Type</th>
                                <th>Qty</th>
                                <th>Price</th>
                                <th>Tax</th>
                                <th>Product Tax Category</th>
                                <th>Site</th>
                                <th>Terminal</th>
                                <th>Synced</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($products as $product): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo htmlspecialchars($product['product_name']); ?></strong>
                                        <div class="product-meta">
                                            Code: <?php echo htmlspecialchars($product['product_code']); ?><br>
                                            <?php echo htmlspecialchars($product['description'] ?: 'No description'); ?>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php echo (int)$product['is_product'] === 1 ? 'primary' : 'secondary'; ?>">
                                            <?php echo (int)$product['is_product'] === 1 ? 'Product' : 'Service'; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php echo number_format((float)$product['quantity'], 2); ?>
                                        <div class="product-meta"><?php echo htmlspecialchars($product['unit_of_measure'] ?: 'Unit'); ?></div>
                                    </td>
                                    <td><?php echo number_format((float)$product['price'], 2); ?></td>
                                    <td><?php echo htmlspecialchars($product['tax_rate_id'] ?: 'N/A'); ?></td>
                                    <td><?php echo htmlspecialchars($product['tax_category'] ?: 'N/A'); ?></td>
                                    <td><?php echo htmlspecialchars($product['site_id']); ?></td>
                                    <td>
                                        <?php echo htmlspecialchars($product['terminal_label'] ?: 'Unknown'); ?>
                                        <div class="product-meta"><?php echo htmlspecialchars($product['branch_name'] ?: 'Unknown branch'); ?></div>
                                    </td>
                                    <td><?php echo htmlspecialchars($product['synced_at']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var syncButton = document.querySelector('button[name="sync_products"]');
    if (!syncButton) {
        return;
    }

    var form = syncButton.closest('form');
    if (!form) {
        return;
    }

    var terminalSelect = form.querySelector('select[name="terminal_id"]');
    var tinInput = form.querySelector('input[name="tin"]');
    var siteInput = form.querySelector('input[name="site_id"]');

    function applyTerminalDetails() {
        var option = terminalSelect && terminalSelect.options[terminalSelect.selectedIndex];
        if (!option) {
            return;
        }

        if (tinInput) {
            tinInput.value = option.getAttribute('data-tin') || '';
        }
        if (siteInput) {
            siteInput.value = option.getAttribute('data-site-id') || '';
        }
    }

    if (terminalSelect) {
        terminalSelect.addEventListener('change', applyTerminalDetails);
        applyTerminalDetails();
    }
});
</script>

<?php if ($warehouseOnly && !empty($warehouseCombined)): ?>
<script>
$(document).ready(function() {
    $('#warehouseStockTable').DataTable({
        pageLength: 25,
        order: [],
        language: {
            search: 'Search warehouse stock:',
            emptyTable: 'No warehouse stock rows were returned from EIS.'
        }
    });

    var linkedItemsModalEl = document.getElementById('linkedItemsModal');
    var linkedItemsModal = linkedItemsModalEl ? bootstrap.Modal.getOrCreateInstance(linkedItemsModalEl) : null;
    var linkedItemsModalTitle = document.getElementById('linkedItemsModalTitle');
    var linkedItemsModalBody = document.getElementById('linkedItemsModalBody');
    var linkedItemsBulkSection = document.getElementById('linkedItemsBulkSection');
    var linkedItemsBulkBranchName = document.getElementById('linkedItemsBulkBranchName');
    var linkedItemsBulkFile = document.getElementById('linkedItemsBulkFile');
    var linkedItemsBulkResult = document.getElementById('linkedItemsBulkResult');
    var currentStockId = null;
    var currentBarcode = '';
    var currentBranchId = null;
    var currentItems = [];

    function escapeHtml(value) {
        return $('<div>').text(value == null ? '' : value).html();
    }

    function renderLinkedItems(items) {
        var rows = items.map(function (item) {
            return '<tr>' +
                '<td style="min-width: 200px;">' +
                    '<form method="POST" action="mra_eis_site_products.php?warehouse_stock=1" class="d-grid" style="gap: 6px;">' +
                        '<input type="hidden" name="item_id" value="' + escapeHtml(item.item_id) + '">' +
                        '<input type="text" name="unique_code" class="form-control form-control-sm" value="' + escapeHtml(item.unique_code) + '" required>' +
                        '<textarea name="item_details" class="form-control form-control-sm" rows="2" placeholder="Item details">' + escapeHtml(item.item_details || '') + '</textarea>' +
                        '<button type="submit" name="save_unique_code" value="1" class="btn btn-sm btn-outline-primary" title="Save"><i class="fas fa-save"></i></button>' +
                    '</form>' +
                '</td>' +
                '<td>' + escapeHtml(item.item_name) + '</td>' +
                '<td>' + escapeHtml(item.tax_category || 'N/A') + '</td>' +
                '<td>' + escapeHtml(item.created_at) + '</td>' +
            '</tr>';
        }).join('');

        linkedItemsModalBody.innerHTML = '<div class="table-responsive"><table class="table table-sm table-bordered mb-0">' +
            '<thead><tr><th>Unique Code / Item Details</th><th>Item Name</th><th>Tax Category</th><th>Added</th></tr></thead>' +
            '<tbody>' + rows + '</tbody></table></div>';
    }

    document.addEventListener('click', function (e) {
        var trigger = e.target.closest('.linked-items-trigger');
        if (!trigger || !linkedItemsModal) {
            return;
        }

        var stockId = trigger.getAttribute('data-stock-id');
        var barcode = trigger.getAttribute('data-barcode');
        var branchId = trigger.getAttribute('data-branch-id');
        currentStockId = stockId;
        currentBarcode = barcode;
        currentBranchId = branchId;
        linkedItemsModalTitle.textContent = 'IMS Items — Barcode ' + barcode;
        linkedItemsModalBody.innerHTML = '<div class="text-center text-muted py-4"><i class="fas fa-spinner fa-spin"></i> Loading...</div>';
        linkedItemsBulkSection.classList.add('d-none');
        linkedItemsBulkResult.innerHTML = '';
        linkedItemsBulkFile.value = '';
        linkedItemsModal.show();

        $.get('../../ajax/admin/mra_eis_linked_items.php', { stock_id: stockId, branch_id: branchId }, function (response) {
            if (!response || !response.success) {
                linkedItemsModalBody.innerHTML = '<div class="alert alert-danger mb-0">' + escapeHtml((response && response.error) || 'Unable to load linked items.') + '</div>';
                return;
            }
            if (!response.items.length) {
                linkedItemsModalBody.innerHTML = '<div class="alert alert-info mb-0">No linked IMS items found for this branch.</div>';
                return;
            }

            currentItems = response.items;
            renderLinkedItems(currentItems);
            linkedItemsBulkBranchName.textContent = currentItems[0].branch_name || ('Branch ' + currentItems[0].branch_id);
            linkedItemsBulkSection.classList.remove('d-none');
        }, 'json').fail(function () {
            linkedItemsModalBody.innerHTML = '<div class="alert alert-danger mb-0">Server error while loading linked items.</div>';
        });
    });

    document.getElementById('linkedItemsDownloadTemplate').addEventListener('click', function () {
        var csv = 'item_id,item_name,unique_code,item_details\n' + currentItems.map(function (item) {
            var name = String(item.item_name || '').replace(/"/g, '""');
            var code = String(item.unique_code || '').replace(/"/g, '""');
            var details = String(item.item_details || '').replace(/"/g, '""');
            return item.item_id + ',"' + name + '","' + code + '","' + details + '"';
        }).join('\n');

        var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        var link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'unique_codes_' + currentBarcode + '_branch' + currentBranchId + '.csv';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });

    document.getElementById('linkedItemsBulkUpload').addEventListener('click', function () {
        var file = linkedItemsBulkFile.files[0];
        if (!file || !currentStockId || !currentBranchId) {
            linkedItemsBulkResult.innerHTML = '<div class="alert alert-warning mb-0 py-1 px-2">Select a file first.</div>';
            return;
        }

        var formData = new FormData();
        formData.append('stock_id', currentStockId);
        formData.append('branch_id', currentBranchId);
        formData.append('excel_file', file);

        linkedItemsBulkResult.innerHTML = '<div class="text-muted"><i class="fas fa-spinner fa-spin"></i> Uploading...</div>';

        $.ajax({
            url: '../../ajax/admin/mra_eis_bulk_unique_code.php',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json'
        }).done(function (response) {
            if (!response || !response.success) {
                linkedItemsBulkResult.innerHTML = '<div class="alert alert-danger mb-0 py-1 px-2">' + escapeHtml((response && response.error) || 'Upload failed.') + '</div>';
                return;
            }
            var summary = response.updated + ' item(s) updated.';
            if (response.skipped && response.skipped.length) {
                summary += ' ' + response.skipped.length + ' row(s) skipped: ' + response.skipped.map(escapeHtml).join('; ');
            }
            linkedItemsBulkResult.innerHTML = '<div class="alert alert-success mb-0 py-1 px-2">' + summary + '</div>';

            $.get('../../ajax/admin/mra_eis_linked_items.php', { stock_id: currentStockId, branch_id: currentBranchId }, function (refreshed) {
                if (refreshed && refreshed.success) {
                    currentItems = refreshed.items;
                    renderLinkedItems(currentItems);
                }
            }, 'json');
        }).fail(function () {
            linkedItemsBulkResult.innerHTML = '<div class="alert alert-danger mb-0 py-1 px-2">Server error while uploading the file.</div>';
        });
    });
});
</script>
<?php endif; ?>

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