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

<div class="content-wrapper">
<section class="content pt-3">
<div class="container-fluid pb-5">

<!-- ══════════════════════════════════════════════════
     PAGE HEADER
══════════════════════════════════════════════════ -->
<div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
    <div>
        <h3 class="mb-1 fw-bold">
            <i class="bi bi-archive-fill me-2 text-primary"></i>
            <?= __('inventory.title', 'Inventory Management') ?>
        </h3>
        <p class="text-muted mb-0 small"><?= __('inventory.subtitle', 'Real-time stock levels, alerts, and adjustments for all products') ?></p>
    </div>
    <div class="d-flex gap-2">
        <a href="/admin/products/create" class="btn btn-sm btn-outline-primary">
            <i class="bi bi-plus-lg me-1"></i>
            <?= __('inventory.add_product', 'Add Product') ?>
        </a>
        <a href="/admin/products" class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-box-seam me-1"></i>
            <?= __('inventory.manage_products', 'Products') ?>
        </a>
    </div>
</div>

<!-- ══════════════════════════════════════════════════
     KPI CARDS
══════════════════════════════════════════════════ -->
<div class="row g-3 mb-4">

    <!-- Total Products -->
    <div class="col-6 col-md-4 col-xl-2">
        <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #0d6efd !important">
            <div class="card-body px-3 py-3">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div class="rounded-circle d-flex align-items-center justify-content-center bg-primary-subtle"
                         style="width:38px;height:38px">
                        <i class="bi bi-box-seam-fill fs-6 text-primary"></i>
                    </div>
                </div>
                <div class="fw-bold fs-2 lh-1 mb-1"><?= $totalProducts ?></div>
                <div class="text-muted small"><?= __('inventory.kpi.total_products', 'Total Products') ?></div>
                <div class="text-muted" style="font-size:.72rem"><?= $activeProducts ?> <?= __('inventory.kpi.active', 'active') ?></div>
            </div>
        </div>
    </div>

    <!-- Total Units -->
    <div class="col-6 col-md-4 col-xl-2">
        <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #198754 !important">
            <div class="card-body px-3 py-3">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div class="rounded-circle d-flex align-items-center justify-content-center bg-success-subtle"
                         style="width:38px;height:38px">
                        <i class="bi bi-stack fs-6 text-success"></i>
                    </div>
                </div>
                <div class="fw-bold fs-2 lh-1 mb-1"><?= number_format($totalUnits) ?></div>
                <div class="text-muted small"><?= __('inventory.kpi.total_units', 'Total Units') ?></div>
                <div class="text-muted" style="font-size:.72rem"><?= __('inventory.kpi.in_stock', 'In stock') ?></div>
            </div>
        </div>
    </div>

    <!-- Stock Value -->
    <div class="col-6 col-md-4 col-xl-2">
        <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #6f42c1 !important">
            <div class="card-body px-3 py-3">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div class="rounded-circle d-flex align-items-center justify-content-center bg-purple-subtle"
                         style="width:38px;height:38px;background:rgba(111,66,193,.1)!important">
                        <i class="bi bi-currency-exchange fs-6" style="color:#6f42c1"></i>
                    </div>
                </div>
                <div class="fw-bold fs-2 lh-1 mb-1" style="font-size:1.4rem!important"><?= number_format($totalValue) ?></div>
                <div class="text-muted small"><?= __('inventory.kpi.stock_value', 'Stock Value') ?></div>
                <div class="text-muted" style="font-size:.72rem"><?= __('inventory.kpi.estimated', 'Estimated') ?></div>
            </div>
        </div>
    </div>

    <!-- Low Stock -->
    <div class="col-6 col-md-4 col-xl-2">
        <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #ffc107 !important">
            <div class="card-body px-3 py-3">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div class="rounded-circle d-flex align-items-center justify-content-center bg-warning-subtle"
                         style="width:38px;height:38px">
                        <i class="bi bi-exclamation-triangle-fill fs-6 text-warning"></i>
                    </div>
                </div>
                <div class="fw-bold fs-2 lh-1 mb-1"><?= $lowStock ?></div>
                <div class="text-muted small"><?= __('inventory.kpi.low_stock', 'Low Stock') ?></div>
                <div class="text-muted" style="font-size:.72rem"><?= __('inventory.kpi.below_alert', 'Below alert threshold') ?></div>
            </div>
        </div>
    </div>

    <!-- Out of Stock -->
    <div class="col-6 col-md-4 col-xl-2">
        <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #dc3545 !important">
            <div class="card-body px-3 py-3">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div class="rounded-circle d-flex align-items-center justify-content-center bg-danger-subtle"
                         style="width:38px;height:38px">
                        <i class="bi bi-x-circle-fill fs-6 text-danger"></i>
                    </div>
                </div>
                <div class="fw-bold fs-2 lh-1 mb-1"><?= $outOfStock ?></div>
                <div class="text-muted small"><?= __('inventory.kpi.out_of_stock', 'Out of Stock') ?></div>
                <div class="text-muted" style="font-size:.72rem"><?= __('inventory.kpi.needs_restock', 'Needs restock') ?></div>
            </div>
        </div>
    </div>

    <!-- In Stock (healthy) -->
    <div class="col-6 col-md-4 col-xl-2">
        <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #0dcaf0 !important">
            <div class="card-body px-3 py-3">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div class="rounded-circle d-flex align-items-center justify-content-center bg-info-subtle"
                         style="width:38px;height:38px">
                        <i class="bi bi-check-circle-fill fs-6 text-info"></i>
                    </div>
                </div>
                <div class="fw-bold fs-2 lh-1 mb-1"><?= max(0, $totalProducts - $lowStock - $outOfStock) ?></div>
                <div class="text-muted small"><?= __('inventory.kpi.healthy', 'Healthy Stock') ?></div>
                <div class="text-muted" style="font-size:.72rem"><?= __('inventory.kpi.above_alert', 'Above alert threshold') ?></div>
            </div>
        </div>
    </div>

</div>

<!-- ══════════════════════════════════════════════════
     FILTERS + SEARCH
══════════════════════════════════════════════════ -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-body py-3">
        <div class="d-flex flex-wrap gap-2 align-items-center">

            <span class="text-muted small fw-semibold me-1"><?= __('inventory.filter_by', 'Filter:') ?></span>

            <button type="button" class="btn btn-sm btn-outline-secondary inv-filter active" data-filter="all">
                <i class="bi bi-list-ul me-1"></i>
                <?= __('inventory.filter.all', 'All') ?>
                <span class="badge bg-secondary ms-1 rounded-pill"><?= $totalProducts ?></span>
            </button>
            <button type="button" class="btn btn-sm btn-outline-danger inv-filter" data-filter="out">
                <i class="bi bi-x-circle-fill me-1"></i>
                <?= __('inventory.filter.out_of_stock', 'Out of Stock') ?>
                <span class="badge bg-danger ms-1 rounded-pill"><?= $outOfStock ?></span>
            </button>
            <button type="button" class="btn btn-sm btn-outline-warning inv-filter" data-filter="low">
                <i class="bi bi-exclamation-triangle-fill me-1"></i>
                <?= __('inventory.filter.low_stock', 'Low Stock') ?>
                <span class="badge bg-warning ms-1 rounded-pill"><?= $lowStock ?></span>
            </button>
            <button type="button" class="btn btn-sm btn-outline-success inv-filter" data-filter="ok">
                <i class="bi bi-check-circle-fill me-1"></i>
                <?= __('inventory.filter.healthy', 'Healthy') ?>
                <span class="badge bg-success ms-1 rounded-pill"><?= max(0, $totalProducts - $lowStock - $outOfStock) ?></span>
            </button>

            <div class="ms-auto d-flex gap-2">
                <div class="input-group input-group-sm" style="width:230px">
                    <span class="input-group-text bg-white border-end-0"><i class="bi bi-search text-muted"></i></span>
                    <input type="text" id="invSearch" class="form-control border-start-0"
                           placeholder="<?= __('inventory.search_placeholder', 'Search by name, SKU or barcode...') ?>">
                </div>
            </div>

        </div>
    </div>
</div>

<!-- ══════════════════════════════════════════════════
     INVENTORY TABLE
══════════════════════════════════════════════════ -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
        <h6 class="mb-0 fw-semibold">
            <i class="bi bi-table me-2 text-muted"></i>
            <span id="invTableTitle"><?= __('inventory.table.title', 'All Products — Stock Details') ?></span>
        </h6>
        <span class="badge bg-secondary rounded-pill" id="invTableCount"><?= $totalProducts ?></span>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0" id="invTable">
                <thead class="table-light">
                    <tr>
                        <th class="ps-3" style="width:52px"><?= __('inventory.table.image', 'Image') ?></th>
                        <th><?= __('inventory.table.product', 'Product') ?></th>
                        <th><?= __('inventory.table.price', 'Price') ?></th>
                        <th><?= __('inventory.table.stock', 'Stock') ?></th>
                        <th><?= __('inventory.table.alert', 'Alert') ?></th>
                        <th><?= __('inventory.table.value', 'Value') ?></th>
                        <th><?= __('inventory.table.status', 'Status') ?></th>
                        <th class="text-center pe-3"><?= __('inventory.table.actions', 'Actions') ?></th>
                    </tr>
                </thead>
                <tbody>

                <?php if (empty($rows)): ?>
                <tr>
                    <td colspan="8">
                        <div class="text-center py-5">
                            <i class="bi bi-archive display-4 d-block mb-3 opacity-25"></i>
                            <h5 class="fw-semibold mb-1"><?= __('inventory.empty.title', 'No products found') ?></h5>
                            <p class="text-muted small mb-3"><?= __('inventory.empty.text', 'Add your first product to track inventory.') ?></p>
                            <a href="/admin/products/create" class="btn btn-primary btn-sm">
                                <i class="bi bi-plus-lg me-1"></i><?= __('inventory.add_product', 'Add Product') ?>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php else: ?>

                <?php foreach ($rows as $row):
                    $stockStatus  = $row['stock_status'];
                    $stockColor   = $stockStatus === 'out' ? 'danger' : ($stockStatus === 'low' ? 'warning' : 'success');
                    $stockIcon    = $stockStatus === 'out' ? 'bi-x-circle-fill' : ($stockStatus === 'low' ? 'bi-exclamation-triangle-fill' : 'bi-check-circle-fill');
                    $stockLabel   = $stockStatus === 'out' ? __('inventory.status.out','Out of Stock') : ($stockStatus === 'low' ? __('inventory.status.low','Low Stock') : __('inventory.status.ok','In Stock'));
                    $prdStatus    = $row['status'] === 'active' ? 'success' : 'secondary';
                    $prdStsLabel  = $row['status'] === 'active' ? __('actions.active','Active') : __('actions.inactive','Inactive');
                    // Stock progress bar width (max 100%)
                    $alertQty     = max(1, $row['stock_alert']);
                    $progressQty  = $row['stock_quantity'];
                    $progressMax  = max($alertQty * 4, $progressQty, 1);
                    $progressPct  = min(100, round(($progressQty / $progressMax) * 100));
                    $imgSrc       = $row['featured_image'] ? htmlspecialchars($row['featured_image']) : '/public/assets/images/no-image.png';
                ?>
                <tr class="inv-row"
                    data-stock-status="<?= $stockStatus ?>"
                    data-search="<?= htmlspecialchars(strtolower($row['title'].' '.($row['sku'] ?? '').' '.($row['barcode'] ?? ''))) ?>"
                    data-product-id="<?= $row['id'] ?>"
                    data-has-variants="<?= $row['has_variants'] ? '1' : '0' ?>">

                    <!-- Image -->
                    <td class="ps-3">
                        <img src="<?= $imgSrc ?>"
                             alt="<?= htmlspecialchars($row['title']) ?>"
                             class="rounded" style="width:42px;height:42px;object-fit:cover"
                             onerror="this.src='/public/assets/images/no-image.png'">
                    </td>

                    <!-- Product Info -->
                    <td>
                        <div class="fw-semibold small text-dark lh-sm mb-1" style="max-width:220px">
                            <?= htmlspecialchars($row['title']) ?>
                        </div>
                        <?php if ($row['sku'] !== ''): ?>
                        <span class="badge bg-light text-dark border me-1" style="font-size:.68rem">
                            <i class="bi bi-upc me-1"></i><?= htmlspecialchars($row['sku']) ?>
                        </span>
                        <?php endif; ?>
                        <?php if ($row['barcode'] !== ''): ?>
                        <span class="badge bg-light text-dark border" style="font-size:.68rem">
                            <i class="bi bi-123 me-1"></i><?= htmlspecialchars($row['barcode']) ?>
                        </span>
                        <?php endif; ?>
                        <?php if ($row['has_variants']): ?>
                        <div class="mt-1">
                            <button type="button"
                                    class="btn btn-link btn-sm text-decoration-none p-0 text-muted variant-toggle"
                                    style="font-size:.72rem"
                                    data-product-id="<?= $row['id'] ?>">
                                <i class="bi bi-diagram-3 me-1"></i>
                                <?= count($row['variant_stock']) ?> <?= __('inventory.variants', 'variants') ?>
                                <i class="bi bi-chevron-down ms-1 toggle-arrow"></i>
                            </button>
                        </div>
                        <?php endif; ?>
                    </td>

                    <!-- Price -->
                    <td>
                        <?php if ($row['sale_price'] > 0 && $row['sale_price'] < $row['price']): ?>
                        <div class="fw-bold small text-success"><?= number_format($row['sale_price']) ?></div>
                        <div class="text-muted text-decoration-line-through" style="font-size:.72rem"><?= number_format($row['price']) ?></div>
                        <?php else: ?>
                        <div class="fw-bold small"><?= number_format($row['price']) ?></div>
                        <?php endif; ?>
                    </td>

                    <!-- Stock with progress bar -->
                    <td style="min-width:130px">
                        <div class="d-flex align-items-center gap-2 mb-1">
                            <span class="fw-bold fs-6 lh-1 text-<?= $stockColor ?>"
                                  id="stock-display-<?= $row['id'] ?>">
                                <?= number_format($row['stock_quantity']) ?>
                            </span>
                            <span class="text-muted" style="font-size:.72rem"><?= __('inventory.units', 'units') ?></span>
                            <?php if (!$row['has_variants']): ?>
                            <button type="button"
                                    class="btn btn-link btn-sm p-0 text-muted ms-1 stock-edit-btn"
                                    style="font-size:.75rem"
                                    data-product-id="<?= $row['id'] ?>"
                                    data-current="<?= $row['stock_quantity'] ?>"
                                    data-has-variants="0"
                                    title="<?= __('inventory.adjust_stock', 'Adjust Stock') ?>">
                                <i class="bi bi-pencil-square"></i>
                            </button>
                            <?php endif; ?>
                        </div>
                        <div class="progress" style="height:4px;width:90px">
                            <div class="progress-bar bg-<?= $stockColor ?>"
                                 style="width:<?= $progressPct ?>%"></div>
                        </div>
                    </td>

                    <!-- Alert Threshold -->
                    <td>
                        <span class="badge bg-warning-subtle text-warning border border-warning-subtle px-2"
                              style="font-size:.72rem">
                            <i class="bi bi-bell me-1"></i><?= $row['stock_alert'] ?>
                        </span>
                    </td>

                    <!-- Stock Value -->
                    <td>
                        <span class="fw-semibold small"><?= number_format($row['stock_value']) ?></span>
                    </td>

                    <!-- Status -->
                    <td>
                        <span class="badge bg-<?= $stockColor ?>-subtle text-<?= $stockColor ?> border border-<?= $stockColor ?>-subtle px-2 py-1 d-block mb-1"
                              style="font-size:.7rem;width:fit-content">
                            <i class="bi <?= $stockIcon ?> me-1"></i><?= $stockLabel ?>
                        </span>
                        <span class="badge bg-<?= $prdStatus ?>-subtle text-<?= $prdStatus ?> border border-<?= $prdStatus ?>-subtle px-2"
                              style="font-size:.68rem;width:fit-content">
                            <?= $prdStsLabel ?>
                        </span>
                    </td>

                    <!-- Actions -->
                    <td class="text-center pe-3">
                        <div class="d-flex gap-1 justify-content-center">
                            <a href="/admin/products/edit/<?= $row['id'] ?>"
                               class="btn btn-sm btn-outline-primary"
                               title="<?= __('inventory.action.edit', 'Edit Product') ?>">
                                <i class="bi bi-pencil"></i>
                            </a>
                            <a href="/admin/orders?product_id=<?= $row['id'] ?>"
                               class="btn btn-sm btn-outline-secondary"
                               title="<?= __('inventory.action.view_orders', 'View Orders') ?>">
                                <i class="bi bi-bag-check"></i>
                            </a>
                            <?php if ($row['has_variants']): ?>
                            <button type="button"
                                    class="btn btn-sm btn-outline-warning stock-edit-btn"
                                    data-product-id="<?= $row['id'] ?>"
                                    data-has-variants="1"
                                    title="<?= __('inventory.action.adjust_variants', 'Adjust Variant Stock') ?>">
                                <i class="bi bi-sliders2"></i>
                            </button>
                            <?php else: ?>
                            <button type="button"
                                    class="btn btn-sm btn-outline-warning stock-edit-btn"
                                    data-product-id="<?= $row['id'] ?>"
                                    data-current="<?= $row['stock_quantity'] ?>"
                                    data-has-variants="0"
                                    title="<?= __('inventory.action.adjust_stock', 'Adjust Stock') ?>">
                                <i class="bi bi-sliders2"></i>
                            </button>
                            <?php endif; ?>
                        </div>
                    </td>

                </tr>

                <!-- Variants sub-rows (hidden by default) -->
                <?php if ($row['has_variants'] && !empty($row['variant_stock'])): ?>
                <tr class="variant-details-row d-none" id="variants-<?= $row['id'] ?>">
                    <td colspan="8" class="p-0 bg-light">
                        <div class="p-3">
                            <div class="row g-2">
                                <?php foreach ($row['variant_stock'] as $vIdx => $vs):
                                    $vQty    = (int)$vs['quantity'];
                                    $vAlert  = $row['stock_alert'];
                                    $vStatus = $vQty === 0 ? 'danger' : ($vQty <= $vAlert ? 'warning' : 'success');
                                    $sizeLabel  = $vs['size']  ?? '—';
                                    $colorLabel = $vs['color'] ?? '—';
                                ?>
                                <div class="col-6 col-md-4 col-lg-3">
                                    <div class="card border shadow-none p-2" style="border-left:3px solid var(--bs-<?= $vStatus ?>)!important">
                                        <div class="d-flex justify-content-between align-items-start mb-1">
                                            <div style="font-size:.78rem;font-weight:600">
                                                <?php if ($sizeLabel !== '—'): ?>
                                                <span class="badge bg-secondary me-1" style="font-size:.65rem"><?= htmlspecialchars($sizeLabel) ?></span>
                                                <?php endif; ?>
                                                <?php if ($colorLabel !== '—'): ?>
                                                <span><?= htmlspecialchars($colorLabel) ?></span>
                                                <?php endif; ?>
                                            </div>
                                            <button type="button"
                                                    class="btn btn-link btn-sm p-0 text-muted variant-stock-edit"
                                                    data-product-id="<?= $row['id'] ?>"
                                                    data-size="<?= htmlspecialchars($vs['size'] ?? '') ?>"
                                                    data-color="<?= htmlspecialchars($vs['color'] ?? '') ?>"
                                                    data-current="<?= $vQty ?>"
                                                    title="<?= __('inventory.adjust_stock', 'Adjust Stock') ?>">
                                                <i class="bi bi-pencil" style="font-size:.7rem"></i>
                                            </button>
                                        </div>
                                        <div class="d-flex align-items-center gap-2">
                                            <span class="fw-bold text-<?= $vStatus ?> variant-qty"
                                                  data-product-id="<?= $row['id'] ?>"
                                                  data-size="<?= htmlspecialchars($vs['size'] ?? '') ?>"
                                                  data-color="<?= htmlspecialchars($vs['color'] ?? '') ?>">
                                                <?= $vQty ?>
                                            </span>
                                            <span class="text-muted" style="font-size:.68rem"><?= __('inventory.units','units') ?></span>
                                        </div>
                                        <div class="progress mt-1" style="height:3px">
                                            <?php
                                            $vMax  = max($vAlert * 4, $vQty, 1);
                                            $vPct  = min(100, round(($vQty / $vMax) * 100));
                                            ?>
                                            <div class="progress-bar bg-<?= $vStatus ?>" style="width:<?= $vPct ?>%"></div>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </td>
                </tr>
                <?php endif; ?>

                <?php endforeach; ?>
                <?php endif; ?>

                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- No results state (shown via JS) -->
<div id="invNoResults" class="text-center py-5 d-none">
    <i class="bi bi-search display-4 d-block mb-3 opacity-25"></i>
    <h5 class="fw-semibold mb-1"><?= __('inventory.no_results.title', 'No results found') ?></h5>
    <p class="text-muted small"><?= __('inventory.no_results.text', 'Try adjusting your filter or search query.') ?></p>
</div>

</div>
</section>
</div>

<!-- ══════════════════════════════════════════════════
     STOCK ADJUSTMENT MODAL
══════════════════════════════════════════════════ -->
<div class="modal fade" id="stockModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" style="max-width:380px">
        <div class="modal-content border-0 shadow">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold">
                    <i class="bi bi-sliders2 me-2 text-primary"></i>
                    <span id="stockModalTitle"><?= __('inventory.modal.title', 'Adjust Stock') ?></span>
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body pt-2">
                <p class="text-muted small mb-3" id="stockModalProduct"></p>

                <!-- Simple quantity input -->
                <div id="stockSimpleForm">
                    <label class="form-label fw-semibold small"><?= __('inventory.modal.new_quantity', 'New Quantity') ?></label>
                    <div class="input-group">
                        <button type="button" class="btn btn-outline-secondary" id="stockDecBtn">
                            <i class="bi bi-dash-lg"></i>
                        </button>
                        <input type="number" id="stockQtyInput" class="form-control text-center fw-bold fs-5"
                               min="0" value="0" style="border-left:0;border-right:0">
                        <button type="button" class="btn btn-outline-secondary" id="stockIncBtn">
                            <i class="bi bi-plus-lg"></i>
                        </button>
                    </div>
                    <div class="form-text"><?= __('inventory.modal.hint', 'Enter 0 to mark as out of stock.') ?></div>
                </div>

            </div>
            <div class="modal-footer border-0 pt-0">
                <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">
                    <?= __('actions.cancel', 'Cancel') ?>
                </button>
                <button type="button" class="btn btn-primary btn-sm" id="stockSaveBtn">
                    <i class="bi bi-check-lg me-1"></i><?= __('actions.save', 'Save') ?>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- CSRF token for AJAX -->
<input type="hidden" id="csrfToken" value="<?= \Core\System\Csrf::token() ?>">

<script>
(function () {
    'use strict';

    /* ── Filter & Search ── */
    const filterBtns  = document.querySelectorAll('.inv-filter');
    const rows        = document.querySelectorAll('.inv-row');
    const variantRows = document.querySelectorAll('.variant-details-row');
    const searchInput = document.getElementById('invSearch');
    const tableCount  = document.getElementById('invTableCount');
    const tableTitle  = document.getElementById('invTableTitle');
    const noResults   = document.getElementById('invNoResults');

    const filterLabels = {
        all: '<?= __('inventory.table.title', 'All Products — Stock Details') ?>',
        out: '<?= __('inventory.filter.out_of_stock', 'Out of Stock') ?>',
        low: '<?= __('inventory.filter.low_stock', 'Low Stock') ?>',
        ok:  '<?= __('inventory.filter.healthy', 'Healthy') ?>',
    };

    let activeFilter = 'all';

    function applyFilters() {
        const q = (searchInput.value || '').toLowerCase().trim();
        let visible = 0;

        rows.forEach(function (row) {
            const statusOk = activeFilter === 'all' || row.dataset.stockStatus === activeFilter;
            const searchOk = !q || (row.dataset.search || '').includes(q);
            const show     = statusOk && searchOk;
            row.style.display = show ? '' : 'none';

            // also hide related variant sub-row if main row is hidden
            const varRow = document.getElementById('variants-' + row.dataset.productId);
            if (varRow) varRow.style.display = show && !varRow.classList.contains('d-none') ? '' : 'none';

            if (show) visible++;
        });

        tableCount.textContent = visible;
        tableTitle.textContent = (filterLabels[activeFilter] || '<?= __('inventory.table.title', 'All Products') ?>');

        noResults.classList.toggle('d-none', visible > 0);
    }

    filterBtns.forEach(function (btn) {
        btn.addEventListener('click', function () {
            filterBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            activeFilter = this.dataset.filter;
            applyFilters();
        });
    });

    searchInput.addEventListener('input', applyFilters);

    /* ── Variant Toggle ── */
    document.querySelectorAll('.variant-toggle').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const pid    = this.dataset.productId;
            const varRow = document.getElementById('variants-' + pid);
            const arrow  = this.querySelector('.toggle-arrow');
            if (!varRow) return;
            const isHidden = varRow.classList.contains('d-none');
            varRow.classList.toggle('d-none', !isHidden);
            varRow.style.display = isHidden ? '' : 'none';
            if (arrow) arrow.className = isHidden ? 'bi bi-chevron-up ms-1 toggle-arrow' : 'bi bi-chevron-down ms-1 toggle-arrow';
        });
    });

    /* ── Stock Adjust Modal ── */
    // Bootstrap JS loads in footer.php — use lazy getter so it's available on first click
    function getStockModal() {
        return bootstrap.Modal.getOrCreateInstance(document.getElementById('stockModal'));
    }
    const stockQtyInput  = document.getElementById('stockQtyInput');
    const stockDecBtn    = document.getElementById('stockDecBtn');
    const stockIncBtn    = document.getElementById('stockIncBtn');
    const stockSaveBtn   = document.getElementById('stockSaveBtn');
    const stockModalProd = document.getElementById('stockModalProduct');
    const stockModalTitle= document.getElementById('stockModalTitle');
    const csrfToken      = document.getElementById('csrfToken').value;

    let _currentPid      = null;
    let _currentSize     = null;
    let _currentColor    = null;
    let _isVariant       = false;
    let _productTitle    = '';

    function openStockModal(pid, current, productTitle, size, color) {
        _currentPid   = pid;
        _currentSize  = size  || null;
        _currentColor = color || null;
        _isVariant    = !!(size || color);
        _productTitle = productTitle;

        stockModalTitle.textContent = _isVariant
            ? '<?= __('inventory.modal.adjust_variant', 'Adjust Variant Stock') ?>'
            : '<?= __('inventory.modal.title', 'Adjust Stock') ?>';

        let subtitle = productTitle;
        if (_isVariant) {
            let parts = [];
            if (size)  parts.push(size);
            if (color) parts.push(color);
            subtitle += ' — ' + parts.join(' / ');
        }
        stockModalProd.textContent = subtitle;

        stockQtyInput.value = parseInt(current) || 0;
        getStockModal().show();
    }

    // Button triggers (simple stock, no variants)
    document.querySelectorAll('.stock-edit-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const pid     = this.dataset.productId;
            const current = this.dataset.current;
            const hasVar  = this.dataset.hasVariants === '1';
            // Find product title
            const row   = document.querySelector('.inv-row[data-product-id="' + pid + '"]');
            const title = row ? row.querySelector('.fw-semibold.small.text-dark').textContent.trim() : '';

            if (hasVar) {
                // Open variant sub-section and scroll to it
                const varRow = document.getElementById('variants-' + pid);
                if (varRow && varRow.classList.contains('d-none')) {
                    varRow.classList.remove('d-none');
                    varRow.style.display = '';
                    const tgl = document.querySelector('.variant-toggle[data-product-id="' + pid + '"]');
                    if (tgl) {
                        const arrow = tgl.querySelector('.toggle-arrow');
                        if (arrow) arrow.className = 'bi bi-chevron-up ms-1 toggle-arrow';
                    }
                }
                if (varRow) varRow.scrollIntoView({ behavior: 'smooth', block: 'center' });
                return;
            }

            openStockModal(pid, current, title, null, null);
        });
    });

    // Variant-specific edit button
    document.querySelectorAll('.variant-stock-edit').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const pid     = this.dataset.productId;
            const size    = this.dataset.size;
            const color   = this.dataset.color;
            const current = this.dataset.current;
            const row     = document.querySelector('.inv-row[data-product-id="' + pid + '"]');
            const title   = row ? row.querySelector('.fw-semibold.small.text-dark').textContent.trim() : '';
            openStockModal(pid, current, title, size, color);
        });
    });

    stockDecBtn.addEventListener('click', function () {
        const v = parseInt(stockQtyInput.value) || 0;
        stockQtyInput.value = Math.max(0, v - 1);
    });

    stockIncBtn.addEventListener('click', function () {
        const v = parseInt(stockQtyInput.value) || 0;
        stockQtyInput.value = v + 1;
    });

    stockSaveBtn.addEventListener('click', function () {
        const qty = parseInt(stockQtyInput.value);
        if (isNaN(qty) || qty < 0) return;

        const btn = this;
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span><?= __('actions.saving', 'Saving...') ?>';

        let url    = '/admin/inventory/update-stock/' + _currentPid;
        let body   = new URLSearchParams({ _csrf: csrfToken, quantity: qty });

        if (_isVariant) {
            url = '/admin/inventory/update-variant-stock/' + _currentPid;
            if (_currentSize)  body.append('size',  _currentSize);
            if (_currentColor) body.append('color', _currentColor);
        }

        fetch(url, { method: 'POST', body: body, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (data.success) {
                    getStockModal().hide();

                    if (_isVariant) {
                        // Update variant display
                        document.querySelectorAll('.variant-qty[data-product-id="' + _currentPid + '"]').forEach(function(el) {
                            if (el.dataset.size === (_currentSize || '') && el.dataset.color === (_currentColor || '')) {
                                el.textContent = qty;
                            }
                        });
                    } else {
                        // Update main stock display
                        const disp = document.getElementById('stock-display-' + _currentPid);
                        if (disp) {
                            disp.textContent = qty.toLocaleString();
                            // Update color classes
                            const row     = document.querySelector('.inv-row[data-product-id="' + _currentPid + '"]');
                            const alert   = row ? parseInt(row.querySelector('[data-product-id]')?.dataset?.current || 0) : 0;
                            const newSt   = qty === 0 ? 'danger' : (qty <= alert ? 'warning' : 'success');
                            disp.className = 'fw-bold fs-6 lh-1 text-' + newSt;
                        }
                    }

                    // Show toast notification
                    showToast('<?= __('inventory.toast.saved', 'Stock updated successfully') ?>', 'success');
                } else {
                    showToast('<?= __('inventory.toast.error', 'Failed to update stock') ?>', 'danger');
                }
            })
            .catch(function () {
                showToast('<?= __('inventory.toast.error', 'Failed to update stock') ?>', 'danger');
            })
            .finally(function () {
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-check-lg me-1"></i><?= __('actions.save', 'Save') ?>';
            });
    });

    /* ── Toast ── */
    function showToast(msg, type) {
        const id   = 'inv-toast-' + Date.now();
        const html = '<div id="' + id + '" class="toast align-items-center text-bg-' + type + ' border-0 show" role="alert" style="position:fixed;bottom:1.5rem;' + (document.dir === 'rtl' ? 'left' : 'right') + ':1.5rem;z-index:9999;min-width:240px">' +
                     '<div class="d-flex"><div class="toast-body fw-semibold">' + msg + '</div>' +
                     '<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button></div></div>';
        document.body.insertAdjacentHTML('beforeend', html);
        const el = document.getElementById(id);
        setTimeout(function () { if (el) el.remove(); }, 3000);
    }

})();
</script>

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