<style>
/* Responsive Header & Buttons */
.responsive-header { display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; }
@media (max-width: 640px) {
    .responsive-header { flex-direction: column; align-items: flex-start; }
    .action-btns { width: 100%; justify-content: space-between; }
    .action-btns .btn { flex: 1; justify-content: center; font-size: 0.7rem !important; padding: 4px !important; }
}

/* Responsive Stats Grid */
.responsive-stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.75rem; margin-bottom: 1rem; }
@media (max-width: 1024px) { .responsive-stats-grid { grid-template-columns: repeat(2, 1fr); } }
@media (max-width: 480px) { .responsive-stats-grid { grid-template-columns: 1fr; } }

/* Compact Labels & Text */
.compact-stat { padding: 8px 12px !important; }
.text-tiny { font-size: 0.65rem !important; }
.text-xs { font-size: 0.75rem !important; }
.font-bold { font-weight: 700 !important; }

/* Filter Bar Fluidity */
.search-box-fluid { position: relative; flex: 1; min-width: 200px; }
.search-icon { position: absolute; left: 8px; top: 50%; transform: translateY(-50%); width: 14px; height: 14px; color: var(--text-muted); }
.form-control-compact { 
    width: 100%; padding: 4px 8px; font-size: 0.8rem; border: 1px solid var(--border); 
    border-radius: 4px; background: var(--bg-raised); transition: all 0.2s;
}
.search-box-fluid .form-control-compact { padding-left: 28px; }
.filter-group-fluid { display: flex; gap: 0.5rem; flex-wrap: wrap; flex: 2; }
.filter-group-fluid select { flex: 1; min-width: 120px; }

/* Table Responsive Card View */
@media (max-width: 768px) {
    .products-data-table thead { display: none; }
    .products-data-table, .products-data-table tbody, .products-data-table tr, .products-data-table td { display: block; width: 100%; }
    .products-data-table tr { margin-bottom: 0.75rem; border: 1px solid var(--border); border-radius: 8px; background: var(--bg-surface); padding: 8px; box-shadow: var(--shadow-sm); }
    .products-data-table td { display: flex; justify-content: space-between; align-items: center; padding: 6px 4px !important; border-bottom: 1px solid var(--border-soft); font-size: 0.8rem; }
    .products-data-table td:last-child { border-bottom: none; }
    .products-data-table td::before { content: attr(data-label); font-weight: 700; color: var(--text-muted); font-size: 0.7rem; text-transform: uppercase; }
    .products-data-table td[data-label="Product"] { flex-direction: column; align-items: flex-start; border-bottom: 1px solid var(--border); margin-bottom: 4px; padding-bottom: 8px !important; }
    .products-data-table td[data-label="Product"]::before { margin-bottom: 4px; }
    .action-cell { justify-content: flex-end !important; }
    .action-cell::before { display: none; }
    .table-footer-totals { display: none !important; }
}

/* Desktop Compact Polish */
.products-data-table th { padding: 8px 12px !important; font-size: 0.7rem !important; background: var(--bg-raised) !important; }
.products-data-table td { padding: 6px 12px !important; }
.product-cell-compact { display: flex; align-items: center; gap: 8px; }
.product-img-tiny { width: 32px; height: 32px; border-radius: 4px; background: var(--bg-raised); overflow: hidden; flex-shrink: 0; }
.product-img-tiny img { width: 100%; height: 100%; object-fit: cover; }
.placeholder-icon { width: 16px; height: 16px; color: var(--text-muted); margin: 8px; }
.product-name-link { font-weight: 600; color: var(--text-primary); text-decoration: none; font-size: 0.85rem; }
.product-sku-tiny { font-size: 0.65rem; color: var(--text-muted); }
.btn-icon-xs { padding: 4px; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; }
.btn-icon-xs svg { width: 14px; height: 14px; }
</style>

<div class="page-header responsive-header" style="margin-bottom: 8px;">
    <div style="flex: 1;">
        <h1 style="font-size: 1.2rem; margin-bottom: 2px;">Products</h1>
        <div class="page-subtitle" style="font-size: 0.75rem;">Manage your inventory items and SKUs.</div>
    </div>
    <div class="flex gap-2 flex-wrap action-btns">
        <button onclick="printTable()" class="btn btn-outline" style="padding: 4px 8px; font-size: 0.75rem;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 14px; height: 14px;"><polyline points="6 9 6 2 18 2 18 9"></polyline><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v-5a2 2 0 0 1-2 2h-2"></path><rect x="6" y="14" width="12" height="8"></rect></svg>
            Print
        </button>
        <button onclick="exportProducts()" class="btn btn-outline" style="padding: 4px 8px; font-size: 0.75rem;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 14px; height: 14px;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
            Export
        </button>
        <button type="button" class="btn btn-outline" onclick="showStockImportModal()" style="padding: 4px 8px; font-size: 0.75rem;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 14px; height: 14px;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>
            Import
        </button>
        <?php if (!PlanGuard::checkLimit('products')['allowed']): ?>
            <button class="btn btn-primary" onclick="alert('Product limit reached for your current plan. Please upgrade.')" style="padding: 4px 8px; font-size: 0.75rem;">Add Product</button>
        <?php else: ?>
            <a href="<?= APP_URL ?>/products/create" class="btn btn-primary" style="padding: 4px 8px; font-size: 0.75rem;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 14px; height: 14px;"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
                Add Product
            </a>
        <?php endif; ?>
    </div>
</div>

<div class="responsive-stats-grid gap-3 mb-3">
    <div class="summary-card summary-card-primary compact-stat">
        <div class="summary-card-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12.89 1.45l8 4v9.11a6 6 0 0 1-8.66 5.55 6 6 0 0 1-1.34-11.66l8.66-4.97"></path><path d="M12 9v6m0 0l-3-1.5m3 1.5l3-1.5"></path></svg>
        </div>
        <div class="summary-card-content">
            <div class="summary-card-label">Total Items</div>
            <div class="summary-card-value"><?= count($products['data']) ?></div>
        </div>
    </div>

    <div class="summary-card summary-card-success compact-stat">
        <div class="summary-card-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M7 7h.01M11 7h.01M15 7h.01M7 11h.01M11 11h.01M15 11h.01M7 15h.01M11 15h.01M15 15h.01"/></svg>
        </div>
        <div class="summary-card-content">
            <div class="summary-card-label">Total Stock</div>
            <div class="summary-card-value"><?= number_format(array_sum(array_column($products['data'], 'total_stock')), 2) ?></div>
        </div>
    </div>

    <div class="summary-card summary-card-warning compact-stat">
        <div class="summary-card-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>
        </div>
        <div class="summary-card-content">
            <div class="summary-card-label">Value (Cost)</div>
            <div class="summary-card-value"><?= money(array_sum(array_map(function($p) { return $p['total_stock'] * $p['cost_price']; }, $products['data']))) ?></div>
        </div>
    </div>

    <div class="summary-card summary-card-accent compact-stat">
        <div class="summary-card-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg>
        </div>
        <div class="summary-card-content">
            <div class="summary-card-label">Value (Retail)</div>
            <div class="summary-card-value"><?= money(array_sum(array_map(function($p) { return $p['total_stock'] * $p['selling_price']; }, $products['data']))) ?></div>
        </div>
    </div>
</div>

<div class="card mb-3 compact-card shadow-sm">
    <div class="filter-bar">
        <form action="" method="GET" class="flex gap-2 flex-1 flex-wrap items-center">
            <div class="search-box-fluid">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="search-icon"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
                <input type="text" name="search" id="searchInput" class="form-control-compact" placeholder="Search products, SKU..." value="<?= e($_GET['search'] ?? '') ?>">
            </div>
            <div class="filter-group-fluid">
                <select name="category_id" id="categoryFilter" class="form-control-compact" onchange="this.form.submit()">
                    <option value="">All Categories</option>
                    <?php foreach ($categories as $cat): ?>
                    <option value="<?= $cat['id'] ?>" <?= ($_GET['category_id'] ?? '') == $cat['id'] ? 'selected' : '' ?>><?= e($cat['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="brand_id" id="brandFilter" class="form-control-compact" onchange="this.form.submit()">
                    <option value="">All Brands</option>
                    <?php foreach ($brands as $brand): ?>
                    <option value="<?= $brand['id'] ?>" <?= ($_GET['brand_id'] ?? '') == $brand['id'] ? 'selected' : '' ?>><?= e($brand['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="status" id="statusFilter" class="form-control-compact" onchange="this.form.submit()">
                    <option value="">Status</option>
                    <option value="1" <?= ($_GET['status'] ?? '') == '1' ? 'selected' : '' ?>>Active</option>
                    <option value="0" <?= ($_GET['status'] ?? '') == '0' ? 'selected' : '' ?>>Inactive</option>
                </select>
                <select name="location_id" id="locationFilter" class="form-control-compact" onchange="this.form.submit()">
                    <option value="">All Locations</option>
                    <?php foreach ($locations as $loc): ?>
                    <option value="<?= $loc['id'] ?>" <?= ($_GET['location_id'] ?? '') == $loc['id'] ? 'selected' : '' ?>><?= e($loc['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="flex gap-1">
                <button type="submit" class="btn btn-primary btn-sm">Search</button>
                <?php if (!empty($_GET['search']) || !empty($_GET['category_id']) || !empty($_GET['brand_id']) || !empty($_GET['status']) || !empty($_GET['location_id'])): ?>
                    <a href="<?= APP_URL ?>/products" class="btn btn-outline btn-sm">Clear</a>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <div class="table-wrapper responsive-table-wrapper" style="margin-top: 8px;">
        <table class="products-data-table">
            <thead>
                <tr>
                    <th>Product details</th>
                    <th>Category / Brand</th>
                    <th>Stock</th>
                    <th>Cost Price</th>
                    <th>Selling Price</th>
                    <th class="text-right">Stock Value</th>
                    <th>Status</th>
                    <th class="text-right" style="width: 100px;">Actions</th>
                </tr>
            </thead>
            <tbody id="productsTableBody">
                <?php if (empty($products['data'])): ?>
                <tr>
                    <td colspan="8" class="text-center no-data-cell">
                        <div class="empty-state">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path><polyline points="3.27 6.96 12 12.01 20.73 6.96"></polyline><line x1="12" y1="22.08" x2="12" y2="12"></line></svg>
                            <h3>No products found</h3>
                            <p>Get started by adding your first product to the inventory.</p>
                        </div>
                    </td>
                </tr>
                <?php else: foreach ($products['data'] as $p): ?>
                <tr class="product-row" data-category-id="<?= $p['category_id'] ?>" data-brand-id="<?= $p['brand_id'] ?>" data-status="<?= $p['is_active'] ? '1' : '0' ?>" data-name="<?= e(strtolower($p['name'])) ?>" data-sku="<?= e(strtolower($p['sku'])) ?>" data-stock="<?= $p['total_stock'] ?>" data-cost-price="<?= $p['cost_price'] ?>" data-selling-price="<?= $p['selling_price'] ?>">
                    <td data-label="Product">
                        <div class="product-cell-compact">
                            <div class="product-img-tiny">
                                <?php if ($p['image']): ?>
                                    <img src="<?= APP_URL ?>/uploads/<?= Auth::tenantId() ?>/<?= e($p['image']) ?>" alt="" loading="lazy">
                                <?php else: ?>
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="placeholder-icon"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>
                                <?php endif; ?>
                            </div>
                            <div class="product-info-compact">
                                <a href="<?= APP_URL ?>/products/<?= $p['id'] ?>" class="product-name-link"><?= e($p['name']) ?></a>
                                <div class="product-sku-tiny">SKU: <?= e($p['sku']) ?></div>
                            </div>
                        </div>
                    </td>
                    <td data-label="Category / Brand">
                        <div class="text-xs font-semibold"><?= e($p['category_name'] ?: '—') ?></div>
                        <div class="text-tiny text-muted"><?= e($p['brand_name'] ?: '—') ?></div>
                    </td>
                    <td data-label="Stock">
                        <?php 
                        $stock = (float)$p['total_stock'];
                        $alert = (float)$p['alert_qty'];
                        if ($stock <= 0): ?>
                            <span class="badge badge-danger text-tiny">Out of stock</span>
                        <?php elseif ($stock <= $alert): ?>
                            <span class="text-orange-600 font-bold text-xs"><?= number_format($stock, 2) ?> <?= e($p['unit']) ?></span>
                        <?php else: ?>
                            <span class="text-green-600 font-bold text-xs"><?= number_format($stock, 2) ?> <?= e($p['unit']) ?></span>
                        <?php endif; ?>
                    </td>
                    <td data-label="Cost Price" class="text-xs"><?= money($p['cost_price']) ?></td>
                    <td data-label="Selling Price" class="text-xs font-bold"><?= money($p['selling_price']) ?></td>
                    <td data-label="Stock Value" class="text-right text-xs font-bold"><?= money($p['total_stock'] * $p['selling_price']) ?></td>
                    <td data-label="Status">
                        <?php if ($p['is_active']): ?>
                            <span class="badge badge-success text-tiny">Active</span>
                        <?php else: ?>
                            <span class="badge badge-muted text-tiny">Inactive</span>
                        <?php endif; ?>
                    </td>
                    <td class="text-right action-cell">
                        <div class="flex gap-1 justify-end">
                            <a href="<?= APP_URL ?>/products/<?= $p['id'] ?>/history" class="btn btn-ghost btn-icon-xs" title="History">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
                            </a>
                            <a href="<?= APP_URL ?>/products/<?= $p['id'] ?>/edit" class="btn btn-ghost btn-icon-xs" title="Edit">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>
                            </a>
                            <form action="<?= APP_URL ?>/products/<?= $p['id'] ?>/delete" method="POST" style="display:inline;" onsubmit="return confirm('Are you sure you want to delete this product?');">
                                <?= Security::csrfField() ?>
                                <button type="submit" class="btn btn-ghost btn-icon-xs text-red-600">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>
                                </button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
            <?php if (!empty($products['data'])): ?>
            <tfoot>
                <tr class="table-footer-totals">
                    <td class="table-footer-label" colspan="2">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 14px; height: 14px; margin-right: 4px; display: inline; vertical-align: middle;"><path d="M12 2v20m10-10H2"></path></svg>
                        <span class="text-xs font-bold">Page Total</span>
                    </td>
                    <td class="table-footer-value">
                        <div class="text-tiny text-muted uppercase font-bold">Stock</div>
                        <div class="text-xs font-bold"><?= number_format(array_sum(array_column($products['data'], 'total_stock')), 2) ?></div>
                    </td>
                    <td class="table-footer-value">
                        <div class="text-tiny text-muted uppercase font-bold">Cost</div>
                        <div class="text-xs font-bold"><?= money(array_sum(array_column($products['data'], 'cost_price'))) ?></div>
                    </td>
                    <td class="table-footer-value">
                        <div class="text-tiny text-muted uppercase font-bold">Selling</div>
                        <div class="text-xs font-bold"><?= money(array_sum(array_column($products['data'], 'selling_price'))) ?></div>
                    </td>
                    <td class="table-footer-value text-right">
                        <div class="text-tiny text-muted uppercase font-bold">Total Val</div>
                        <div class="text-xs font-bold"><?= money(array_sum(array_map(function($p) { return $p['total_stock'] * $p['selling_price']; }, $products['data']))) ?></div>
                    </td>
                    <td colspan="2"></td>
                </tr>
            </tfoot>
            <?php endif; ?>
        </table>
    </div>
    
    <div class="flex justify-between items-center mt-3">
        <?= paginationLinks($products, APP_URL . '/products', $_GET) ?>
    </div>
</div>

<script>
function printTable() {
    const tableWrapper = document.querySelector('.table-wrapper');
    if (!tableWrapper) return;
    
    // Clone the table wrapper to avoid modifying the original
    const clonedWrapper = tableWrapper.cloneNode(true);
    const table = clonedWrapper.querySelector('table');
    
    // Remove the action column (last column) from header and body
    const headerRow = table.querySelector('thead tr');
    if (headerRow) {
        headerRow.deleteCell(-1); // Remove last cell
    }
    
    // Remove last cell from each body row and calculate totals
    let totalStock = 0;
    let totalCost = 0;
    let totalRetail = 0;
    const bodyRows = table.querySelectorAll('tbody tr');
    bodyRows.forEach(row => {
        row.deleteCell(-1);
        // Extract values from cells for totals calculation
        const cells = row.querySelectorAll('td');
        if (cells.length >= 5) {
            // Stock is in cell index 2
            const stockText = cells[2].textContent.trim();
            const stockMatch = stockText.match(/[\d,]+\.?\d*/);
            if (stockMatch) {
                totalStock += parseFloat(stockMatch[0].replace(/,/g, ''));
            }
            // Cost price is in cell index 3
            const costText = cells[3].textContent.trim();
            const costMatch = costText.match(/[\d,]+\.?\d*/);
            if (costMatch) {
                totalCost += parseFloat(costMatch[0].replace(/,/g, ''));
            }
            // Selling price is in cell index 4
            const retailText = cells[4].textContent.trim();
            const retailMatch = retailText.match(/[\d,]+\.?\d*/);
            if (retailMatch) {
                totalRetail += parseFloat(retailMatch[0].replace(/,/g, ''));
            }
        }
    });
    
    // Remove existing footer if any
    const existingTfoot = table.querySelector('tfoot');
    if (existingTfoot) {
        existingTfoot.remove();
    }
    
    // Add new footer with totals
    const tfoot = document.createElement('tfoot');
    const footerRow = document.createElement('tr');
    footerRow.style.background = '#f5f5f5';
    footerRow.style.fontWeight = 'bold';
    footerRow.style.borderTop = '2px solid #333';
    
    // Total label cell
    const labelCell = document.createElement('td');
    labelCell.colSpan = 2;
    labelCell.textContent = 'Total';
    labelCell.style.fontWeight = 'bold';
    footerRow.appendChild(labelCell);
    
    // Total stock cell
    const stockCell = document.createElement('td');
    stockCell.textContent = totalStock.toLocaleString();
    stockCell.style.fontWeight = 'bold';
    footerRow.appendChild(stockCell);
    
    // Total cost cell
    const costCell = document.createElement('td');
    costCell.textContent = totalCost.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
    costCell.style.fontWeight = 'bold';
    footerRow.appendChild(costCell);
    
    // Total retail cell
    const retailCell = document.createElement('td');
    retailCell.textContent = totalRetail.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
    retailCell.style.fontWeight = 'bold';
    footerRow.appendChild(retailCell);
    
    // Status cell (empty)
    const statusCell = document.createElement('td');
    footerRow.appendChild(statusCell);
    
    tfoot.appendChild(footerRow);
    table.appendChild(tfoot);
    
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Products List</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    margin: 20px;
                    padding: 20px;
                    font-size: 12px;
                }
                .print-header {
                    margin-bottom: 20px;
                    padding-bottom: 15px;
                    border-bottom: 2px solid #333;
                }
                .print-header h2 {
                    margin: 0 0 5px 0;
                    font-size: 18px;
                }
                .print-header p {
                    margin: 0;
                    color: #666;
                    font-size: 11px;
                }
                table {
                    border-collapse: collapse;
                    width: 100%;
                    margin-top: 10px;
                }
                th, td {
                    border: 1px solid #ccc;
                    padding: 8px 10px;
                    text-align: left;
                }
                th {
                    background: #f5f5f5;
                    font-weight: bold;
                    font-size: 11px;
                }
                tbody tr:nth-child(even) {
                    background: #f9f9f9;
                }
                tfoot tr {
                    background: #f5f5f5 !important;
                    font-weight: bold;
                    border-top: 2px solid #333;
                }
                tfoot td {
                    font-weight: bold;
                }
                .badge {
                    padding: 3px 8px;
                    border-radius: 3px;
                    font-size: 10px;
                    display: inline-block;
                }
                .badge-success {
                    background: #d4edda;
                    color: #155724;
                }
                .badge-danger {
                    background: #f8d7da;
                    color: #721c24;
                }
                .badge-muted {
                    background: #e2e3e5;
                    color: #383d41;
                }
                img {
                    max-width: 40px;
                    max-height: 40px;
                    object-fit: cover;
                }
                @media print {
                    body {
                        margin: 15mm;
                        padding: 0;
                    }
                    .print-header {
                        page-break-after: avoid;
                    }
                    table {
                        page-break-inside: auto;
                    }
                    tr {
                        page-break-inside: avoid;
                        page-break-after: auto;
                    }
                }
            </style>
        </head>
        <body>
            <div class="print-header">
                <h2>Products List</h2>
                <p>Generated on: ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}</p>
            </div>
            ${clonedWrapper.outerHTML}
        </body>
        </html>
    `);
    printWindow.document.close();
    printWindow.onload = function() {
        printWindow.print();
        printWindow.close();
    };
}

function exportProducts() {
    let csv = 'Product Name,SKU,Category,Brand,Stock,Cost Price,Selling Price,Status\n';
    <?php foreach ($products['data'] as $p): ?>
    csv += '<?= e($p['name']) ?>,<?= e($p['sku']) ?>,<?= e($p['category_name'] ?: '') ?>,<?= e($p['brand_name'] ?: '') ?>,<?= number_format($p['total_stock'], 2) ?>,<?= $p['cost_price'] ?>,<?= $p['selling_price'] ?>,<?= $p['is_active'] ? 'Active' : 'Inactive' ?>\n';
    <?php endforeach; ?>
    
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'products_export.csv';
    a.click();
    window.URL.revokeObjectURL(url);
}

function showStockImportModal() {
    const modal = document.createElement('div');
    modal.className = 'modal-overlay show';
    modal.id = 'stockImportModal';
    modal.innerHTML = `
        <div class="modal" style="max-width: 600px;">
            <div class="modal-header">
                <h3 class="modal-title">Import Stock from CSV</h3>
                <button class="modal-close" onclick="closeStockImportModal()">&times;</button>
            </div>
            <div class="modal-body">
                <p class="text-muted" style="margin-bottom: 12px;">Upload a CSV file to update stock quantities for existing products. The CSV should have the following columns:</p>
                <div style="background:var(--bg-surface); padding:12px; border-radius:6px; font-size:0.85rem; margin-bottom:12px;">
                    <code>sku, location_name, quantity</code>
                </div>
                <div style="margin-bottom:16px;">
                    <div style="font-size:0.8rem; color:var(--text-muted); margin-bottom:8px;">
                        <strong>Column descriptions:</strong>
                    </div>
                    <ul style="font-size:0.8rem; color:var(--text-muted); margin:0; padding-left:20px;">
                        <li><strong>sku:</strong> Product SKU (must match existing product)</li>
                        <li><strong>location_name:</strong> Name of the location/warehouse</li>
                        <li><strong>quantity:</strong> Stock quantity to add or set</li>
                    </ul>
                </div>
                <a href="<?= APP_URL ?>/products/stock-import-template" class="btn btn-outline btn-sm" style="display:inline-flex; align-items:center; gap:4px; margin-bottom:16px;">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:14px;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
                    Download CSV Template
                </a>

                <div style="margin-top:16px;">
                    <h4 style="font-size:0.9rem; margin-bottom:8px; font-weight:600;">Sample CSV Format:</h4>
                    <div style="background:var(--bg-surface); border:1px solid var(--border); border-radius:6px; overflow-x:auto;">
                        <table style="font-size:0.75rem; border-collapse:collapse; width:100%;">
                            <thead>
                                <tr style="background:var(--bg-raised);">
                                    <th style="padding:8px; text-align:left; border-bottom:1px solid var(--border);">sku</th>
                                    <th style="padding:8px; text-align:left; border-bottom:1px solid var(--border);">location_name</th>
                                    <th style="padding:8px; text-align:left; border-bottom:1px solid var(--border);">quantity</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td style="padding:8px; border-bottom:1px solid var(--border);">SKU-001</td>
                                    <td style="padding:8px; border-bottom:1px solid var(--border);">Main Warehouse</td>
                                    <td style="padding:8px; border-bottom:1px solid var(--border);">50</td>
                                </tr>
                                <tr>
                                    <td style="padding:8px; border-bottom:1px solid var(--border);">SKU-002</td>
                                    <td style="padding:8px; border-bottom:1px solid var(--border);">Main Warehouse</td>
                                    <td style="padding:8px; border-bottom:1px solid var(--border);">25</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <form action="<?= APP_URL ?>/products/stock-import" method="POST" enctype="multipart/form-data" style="margin-top:20px;" id="stockImportForm">
                    <?= Security::csrfField() ?>
                    <div class="form-group">
                        <label class="form-label">CSV File <span class="required">*</span></label>
                        <input type="file" name="csv_file" id="csvFile" class="form-control" accept=".csv" required onchange="detectCsvFormat()">
                        <div class="form-hint">Maximum file size: 5MB. Supports both stock format (sku, location_name, quantity) and product format (with sku, initial_stock columns).</div>
                    </div>
                    <div class="form-group" id="locationSelectGroup" style="display:none;">
                        <label class="form-label">Default Location <span class="required">*</span></label>
                        <select name="default_location" id="defaultLocation" class="form-control">
                            <option value="">Select a location...</option>
                            <?php
                            $locations = \Location::active();
                            foreach ($locations as $loc): ?>
                                <option value="<?= $loc['id'] ?>"><?= e($loc['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <div class="form-hint">Required when using product CSV format (no location_name column detected).</div>
                    </div>
                    <div class="form-group">
                        <label class="flex items-center gap-2" style="cursor:pointer;">
                            <input type="checkbox" name="replace_stock" value="1">
                            <span>Replace existing stock (instead of adding to it)</span>
                        </label>
                        <div class="form-hint">If checked, the stock quantity will be set to the CSV value instead of being added to current stock.</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-ghost" onclick="closeStockImportModal()">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="submitStockImport()">Import Stock</button>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
}

function closeStockImportModal() {
    const modal = document.getElementById('stockImportModal');
    if (modal) {
        modal.remove();
    }
}

function submitStockImport() {
    const form = document.getElementById('stockImportForm');
    const locationGroup = document.getElementById('locationSelectGroup');
    const defaultLocation = document.getElementById('defaultLocation');

    // Validate location is selected if showing
    if (locationGroup.style.display !== 'none' && !defaultLocation.value) {
        alert('Please select a default location for this CSV format.');
        defaultLocation.focus();
        return;
    }

    if (form) {
        form.submit();
    }
}

function detectCsvFormat() {
    const fileInput = document.getElementById('csvFile');
    const locationGroup = document.getElementById('locationSelectGroup');

    if (!fileInput.files.length) {
        locationGroup.style.display = 'none';
        return;
    }

    const file = fileInput.files[0];
    const reader = new FileReader();

    reader.onload = function(e) {
        const content = e.target.result;
        const lines = content.split('\n');
        if (lines.length > 0) {
            const header = lines[0].toLowerCase().split(',').map(h => h.trim());

            // Check if it has stock format columns
            const hasStockFormat = header.includes('sku') && header.includes('location_name') && header.includes('quantity');
            // Check if it has product format columns
            const hasProductFormat = header.includes('sku') && header.includes('initial_stock');

            // Show location dropdown only for product format
            if (hasProductFormat && !hasStockFormat) {
                locationGroup.style.display = 'block';
                document.getElementById('defaultLocation').setAttribute('required', 'required');
            } else {
                locationGroup.style.display = 'none';
                document.getElementById('defaultLocation').removeAttribute('required');
            }
        }
    };

    reader.readAsText(file);
}

// Search input submits form on Enter key
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                this.form.submit();
            }
        });
    }
});
</script>

