<?php
// app/Views/inventory/index.php
// Rendered by InventoryController::index()
$isInventoryRole = ($_SESSION['role'] === 'inventory');
$baseUrl  = $isInventoryRole ? '/restpo/inventory' : '/restpo/admin/inventory';
$cashierQs = $ctx['cashier_id'] ? '?cashier_id=' . $ctx['cashier_id'] : '';
$cashierQsAmp = $ctx['cashier_id'] ? '&cashier_id=' . $ctx['cashier_id'] : '';

// map categories
$categories = [];
foreach ($categoriesList as $cat) {
    $categories[$cat['id']] = $cat['name'];
}

$currency      = '৳';
$totalValueFmt = $currency . ' ' . number_format($totalValue, 2);
$logsBase      = $isInventoryRole ? '/restpo/inventory' : '/restpo/admin/inventory';
?>
<div class="space-y-5" x-data="inventoryApp()" x-init="init()">

<?php if (!empty($_GET['success'])): ?>
<div x-data="{show:true}" x-show="show" x-init="setTimeout(()=>show=false,3500)"
     class="rounded-xl px-4 py-3 text-sm font-medium flex items-center gap-2"
     style="background:rgba(16,185,129,0.12);border:1px solid rgba(16,185,129,0.3);color:#6ee7b7">
    <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($_GET['success']); ?>
</div>
<?php endif; ?>
<?php if (!empty($_GET['error'])): ?>
<div class="rounded-xl px-4 py-3 text-sm font-medium flex items-center gap-2"
     style="background:rgba(239,68,68,0.12);border:1px solid rgba(239,68,68,0.3);color:#f87171">
    <i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($_GET['error']); ?>
</div>
<?php endif; ?>

<!-- HEADER -->
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
    <div>
        <h2 class="text-xl font-bold text-white flex items-center gap-2">
            <i class="fas fa-boxes text-amber-400"></i> Inventory
            <?php if ($cashierName): ?>
                <span class="text-sm font-medium px-2 py-0.5 rounded-lg" style="background:rgba(245,158,11,0.15);color:#fcd34d">
                    <i class="fas fa-store text-xs mr-1"></i><?php echo htmlspecialchars($cashierName); ?>
                </span>
            <?php elseif (!$ctx['cashier_id']): ?>
                <span class="text-sm font-medium px-2 py-0.5 rounded-lg" style="background:rgba(100,116,139,0.2);color:#94a3b8">All Branches</span>
            <?php endif; ?>
        </h2>
        <p class="text-xs text-slate-500 mt-0.5">Manage stock levels, track movements &amp; waste</p>
    </div>
    <div class="flex items-center gap-2 flex-wrap">
        <?php if ($ctx['is_admin'] && !empty($cashiers)): ?>
        <form method="GET" action="<?php echo $baseUrl; ?>" class="flex items-center gap-2">
            <select name="cashier_id" onchange="this.form.submit()"
                    class="text-xs px-3 py-2 rounded-xl text-white outline-none"
                    style="background:rgba(13,33,55,1);border:1px solid rgba(255,255,255,0.12)">
                <option value="">All Branches</option>
                <?php foreach($cashiers as $c): ?>
                <option value="<?php echo $c['id']; ?>" <?php echo $ctx['cashier_id']==$c['id']?'selected':''; ?>>
                    <?php echo htmlspecialchars($c['name']); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </form>
        <?php endif; ?>
        <button @click="addModal=true"
                class="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold text-white transition"
                style="background:linear-gradient(135deg,#f59e0b,#d97706)">
            <i class="fas fa-plus text-xs"></i> Add Item
        </button>
    </div>
</div>

<!-- SUB-NAVIGATION BAR (COHESIVE TABS) -->
<div class="flex items-center gap-2 border-b border-white/5 pb-0.5">
    <a href="<?php echo $baseUrl; ?><?php echo $cashierQs; ?>" 
       class="text-sm font-semibold px-4 py-2 text-amber-400 border-b-2 border-amber-500 transition">
        <i class="fas fa-box text-xs mr-1.5"></i>Stock Items
    </a>
    <a href="<?php echo $baseUrl; ?>/categories<?php echo $cashierQs; ?>" 
       class="text-sm font-medium px-4 py-2 text-slate-400 hover:text-white transition">
        <i class="fas fa-tags text-xs mr-1.5"></i>Categories
    </a>
    <a href="<?php echo $baseUrl; ?>/suppliers<?php echo $cashierQs; ?>" 
       class="text-sm font-medium px-4 py-2 text-slate-400 hover:text-white transition">
        <i class="fas fa-truck text-xs mr-1.5"></i>Suppliers
    </a>
    <a href="<?php echo $baseUrl; ?>/reports<?php echo $cashierQs; ?>" 
       class="text-sm font-medium px-4 py-2 text-slate-400 hover:text-white transition">
        <i class="fas fa-chart-line text-xs mr-1.5"></i>Reports
    </a>
</div>

<!-- STATS CARDS (4-up) -->
<div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
    <div class="rounded-2xl p-4" style="background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.07)">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-xs text-slate-500 mb-1">Total Items</p>
                <p class="text-2xl font-bold text-white"><?php echo $totalItems; ?></p>
            </div>
            <div class="w-10 h-10 rounded-xl flex items-center justify-center" style="background:rgba(59,130,246,0.15)">
                <i class="fas fa-box text-blue-400"></i>
            </div>
        </div>
    </div>
    <div class="rounded-2xl p-4 cursor-pointer" @click="scrollToLowStock()"
         style="background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.07)">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-xs text-slate-500 mb-1">Low Stock</p>
                <p class="text-2xl font-bold text-amber-400"><?php echo count($lowStock); ?></p>
            </div>
            <div class="w-10 h-10 rounded-xl flex items-center justify-center" style="background:rgba(245,158,11,0.15)">
                <i class="fas fa-exclamation-triangle text-amber-400"></i>
            </div>
        </div>
    </div>
    <div class="rounded-2xl p-4" style="background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.07)">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-xs text-slate-500 mb-1">Out of Stock</p>
                <p class="text-2xl font-bold text-red-400"><?php echo count($outOfStock); ?></p>
            </div>
            <div class="w-10 h-10 rounded-xl flex items-center justify-center" style="background:rgba(239,68,68,0.15)">
                <i class="fas fa-times-circle text-red-400"></i>
            </div>
        </div>
    </div>
    <div class="rounded-2xl p-4" style="background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.07)">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-xs text-slate-500 mb-1">Stock Value</p>
                <p class="font-bold text-emerald-400 truncate" style="font-size:clamp(0.8rem,1.8vw,1.1rem)"><?php echo $totalValueFmt; ?></p>
            </div>
            <div class="w-10 h-10 rounded-xl flex items-center justify-center" style="background:rgba(16,185,129,0.15)">
                <i class="fas fa-coins text-emerald-400"></i>
            </div>
        </div>
    </div>
</div>

<!-- TODAY MOVEMENTS BAR -->
<?php if (array_sum($todayMovements) > 0): ?>
<div class="rounded-xl px-4 py-2.5 flex flex-wrap items-center gap-4 text-xs"
     style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06)">
    <span class="text-slate-500 font-medium">Today:</span>
    <span class="flex items-center gap-1.5 text-emerald-400">
        <i class="fas fa-arrow-down"></i> In <strong><?php echo number_format($todayMovements['stock_in'],2); ?></strong>
    </span>
    <span class="flex items-center gap-1.5 text-red-400">
        <i class="fas fa-arrow-up"></i> Out <strong><?php echo number_format($todayMovements['stock_out'],2); ?></strong>
    </span>
    <span class="flex items-center gap-1.5 text-orange-400">
        <i class="fas fa-trash-restore-alt"></i> Waste <strong><?php echo number_format($todayMovements['waste'],2); ?></strong>
    </span>
</div>
<?php endif; ?>

<!-- LOW STOCK ALERT PANEL -->
<?php $lowStockItems = array_values(array_filter($items, fn($i) => (float)$i['quantity'] <= (float)$i['low_stock_threshold'])); ?>
<?php if (!empty($lowStockItems)): ?>
<div id="low-stock-panel" class="rounded-2xl overflow-hidden"
     style="background:rgba(245,158,11,0.05);border:1px solid rgba(245,158,11,0.25)">
    <div class="flex items-center gap-2 px-5 py-3 border-b" style="border-color:rgba(245,158,11,0.15)">
        <i class="fas fa-exclamation-triangle text-amber-400 text-sm"></i>
        <span class="text-sm font-semibold text-amber-300">Low Stock Alert</span>
        <span class="text-xs px-2 py-0.5 rounded-full font-bold ml-1"
              style="background:rgba(245,158,11,0.2);color:#fcd34d"><?php echo count($lowStockItems); ?> items</span>
    </div>
    <div class="p-4 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
        <?php foreach($lowStockItems as $ls):
            $lsOut = (float)$ls['quantity'] <= 0;
        ?>
        <div class="flex items-center justify-between rounded-xl px-3 py-2.5"
             style="background:rgba(0,0,0,0.2);border:1px solid rgba(245,158,11,0.12)">
            <div class="min-w-0 mr-2">
                <p class="text-sm font-semibold text-white truncate"><?php echo htmlspecialchars($ls['name']); ?></p>
                <p class="text-xs" style="color:<?php echo $lsOut?'#f87171':'#fcd34d'; ?>">
                    <?php echo $lsOut ? 'OUT' : rtrim(rtrim(number_format((float)$ls['quantity'],2,'.','' ),'0'),'.'); ?>
                    / <?php echo number_format((float)$ls['low_stock_threshold'],2); ?> <?php echo htmlspecialchars($ls['unit']); ?>
                </p>
            </div>
            <button @click="openStockIn(<?php echo htmlspecialchars(json_encode(['id'=>(int)$ls['id'],'name'=>$ls['name'],'unit'=>$ls['unit'],'qty'=>(float)$ls['quantity'],'sku'=>$ls['sku']??'','category_id'=>$ls['category_id']??'','category'=>$ls['category']??'','low'=>(float)$ls['low_stock_threshold'],'cost'=>$ls['cost_price']??'','notes'=>$ls['notes']??''])); ?>)"
                    class="flex-shrink-0 px-2.5 py-1 rounded-lg text-xs font-semibold transition"
                    style="background:rgba(16,185,129,0.2);color:#6ee7b7">
                +&nbsp;In
            </button>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<!-- ITEMS TABLE -->
<div class="rounded-2xl overflow-hidden" style="background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.07)">
    <div class="flex flex-col sm:flex-row sm:items-center gap-3 px-5 py-3 border-b border-white/5">
        <p class="text-sm font-semibold text-white flex-shrink-0">Inventory Items</p>
        <?php if (!empty($categories)): ?>
        <div class="flex items-center gap-1.5 flex-wrap flex-1">
            <button @click="filterCat('')"
                    :style="activeCat==='' ? 'background:rgba(245,158,11,0.2);color:#fcd34d' : 'background:rgba(255,255,255,0.04);color:#64748b'"
                    class="px-2.5 py-1 rounded-lg text-xs font-medium transition hover:opacity-80">All</button>
            <?php foreach($categories as $catId => $catName): ?>
            <button @click="filterCat('<?php echo $catId; ?>')"
                    :style="activeCat==='<?php echo $catId; ?>' ? 'background:rgba(245,158,11,0.2);color:#fcd34d' : 'background:rgba(255,255,255,0.04);color:#64748b'"
                    class="px-2.5 py-1 rounded-lg text-xs font-medium transition hover:opacity-80">
                <?php echo htmlspecialchars($catName); ?>
            </button>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
        <div class="relative flex-shrink-0">
            <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-xs"></i>
            <input type="text" x-model="search" placeholder="Search…"
                   class="pl-8 pr-3 py-1.5 text-xs text-white rounded-lg outline-none"
                   style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.1);width:150px">
        </div>
    </div>

    <?php if (empty($items)): ?>
    <div class="px-6 py-16 text-center">
        <div class="w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4" style="background:rgba(245,158,11,0.1)">
            <i class="fas fa-boxes text-amber-400 text-2xl"></i>
        </div>
        <p class="text-slate-400 font-medium">No inventory items yet</p>
        <p class="text-slate-600 text-xs mt-1">Click "Add Item" to get started</p>
    </div>
    <?php else: ?>
    <div class="overflow-x-auto">
        <table class="w-full text-sm">
            <thead>
                <tr class="border-b border-white/5 text-xs">
                    <th class="text-left px-4 py-3 text-slate-500 font-medium">Item</th>
                    <th class="text-left px-4 py-3 text-slate-500 font-medium">Category</th>
                    <th class="text-left px-4 py-3 text-slate-500 font-medium">Stock</th>
                    <th class="text-left px-4 py-3 text-slate-500 font-medium">Unit</th>
                    <th class="text-left px-4 py-3 text-slate-500 font-medium">Alert</th>
                    <th class="text-left px-4 py-3 text-slate-500 font-medium">Status</th>
                    <th class="text-right px-4 py-3 text-slate-500 font-medium">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($items as $item):
                    $qty   = (float)$item['quantity'];
                    $low   = (float)$item['low_stock_threshold'];
                    $isOut = $qty <= 0;
                    $isLow = !$isOut && $qty <= $low;
                    $statusLabel = $isOut ? 'Out of Stock' : ($isLow ? 'Low Stock' : 'In Stock');
                    $statusBg    = $isOut ? 'rgba(239,68,68,0.15)' : ($isLow ? 'rgba(245,158,11,0.15)' : 'rgba(16,185,129,0.15)');
                    $statusColor = $isOut ? '#f87171' : ($isLow ? '#fcd34d' : '#6ee7b7');
                    $iJson = htmlspecialchars(json_encode([
                        'id'          => (int)$item['id'],
                        'name'        => $item['name'],
                        'sku'         => $item['sku'] ?? '',
                        'category_id' => $item['category_id'] ?? '',
                        'category'    => $item['category_name'] ?? $item['category'] ?? '',
                        'unit'        => $item['unit'],
                        'qty'         => $qty,
                        'low'         => $low,
                        'cost'        => $item['cost_price'] ?? '',
                        'notes'       => $item['notes'] ?? '',
                    ]));
                ?>
                <tr class="border-b border-white/5 hover:bg-white/[0.03] transition inv-row"
                    data-name="<?php echo strtolower(htmlspecialchars($item['name'])); ?>"
                    data-catid="<?php echo $item['category_id'] ?? ''; ?>">
                    <td class="px-4 py-3">
                        <div class="font-semibold text-white"><?php echo htmlspecialchars($item['name']); ?></div>
                        <?php if ($item['sku']): ?><div class="text-xs text-slate-500">SKU: <?php echo htmlspecialchars($item['sku']); ?></div><?php endif; ?>
                    </td>
                    <td class="px-4 py-3 text-slate-400 text-sm"><?php echo htmlspecialchars($item['category_name'] ?? $item['category'] ?? '—'); ?></td>
                    <td class="px-4 py-3">
                        <span class="text-lg font-bold <?php echo $isOut?'text-red-400':($isLow?'text-amber-400':'text-white'); ?>">
                            <?php echo rtrim(rtrim(number_format($qty,2,'.','' ),'0'),'.'); ?>
                        </span>
                    </td>
                    <td class="px-4 py-3 text-slate-400 text-sm"><?php echo htmlspecialchars($item['unit']); ?></td>
                    <td class="px-4 py-3 text-slate-500 text-xs"><?php echo number_format($low,2); ?></td>
                    <td class="px-4 py-3">
                        <span class="px-2 py-1 rounded-full text-xs font-semibold"
                              style="background:<?php echo $statusBg; ?>;color:<?php echo $statusColor; ?>">
                            <?php echo $statusLabel; ?>
                        </span>
                    </td>
                    <td class="px-4 py-3">
                        <div class="flex items-center justify-end gap-1">
                            <button @click="openStockIn(<?php echo $iJson; ?>)"
                                    class="w-7 h-7 rounded-lg flex items-center justify-center text-xs transition hover:scale-110"
                                    style="background:rgba(16,185,129,0.15);color:#6ee7b7" title="Stock In">
                                <i class="fas fa-arrow-down"></i>
                            </button>
                            <button @click="openStockOut(<?php echo $iJson; ?>)"
                                    class="w-7 h-7 rounded-lg flex items-center justify-center text-xs transition hover:scale-110"
                                    style="background:rgba(239,68,68,0.15);color:#f87171" title="Stock Out">
                                <i class="fas fa-arrow-up"></i>
                            </button>
                            <button @click="openWaste(<?php echo $iJson; ?>)"
                                    class="w-7 h-7 rounded-lg flex items-center justify-center text-xs transition hover:scale-110"
                                    style="background:rgba(249,115,22,0.15);color:#fdba74" title="Record Waste">
                                <i class="fas fa-trash-restore-alt"></i>
                            </button>
                            <button @click="openAdjust(<?php echo $iJson; ?>)"
                                    class="w-7 h-7 rounded-lg flex items-center justify-center text-xs transition hover:scale-110"
                                    style="background:rgba(99,102,241,0.15);color:#a5b4fc" title="Adjust Stock">
                                <i class="fas fa-sliders-h"></i>
                            </button>
                            <button @click="openEdit(<?php echo $iJson; ?>)"
                                    class="w-7 h-7 rounded-lg flex items-center justify-center text-xs transition hover:scale-110"
                                    style="background:rgba(100,116,139,0.18);color:#94a3b8" title="Edit Item">
                                <i class="fas fa-pen"></i>
                            </button>
                            <button @click="openLogs(<?php echo (int)$item['id']; ?>, '<?php echo addslashes(htmlspecialchars($item['name'])); ?>')"
                                    class="w-7 h-7 rounded-lg flex items-center justify-center text-xs transition hover:scale-110"
                                    style="background:rgba(59,130,246,0.15);color:#93c5fd" title="View History">
                                <i class="fas fa-history"></i>
                            </button>
                            <form action="<?php echo $baseUrl; ?>/delete<?php echo $cashierQs ? '?'.ltrim($cashierQs,'?') : ''; ?>" method="POST" class="inline"
                                  onsubmit="return confirm('Remove this item from inventory?')">
                                <input type="hidden" name="item_id" value="<?php echo (int)$item['id']; ?>">
                                <button type="submit"
                                        class="w-7 h-7 rounded-lg flex items-center justify-center text-xs transition hover:scale-110"
                                        style="background:rgba(239,68,68,0.08);color:#64748b" title="Delete">
                                     <i class="fas fa-trash-alt"></i>
                                </button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>


<!-- ADD ITEM MODAL -->
<div x-show="addModal" @keydown.escape.window="addModal=false"
     class="fixed inset-0 z-50 flex items-center justify-center"
     style="background:rgba(0,0,0,0.75);backdrop-filter:blur(6px);display:none">
    <div class="w-full max-w-lg mx-4 rounded-2xl shadow-2xl overflow-y-auto" style="max-height:92vh;background:#0d2137;border:1px solid rgba(245,158,11,0.25)" @click.away="addModal=false">
        <div class="flex items-center justify-between p-5 border-b border-white/8 sticky top-0" style="background:#0d2137;z-index:1">
            <h3 class="text-base font-bold text-white flex items-center gap-2"><i class="fas fa-plus-circle text-amber-400"></i> Add Inventory Item</h3>
            <button @click="addModal=false" class="text-slate-500 hover:text-white transition"><i class="fas fa-times"></i></button>
        </div>
        <form action="<?php echo $baseUrl; ?>/store<?php echo $cashierQs; ?>" method="POST" class="p-5 space-y-4">
            <div class="grid grid-cols-2 gap-4">
                <div class="col-span-2">
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Item Name *</label>
                    <input type="text" name="name" required placeholder="e.g. Chicken Breast"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">SKU / Code</label>
                    <input type="text" name="sku" placeholder="CHK-001"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Category</label>
                    <select name="category_id"
                            class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                            style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
                        <option value="">Uncategorized</option>
                        <?php foreach ($categoriesList as $cat): ?>
                        <option value="<?php echo $cat['id']; ?>">
                            <?php echo htmlspecialchars($cat['name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Initial Quantity *</label>
                    <input type="number" name="quantity" value="0" min="0" step="0.01" required
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Unit</label>
                    <select name="unit" class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                            style="background:rgba(13,33,55,1);border:1px solid rgba(255,255,255,0.12)">
                        <option>pcs</option><option>kg</option><option>g</option>
                        <option>L</option><option>ml</option><option>box</option>
                        <option>bag</option><option>bottle</option><option>dozen</option><option>pack</option>
                    </select>
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Low Stock Alert At</label>
                    <input type="number" name="low_stock_threshold" value="10" min="0" step="0.01"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Cost Price</label>
                    <input type="number" name="cost_price" placeholder="0.00" min="0" step="0.01"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
                </div>
                <div class="col-span-2">
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Notes</label>
                    <textarea name="notes" rows="2" placeholder="Optional notes…"
                              class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none resize-none"
                              style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)"></textarea>
                </div>
            </div>
            <div class="flex gap-3">
                <button type="submit" class="flex-1 py-2.5 rounded-xl font-semibold text-white text-sm"
                        style="background:linear-gradient(135deg,#f59e0b,#d97706)">
                    <i class="fas fa-plus mr-1.5"></i> Add Item
                </button>
                <button type="button" @click="addModal=false"
                        class="px-5 py-2.5 rounded-xl text-sm text-slate-400 border border-white/10 hover:bg-white/5 transition">Cancel</button>
            </div>
        </form>
    </div>
</div>


<!-- STOCK IN MODAL -->
<div x-show="stockInModal" @keydown.escape.window="stockInModal=false"
     class="fixed inset-0 z-50 flex items-center justify-center"
     style="background:rgba(0,0,0,0.75);backdrop-filter:blur(6px);display:none">
    <div class="w-full max-w-sm mx-4 rounded-2xl shadow-2xl" style="background:#0d2137;border:1px solid rgba(16,185,129,0.3)" @click.away="stockInModal=false">
        <div class="flex items-center justify-between p-5 border-b border-white/8">
            <div>
                <h3 class="text-base font-bold text-white flex items-center gap-2"><i class="fas fa-arrow-down text-emerald-400"></i> Stock In</h3>
                <p class="text-xs text-slate-400 mt-0.5" x-text="activeItem.name"></p>
            </div>
            <button @click="stockInModal=false" class="text-slate-500 hover:text-white transition"><i class="fas fa-times"></i></button>
        </div>
        <form :action="'<?php echo $baseUrl; ?>/stock-in<?php echo $cashierQs; ?>'" method="POST" class="p-5 space-y-4">
            <input type="hidden" name="item_id" :value="activeItem.id">
            <div class="rounded-xl p-3 flex items-center justify-between" style="background:rgba(16,185,129,0.08);border:1px solid rgba(16,185,129,0.15)">
                <span class="text-xs text-slate-400">Current Stock</span>
                <span class="font-bold text-emerald-400" x-text="activeItem.qty + ' ' + activeItem.unit"></span>
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium">Quantity to Add *</label>
                <input type="number" name="quantity" min="0.01" step="0.01" required placeholder="0"
                       class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none text-center text-lg font-bold"
                       style="background:rgba(255,255,255,0.07);border:1px solid rgba(16,185,129,0.3)">
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium">Supplier</label>
                <select name="supplier_id"
                        class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                        style="background:rgba(13,33,55,1);border:1px solid rgba(255,255,255,0.12)">
                    <option value="">None / Direct</option>
                    <?php foreach ($suppliersList as $sup): ?>
                    <option value="<?php echo $sup['id']; ?>">
                        <?php echo htmlspecialchars($sup['name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium">Single Piece/Unit Price *</label>
                <input type="number" name="unit_price" placeholder="0.00" min="0.01" step="0.01" required
                       class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                       style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium">Reference (Invoice / PO No.)</label>
                <input type="text" name="reference" placeholder="INV-0001"
                       class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                       style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium">Notes</label>
                <input type="text" name="notes" placeholder="Received from supplier…"
                       class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                       style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
            </div>
            <button type="submit" class="w-full py-2.5 rounded-xl font-semibold text-white text-sm"
                    style="background:linear-gradient(135deg,#10b981,#059669)">
                <i class="fas fa-check mr-1.5"></i> Confirm Stock In
            </button>
        </form>
    </div>
</div>


<!-- STOCK OUT MODAL -->
<div x-show="stockOutModal" @keydown.escape.window="stockOutModal=false"
     class="fixed inset-0 z-50 flex items-center justify-center"
     style="background:rgba(0,0,0,0.75);backdrop-filter:blur(6px);display:none">
    <div class="w-full max-w-sm mx-4 rounded-2xl shadow-2xl" style="background:#0d2137;border:1px solid rgba(239,68,68,0.3)" @click.away="stockOutModal=false">
        <div class="flex items-center justify-between p-5 border-b border-white/8">
            <div>
                <h3 class="text-base font-bold text-white flex items-center gap-2"><i class="fas fa-arrow-up text-red-400"></i> Stock Out</h3>
                <p class="text-xs text-slate-400 mt-0.5" x-text="activeItem.name"></p>
            </div>
            <button @click="stockOutModal=false" class="text-slate-500 hover:text-white transition"><i class="fas fa-times"></i></button>
        </div>
        <form :action="'<?php echo $baseUrl; ?>/stock-out<?php echo $cashierQs; ?>'" method="POST" class="p-5 space-y-4">
            <input type="hidden" name="item_id" :value="activeItem.id">
            <div class="rounded-xl p-3 flex items-center justify-between" style="background:rgba(239,68,68,0.08);border:1px solid rgba(239,68,68,0.15)">
                <span class="text-xs text-slate-400">Current Stock</span>
                <span class="font-bold text-red-400" x-text="activeItem.qty + ' ' + activeItem.unit"></span>
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium">Quantity to Remove *</label>
                <input type="number" name="quantity" min="0.01" step="0.01" required placeholder="0"
                       class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none text-center text-lg font-bold"
                       style="background:rgba(255,255,255,0.07);border:1px solid rgba(239,68,68,0.3)">
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium">Reference</label>
                <input type="text" name="reference" placeholder="Order ID / Ref…"
                       class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                       style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium">Notes</label>
                <input type="text" name="notes" placeholder="Used in kitchen…"
                       class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                       style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
            </div>
            <button type="submit" class="w-full py-2.5 rounded-xl font-semibold text-white text-sm"
                    style="background:linear-gradient(135deg,#ef4444,#dc2626)">
                <i class="fas fa-check mr-1.5"></i> Confirm Stock Out
            </button>
        </form>
    </div>
</div>


<!-- WASTE MODAL -->
<div x-show="wasteModal" @keydown.escape.window="wasteModal=false"
     class="fixed inset-0 z-50 flex items-center justify-center"
     style="background:rgba(0,0,0,0.75);backdrop-filter:blur(6px);display:none">
    <div class="w-full max-w-sm mx-4 rounded-2xl shadow-2xl" style="background:#0d2137;border:1px solid rgba(249,115,22,0.35)" @click.away="wasteModal=false">
        <div class="flex items-center justify-between p-5 border-b border-white/8">
            <div>
                <h3 class="text-base font-bold text-white flex items-center gap-2"><i class="fas fa-trash-restore-alt text-orange-400"></i> Record Waste</h3>
                <p class="text-xs text-slate-400 mt-0.5" x-text="activeItem.name"></p>
            </div>
            <button @click="wasteModal=false" class="text-slate-500 hover:text-white transition"><i class="fas fa-times"></i></button>
        </div>
        <form :action="'<?php echo $baseUrl; ?>/waste<?php echo $cashierQs; ?>'" method="POST" class="p-5 space-y-4">
            <input type="hidden" name="item_id" :value="activeItem.id">
            <div class="rounded-xl p-3 flex items-center justify-between" style="background:rgba(249,115,22,0.08);border:1px solid rgba(249,115,22,0.2)">
                <span class="text-xs text-slate-400">Current Stock</span>
                <span class="font-bold text-orange-400" x-text="activeItem.qty + ' ' + activeItem.unit"></span>
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium">Waste Reason *</label>
                <select name="reason" required class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                        style="background:rgba(13,33,55,1);border:1px solid rgba(249,115,22,0.3)">
                    <option value="Expired">Expired</option>
                    <option value="Spoiled">Spoiled</option>
                    <option value="Damaged">Damaged</option>
                    <option value="Theft">Theft</option>
                    <option value="Other">Other</option>
                </select>
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium">Quantity Wasted *</label>
                <input type="number" name="quantity" min="0.01" step="0.01" required placeholder="0"
                       class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none text-center text-lg font-bold"
                       style="background:rgba(255,255,255,0.07);border:1px solid rgba(249,115,22,0.3)">
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium">Additional Notes</label>
                <input type="text" name="notes" placeholder="More details (optional)…"
                       class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                       style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
            </div>
            <button type="submit" class="w-full py-2.5 rounded-xl font-semibold text-white text-sm"
                    style="background:linear-gradient(135deg,#f97316,#ea580c)">
                <i class="fas fa-check mr-1.5"></i> Record Waste
            </button>
        </form>
    </div>
</div>


<!-- ADJUST MODAL -->
<div x-show="adjustModal" @keydown.escape.window="adjustModal=false"
     class="fixed inset-0 z-50 flex items-center justify-center"
     style="background:rgba(0,0,0,0.75);backdrop-filter:blur(6px);display:none">
    <div class="w-full max-w-sm mx-4 rounded-2xl shadow-2xl" style="background:#0d2137;border:1px solid rgba(99,102,241,0.3)" @click.away="adjustModal=false">
        <div class="flex items-center justify-between p-5 border-b border-white/8">
            <div>
                <h3 class="text-base font-bold text-white flex items-center gap-2"><i class="fas fa-sliders-h text-indigo-400"></i> Adjust Stock</h3>
                <p class="text-xs text-slate-400 mt-0.5" x-text="activeItem.name"></p>
            </div>
            <button @click="adjustModal=false" class="text-slate-500 hover:text-white transition"><i class="fas fa-times"></i></button>
        </div>
        <form :action="'<?php echo $baseUrl; ?>/adjust<?php echo $cashierQs; ?>'" method="POST" class="p-5 space-y-4">
            <input type="hidden" name="item_id" :value="activeItem.id">
            <div class="rounded-xl p-3 flex items-center justify-between" style="background:rgba(99,102,241,0.08);border:1px solid rgba(99,102,241,0.15)">
                <span class="text-xs text-slate-400">Current Stock</span>
                <span class="font-bold text-indigo-400" x-text="activeItem.qty + ' ' + activeItem.unit"></span>
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium">Set New Quantity *</label>
                <input type="number" name="new_quantity" min="0" step="0.01" required :value="activeItem.qty"
                       class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none text-center text-lg font-bold"
                       style="background:rgba(255,255,255,0.07);border:1px solid rgba(99,102,241,0.3)">
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium">Reason *</label>
                <input type="text" name="notes" required placeholder="Physical count / Correction…"
                       class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                       style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
            </div>
            <button type="submit" class="w-full py-2.5 rounded-xl font-semibold text-white text-sm"
                    style="background:linear-gradient(135deg,#6366f1,#4f46e5)">
                <i class="fas fa-check mr-1.5"></i> Save Adjustment
            </button>
        </form>
    </div>
</div>


<!-- EDIT ITEM MODAL -->
<div x-show="editModal" @keydown.escape.window="editModal=false"
     class="fixed inset-0 z-50 flex items-center justify-center"
     style="background:rgba(0,0,0,0.75);backdrop-filter:blur(6px);display:none">
    <div class="w-full max-w-lg mx-4 rounded-2xl shadow-2xl overflow-y-auto" style="max-height:92vh;background:#0d2137;border:1px solid rgba(100,116,139,0.35)" @click.away="editModal=false">
        <div class="flex items-center justify-between p-5 border-b border-white/8 sticky top-0" style="background:#0d2137;z-index:1">
            <h3 class="text-base font-bold text-white flex items-center gap-2"><i class="fas fa-pen text-slate-400"></i> Edit Item</h3>
            <button @click="editModal=false" class="text-slate-500 hover:text-white transition"><i class="fas fa-times"></i></button>
        </div>
        <form :action="'<?php echo $baseUrl; ?>/update<?php echo $cashierQs; ?>'" method="POST" class="p-5 space-y-4">
            <input type="hidden" name="item_id" :value="activeItem.id">
            <div class="grid grid-cols-2 gap-4">
                <div class="col-span-2">
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Item Name *</label>
                    <input type="text" name="name" required :value="activeItem.name"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">SKU / Code</label>
                    <input type="text" name="sku" :value="activeItem.sku"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Category</label>
                    <select name="category_id" x-model="activeItem.category_id"
                            class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                            style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
                        <option value="">Uncategorized</option>
                        <?php foreach ($categoriesList as $cat): ?>
                        <option value="<?php echo $cat['id']; ?>">
                            <?php echo htmlspecialchars($cat['name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Unit</label>
                    <select name="unit" class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                            style="background:rgba(13,33,55,1);border:1px solid rgba(255,255,255,0.12)">
                        <template x-for="u in ['pcs','kg','g','L','ml','box','bag','bottle','dozen','pack']" :key="u">
                            <option :value="u" :selected="u===activeItem.unit" x-text="u"></option>
                        </template>
                    </select>
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Low Stock Alert At</label>
                    <input type="number" name="low_stock_threshold" min="0" step="0.01" :value="activeItem.low"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Cost Price</label>
                    <input type="number" name="cost_price" min="0" step="0.01" :value="activeItem.cost"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)">
                </div>
                <div class="col-span-2">
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Notes</label>
                    <textarea name="notes" rows="2"
                              class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none resize-none"
                              style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12)"
                              x-text="activeItem.notes"></textarea>
                </div>
            </div>
            <div class="flex gap-3">
                <button type="submit" class="flex-1 py-2.5 rounded-xl font-semibold text-white text-sm"
                        style="background:linear-gradient(135deg,#475569,#334155)">
                    <i class="fas fa-save mr-1.5"></i> Save Changes
                </button>
                <button type="button" @click="editModal=false"
                        class="px-5 py-2.5 rounded-xl text-sm text-slate-400 border border-white/10 hover:bg-white/5 transition">Cancel</button>
            </div>
        </form>
    </div>
</div>


<!-- STOCK HISTORY (LOGS) MODAL -->
<div x-show="logsModal" @keydown.escape.window="logsModal=false"
     class="fixed inset-0 z-50 flex items-center justify-center"
     style="background:rgba(0,0,0,0.75);backdrop-filter:blur(6px);display:none">
    <div class="w-full max-w-2xl mx-4 rounded-2xl shadow-2xl flex flex-col" style="max-height:88vh;background:#0d2137;border:1px solid rgba(59,130,246,0.25)" @click.away="logsModal=false">
        <div class="flex items-center justify-between p-5 border-b border-white/8 flex-shrink-0">
            <div>
                <h3 class="text-base font-bold text-white flex items-center gap-2"><i class="fas fa-history text-blue-400"></i> Stock History</h3>
                <p class="text-xs text-slate-400 mt-0.5" x-text="activeItem.name"></p>
            </div>
            <button @click="logsModal=false" class="text-slate-500 hover:text-white transition"><i class="fas fa-times"></i></button>
        </div>
        <!-- Log filters -->
        <div class="flex flex-wrap items-center gap-2 px-4 py-2.5 border-b border-white/5 flex-shrink-0">
            <template x-for="t in [{val:'',label:'All'},{val:'stock_in',label:'In'},{val:'stock_out',label:'Out'},{val:'waste',label:'Waste'},{val:'adjustment',label:'Adjust'},{val:'initial',label:'Initial'}]" :key="t.val">
                <button @click="setLogType(t.val)"
                        class="px-2.5 py-1 rounded-lg text-xs font-medium transition"
                        :style="logTypeFilter===t.val ? 'background:rgba(59,130,246,0.25);color:#93c5fd' : 'background:rgba(255,255,255,0.05);color:#64748b'"
                        x-text="t.label"></button>
            </template>
            <div class="ml-auto flex items-center gap-1.5">
                <input type="date" x-model="logDateFrom" @change="reloadLogs()"
                       class="text-xs px-2 py-1 rounded-lg text-white outline-none"
                       style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.1)">
                <span class="text-slate-600 text-xs">—</span>
                <input type="date" x-model="logDateTo" @change="reloadLogs()"
                       class="text-xs px-2 py-1 rounded-lg text-white outline-none"
                       style="background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.1)">
            </div>
        </div>
        <div class="flex-1 overflow-y-auto p-4">
            <div x-show="logsLoading" class="py-8 text-center text-slate-500 text-sm">
                <i class="fas fa-spinner fa-spin mr-2"></i> Loading…
            </div>
            <div x-show="!logsLoading && logs.length === 0" class="py-8 text-center text-slate-500 text-sm">
                No movements for this selection.
            </div>
            <div x-show="!logsLoading && logs.length > 0" class="space-y-2">
                <template x-for="l in logs" :key="l.id">
                    <div class="rounded-xl p-3 flex items-start gap-3"
                         style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06)">
                        <div class="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0 text-xs mt-0.5"
                             :style="logStyle(l.type)">
                            <i :class="logIcon(l.type)"></i>
                        </div>
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center justify-between gap-2">
                                <span class="text-xs font-semibold" :style="'color:'+logColor(l.type)" x-text="logLabel(l.type)"></span>
                                <span class="text-xs text-slate-500" x-text="formatDate(l.created_at)"></span>
                            </div>
                            <div class="flex items-center gap-2 mt-0.5">
                                <span class="text-slate-400 text-xs" x-text="l.quantity_before + ' \u2192 ' + l.quantity_after + ' ' + (l.item_unit || '')"></span>
                                <span class="text-xs font-bold" :class="parseFloat(l.quantity_change)>=0?'text-emerald-400':'text-red-400'"
                                      x-text="(parseFloat(l.quantity_change)>=0?'+':'')+parseFloat(l.quantity_change).toFixed(2)"></span>
                            </div>
                            <!-- Supplier & Purchase Price display for Stock In -->
                            <div class="flex flex-wrap items-center gap-x-3 gap-y-0.5 mt-1 text-[11px]">
                                <template x-if="l.unit_price">
                                    <span class="text-slate-400"><i class="fas fa-tag text-[9px] mr-1 text-slate-500"></i>Unit Price: <strong class="text-emerald-400" x-text="'৳' + parseFloat(l.unit_price).toFixed(2)"></strong></span>
                                </template>
                                <template x-if="l.supplier_name">
                                    <span class="text-slate-400"><i class="fas fa-truck text-[9px] mr-1 text-slate-500"></i>Supplier: <strong class="text-slate-300" x-text="l.supplier_name"></strong></span>
                                </template>
                            </div>
                            <div x-show="l.notes" class="text-xs text-slate-500 mt-1.5 truncate" x-text="l.notes"></div>
                            <div x-show="l.reference" class="text-xs text-blue-400 mt-0.5" x-text="'Ref: '+l.reference"></div>
                            <div class="text-xs text-slate-600 mt-0.5" x-text="'by '+(l.user_name||'System')"></div>
                        </div>
                    </div>
                </template>
            </div>
        </div>
    </div>
</div>

</div><!-- end x-data -->

<script>
function inventoryApp() {
    return {
        search:        '',
        activeCat:     '',
        addModal:      false,
        stockInModal:  false,
        stockOutModal: false,
        wasteModal:    false,
        adjustModal:   false,
        editModal:     false,
        logsModal:     false,
        activeItem:    { id:null, name:'', unit:'', qty:0, sku:'', category_id:'', category:'', low:10, cost:'', notes:'' },
        logs:          [],
        logsLoading:   false,
        logTypeFilter: '',
        logDateFrom:   '',
        logDateTo:     '',

        openStockIn(item)  { this.activeItem = item; this.stockInModal = true; },
        openStockOut(item) { this.activeItem = item; this.stockOutModal = true; },
        openWaste(item)    { this.activeItem = item; this.wasteModal = true; },
        openAdjust(item)   { this.activeItem = item; this.adjustModal = true; },
        openEdit(item)     { this.activeItem = item; this.editModal = true; },

        openLogs(id, name) {
            this.activeItem    = { ...this.activeItem, id, name };
            this.logsModal     = true;
            this.logTypeFilter = '';
            this.logDateFrom   = '';
            this.logDateTo     = '';
            this.reloadLogs();
        },

        setLogType(type) { this.logTypeFilter = type; this.reloadLogs(); },

        reloadLogs() {
            this.logs = []; this.logsLoading = true;
            let url = '<?php echo $logsBase; ?>/logs?item_id=' + this.activeItem.id;
            if (this.logTypeFilter) url += '&type=' + this.logTypeFilter;
            if (this.logDateFrom)   url += '&date_from=' + this.logDateFrom;
            if (this.logDateTo)     url += '&date_to='   + this.logDateTo;
            fetch(url)
                .then(r => r.json())
                .then(d => { this.logs = d; this.logsLoading = false; })
                .catch(() => { this.logsLoading = false; });
        },

        scrollToLowStock() {
            const el = document.getElementById('low-stock-panel');
            if (el) el.scrollIntoView({ behavior:'smooth', block:'start' });
        },

        filterCat(cat) { this.activeCat = cat; this.applyFilters(); },

        applyFilters() {
            const s = this.search.toLowerCase();
            const c = this.activeCat;
            document.querySelectorAll('.inv-row').forEach(row => {
                const nm = (row.dataset.name||'').includes(s) || !s;
                const ct = !c || (row.dataset.catid||'') === c;
                row.style.display = (nm && ct) ? '' : 'none';
            });
        },

        logStyle(type) {
            return {
                stock_in:   'background:rgba(16,185,129,0.15);color:#6ee7b7',
                stock_out:  'background:rgba(239,68,68,0.15);color:#f87171',
                waste:      'background:rgba(249,115,22,0.15);color:#fdba74',
                adjustment: 'background:rgba(99,102,241,0.15);color:#a5b4fc',
                initial:    'background:rgba(59,130,246,0.15);color:#93c5fd',
            }[type] || 'background:rgba(100,116,139,0.15);color:#94a3b8';
        },
        logIcon(type) {
            return { stock_in:'fas fa-arrow-down', stock_out:'fas fa-arrow-up', waste:'fas fa-trash-restore-alt',
                     adjustment:'fas fa-sliders-h', initial:'fas fa-box' }[type] || 'fas fa-circle';
        },
        logColor(type) {
            return { stock_in:'#6ee7b7', stock_out:'#f87171', waste:'#fdba74', adjustment:'#a5b4fc', initial:'#93c5fd' }[type] || '#94a3b8';
        },
        logLabel(type) {
            return { stock_in:'Stock In', stock_out:'Stock Out', waste:'Waste', adjustment:'Adjustment', initial:'Initial Stock' }[type] || type;
        },
        formatDate(dt) {
            const d = new Date(dt);
            return d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour:'2-digit', minute:'2-digit' });
        },

        init() {
            this.$watch('search', () => this.applyFilters());
        }
    };
}
</script>
