<div class="stock-header">
    <div class="sth-icon"><i class="fa-solid fa-layer-group"></i></div>
    <div class="sth-text">
        <h2>Stock Management</h2>
        <div class="sth-sub">
            <?= (int) $stats['total_materials'] ?> materials · Cost value: <?= formatMoney((float) $stats['total_value']) ?> · Tracked ingredients
        </div>
    </div>
    <div class="sth-actions">
        <button type="button" class="btn sth-btn" onclick="rmsOpenModal('rmsMovementsModal')"><i class="fa-solid fa-right-left"></i> Movements</button>
        <button type="button" class="btn sth-btn" onclick="rmsOpenModal('rmsQuickAdjustModal')"><i class="fa-solid fa-sliders"></i> Adjust Stock</button>
        <button type="button" class="btn sth-btn" onclick="window.print()"><i class="fa-solid fa-print"></i> Print</button>
    </div>
</div>

<div class="stat-mini-grid">
    <div class="stat-mini sm-blue"><div class="sm-value"><?= (int) $stats['total_materials'] ?></div><div class="sm-label">Total Materials</div></div>
    <div class="stat-mini sm-red"><div class="sm-value"><?= (int) $stats['out_of_stock'] ?></div><div class="sm-label">Out of Stock</div></div>
    <div class="stat-mini sm-gold"><div class="sm-value"><?= (int) $stats['low_stock'] ?></div><div class="sm-label">Low Stock</div></div>
    <div class="stat-mini sm-green"><div class="sm-value"><?= (int) $stats['in_stock_ok'] ?></div><div class="sm-label">In Stock OK</div></div>
    <div class="stat-mini sm-red"><div class="sm-value"><?= (int) $stats['expired'] ?></div><div class="sm-label">Expired</div></div>
    <div class="stat-mini sm-gold"><div class="sm-value"><?= (int) $stats['expiring_soon'] ?></div><div class="sm-label">Expiring ≤30d</div></div>
    <div class="stat-mini sm-green" style="flex-basis:100%;max-width:220px;"><div class="sm-value"><?= formatMoney((float) $stats['total_value']) ?></div><div class="sm-label">Cost Value</div></div>
</div>

<?php if (!empty($alerts)): ?>
<div class="alert-chips">
    <?php foreach ($alerts as $a): ?>
    <span class="alert-chip ac-<?= $a['color'] ?>"><i class="fa-solid <?= $a['icon'] ?>"></i> <?= e($a['text']) ?></span>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<div class="quick-actions">
    <?php if (Auth::can('stock', 'add')): ?>
    <button type="button" class="qa-btn" onclick="rmsOpenModal('rmsAddMaterialModal')" style="border:none;cursor:pointer;"><i class="fa-solid fa-plus"></i> Add Material</button>
    <?php endif; ?>
    <a href="<?= Router::url('kitchen-issue') ?>" class="qa-btn"><i class="fa-solid fa-kitchen-set"></i> Kitchen Issue</a>
    <a href="<?= Router::url('purchasing') ?>" class="qa-btn"><i class="fa-solid fa-file-invoice-dollar"></i> New Purchase Order</a>
    <a href="<?= Router::url('suppliers') ?>" class="qa-btn"><i class="fa-solid fa-truck"></i> Suppliers</a>
    <a href="<?= Router::url('reports?tab=stock') ?>" class="qa-btn"><i class="fa-solid fa-chart-line"></i> Stock Report</a>
</div>

<div class="panel">
    <div class="panel-head">
        <h3><i class="fa-solid fa-chart-line" style="color:var(--color-teal);margin-right:6px;"></i>Consumption Trend — Top 5 Materials (Last 7 Days)</h3>
    </div>
    <canvas id="rmsConsumptionChart" height="90"></canvas>
</div>

<div class="filter-bar">
    <div class="fb-search"><i class="fa-solid fa-magnifying-glass"></i><input type="text" id="rmsStockSearch" placeholder="Name, unit..." onkeyup="rmsFilterStockTable()"></div>
    <div class="fb-pills" id="rmsStatusPills">
        <button type="button" class="fb-pill active" data-filter="all" onclick="rmsSetStatusFilter('all', this)">All</button>
        <button type="button" class="fb-pill fp-green" data-filter="ok" onclick="rmsSetStatusFilter('ok', this)"><i class="fa-solid fa-circle-check"></i> OK</button>
        <button type="button" class="fb-pill fp-gold" data-filter="low" onclick="rmsSetStatusFilter('low', this)"><i class="fa-solid fa-triangle-exclamation"></i> Low</button>
        <button type="button" class="fb-pill fp-red" data-filter="out" onclick="rmsSetStatusFilter('out', this)"><i class="fa-solid fa-xmark"></i> Out</button>
    </div>
    <div class="fb-pills" id="rmsExpiryPills">
        <button type="button" class="fb-pill active" data-expiry="all" onclick="rmsSetExpiryFilter('all', this)">All Expiry</button>
        <button type="button" class="fb-pill fp-red" data-expiry="expired" onclick="rmsSetExpiryFilter('expired', this)"><i class="fa-solid fa-triangle-exclamation"></i> Expired</button>
        <button type="button" class="fb-pill fp-gold" data-expiry="soon" onclick="rmsSetExpiryFilter('soon', this)"><i class="fa-regular fa-clock"></i> ≤30d</button>
        <button type="button" class="fb-pill fp-green" data-expiry="safe" onclick="rmsSetExpiryFilter('safe', this)"><i class="fa-solid fa-circle-check"></i> Safe</button>
    </div>
    <button type="button" class="btn btn-secondary" onclick="rmsClearStockFilters()"><i class="fa-solid fa-xmark"></i></button>
</div>

<div class="dark-table-panel">
    <div class="dtp-head">
        <span><i class="fa-solid fa-table-list"></i> Stock Register</span>
        <span class="dtp-count" id="rmsStockCount"><?= count($materials) ?> materials</span>
    </div>
    <div style="overflow-x:auto;">
    <table class="data-table">
    <thead><tr><th>#</th><th>Material</th><th>Unit</th><th>Stock Level</th><th>Reorder</th><th>Days Left</th><th>Expiry</th><th>Cost Price</th><th>Stock Value</th><th>Status</th><th>Actions</th></tr></thead>
    <tbody>
    <?php foreach ($materials as $i => $m):
        $stockValue = (float) $m['current_stock'] * (float) $m['unit_cost'];
        $statusKey = 'ok'; $statusBadge = '<span class="badge badge-green"><i class="fa-solid fa-circle-check"></i> OK</span>';
        if (!$m['is_active']) { $statusKey = 'inactive'; $statusBadge = '<span class="badge badge-gray">Inactive</span>'; }
        elseif ($m['current_stock'] <= 0) { $statusKey = 'out'; $statusBadge = '<span class="badge badge-red"><i class="fa-solid fa-ban"></i> Out of Stock</span>'; }
        elseif ($m['current_stock'] <= $m['reorder_level']) { $statusKey = 'low'; $statusBadge = '<span class="badge badge-gold"><i class="fa-solid fa-triangle-exclamation"></i> Low Stock</span>'; }

        if ($m['days_left'] === null) { $daysLeftBadge = '<span class="badge badge-gray">No data</span>'; }
        elseif ($m['days_left'] <= 3) { $daysLeftBadge = '<span class="badge badge-red">' . $m['days_left'] . 'd</span>'; }
        elseif ($m['days_left'] <= 7) { $daysLeftBadge = '<span class="badge badge-gold">' . $m['days_left'] . 'd</span>'; }
        else { $daysLeftBadge = '<span class="badge badge-green">' . $m['days_left'] . 'd</span>'; }

        $expiryKey = 'none'; $expiryBadge = '<span style="color:var(--color-text-muted);">—</span>';
        if (!empty($m['expiry_date'])) {
            $daysToExpiry = (int) floor((strtotime($m['expiry_date']) - strtotime(date('Y-m-d'))) / 86400);
            if ($daysToExpiry < 0) { $expiryKey = 'expired'; $expiryBadge = '<span class="badge badge-red"><i class="fa-solid fa-triangle-exclamation"></i> EXPIRED</span>'; }
            elseif ($daysToExpiry <= 30) { $expiryKey = 'soon'; $expiryBadge = '<span class="badge badge-gold">' . $daysToExpiry . 'd left</span>'; }
            else { $expiryKey = 'safe'; $expiryBadge = '<span class="badge badge-green">' . date('d M Y', strtotime($m['expiry_date'])) . '</span>'; }
        }

        $barPct = $m['reorder_level'] > 0 ? min(100, round(((float) $m['current_stock'] / ((float) $m['reorder_level'] * 2)) * 100)) : ($m['current_stock'] > 0 ? 100 : 0);
        $barColor = $statusKey === 'out' ? 'var(--color-danger)' : ($statusKey === 'low' ? 'var(--color-accent)' : 'var(--color-success)');
    ?>
    <tr class="rms-stock-row" data-name="<?= e(mb_strtolower($m['material_name'])) ?>" data-status="<?= $statusKey ?>" data-expiry="<?= $expiryKey ?>">
        <td><?= $i + 1 ?></td>
        <td><strong><?= e($m['material_name']) ?></strong></td>
        <td><?= e($m['unit']) ?></td>
        <td>
            <div class="stock-level-cell">
                <span><?= number_format((float) $m['current_stock'], 2) ?></span>
                <div class="stock-bar"><div class="stock-bar-fill" style="width:<?= $barPct ?>%;background:<?= $barColor ?>;"></div></div>
            </div>
        </td>
        <td><?= number_format((float) $m['reorder_level'], 2) ?></td>
        <td><?= $daysLeftBadge ?></td>
        <td><?= $expiryBadge ?></td>
        <td><?= formatMoney((float) $m['unit_cost']) ?></td>
        <td><strong><?= formatMoney($stockValue) ?></strong></td>
        <td><?= $statusBadge ?></td>
        <td style="white-space:nowrap;">
            <?php if (($statusKey === 'low' || $statusKey === 'out') && Auth::can('purchasing', 'add')): ?>
            <a href="<?= Router::url('purchasing?reorder_id=' . $m['id'] . '&reorder_qty=' . max(1, (float) $m['reorder_level'] * 2 - (float) $m['current_stock'])) ?>" class="icon-btn icon-btn-teal" title="Quick Reorder"><i class="fa-solid fa-cart-plus"></i></a>
            <?php endif; ?>
            <?php if (Auth::can('stock', 'edit')): ?>
            <button type="button" class="icon-btn icon-btn-blue" onclick="rmsOpenModal('rmsStockInModal<?= $m['id'] ?>')" title="Stock In"><i class="fa-solid fa-arrow-down-to-bracket"></i></button>
            <button type="button" class="icon-btn icon-btn-gold" onclick="rmsOpenModal('rmsAdjustModal<?= $m['id'] ?>')" title="Adjust"><i class="fa-solid fa-sliders"></i></button>
            <button type="button" class="icon-btn icon-btn-gray" onclick="rmsOpenModal('rmsHistoryModal<?= $m['id'] ?>')" title="History"><i class="fa-solid fa-clock-rotate-left"></i></button>
            <button type="button" class="icon-btn icon-btn-gray" onclick="rmsOpenModal('rmsEditModal<?= $m['id'] ?>')" title="Edit"><i class="fa-solid fa-pen"></i></button>
            <?php endif; ?>
            <?php if (Auth::can('stock', 'delete')): ?>
            <form method="POST" action="<?= Router::url('stock/delete') ?>" style="display:inline;" onsubmit="return confirm('Delete this material? If it has stock history, it will be deactivated instead.');">
                <?= $csrf ?>
                <input type="hidden" name="id" value="<?= $m['id'] ?>">
                <button type="submit" class="icon-btn icon-btn-red"><i class="fa-solid fa-trash"></i></button>
            </form>
            <?php endif; ?>
        </td>
    </tr>
    <?php endforeach; ?>
    <?php if (empty($materials)): ?>
    <tr><td colspan="11" style="text-align:center;color:var(--color-text-muted);padding:30px;">No raw materials yet — add your first ingredient.</td></tr>
    <?php endif; ?>
    </tbody>
    </table>
    </div>
</div>

<!-- ===== Add Raw Material Modal ===== -->
<?php if (Auth::can('stock', 'add')): ?>
<div class="rms-modal-overlay" id="rmsAddMaterialModal">
    <div class="rms-modal" style="max-width:400px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-plus" style="color:var(--color-teal);margin-right:6px;"></i>Add Raw Material</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsAddMaterialModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('stock/store') ?>">
            <?= $csrf ?>
            <div class="form-group">
                <label>Material Name</label>
                <input type="text" name="material_name" class="form-control" placeholder="e.g. Rice, Chicken, Coconut Oil" required>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                <div class="form-group">
                    <label>Unit</label>
                    <select name="unit" class="form-control">
                        <option value="kg">kg</option><option value="g">g</option><option value="l">l</option><option value="ml">ml</option><option value="pcs">pcs</option>
                    </select>
                </div>
                <div class="form-group"><label>Unit Cost (Rs.)</label><input type="number" step="0.01" name="unit_cost" class="form-control" value="0"></div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                <div class="form-group"><label>Opening Stock</label><input type="number" step="0.001" name="opening_stock" class="form-control" value="0"></div>
                <div class="form-group"><label>Reorder Level</label><input type="number" step="0.001" name="reorder_level" class="form-control" value="0"></div>
            </div>
            <div class="form-group"><label>Expiry Date (optional)</label><input type="date" name="expiry_date" class="form-control"></div>
            <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-plus"></i> Add Material</button>
        </form>
    </div>
</div>
<?php endif; ?>

<!-- ===== Movements Modal (all materials) ===== -->
<div class="rms-modal-overlay" id="rmsMovementsModal">
    <div class="rms-modal" style="max-width:640px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-right-left" style="color:var(--color-teal);margin-right:6px;"></i>Recent Stock Movements</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsMovementsModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <div style="max-height:60vh;overflow-y:auto;">
        <?php
        $typeMeta = [
            'PURCHASE_IN'   => ['label' => 'Purchase In',   'badge' => 'badge-green', 'icon' => 'fa-arrow-down-to-bracket'],
            'SALE_DEDUCT'   => ['label' => 'Sale',          'badge' => 'badge-blue',  'icon' => 'fa-receipt'],
            'ADJUSTMENT'    => ['label' => 'Adjustment',    'badge' => 'badge-gold',  'icon' => 'fa-sliders'],
            'WASTAGE'       => ['label' => 'Wastage',       'badge' => 'badge-red',   'icon' => 'fa-trash'],
            'KITCHEN_ISSUE' => ['label' => 'Kitchen Issue', 'badge' => 'badge-blue',  'icon' => 'fa-kitchen-set'],
        ];
        foreach ($allMovements as $mv): $tm = $typeMeta[$mv['transaction_type']] ?? ['label' => $mv['transaction_type'], 'badge' => 'badge-gray', 'icon' => 'fa-circle'];
        ?>
        <div class="history-row">
            <div class="hr-top">
                <span class="badge <?= $tm['badge'] ?>"><i class="fa-solid <?= $tm['icon'] ?>"></i> <?= e($tm['label']) ?></span>
                <strong><?= e($mv['material_name']) ?></strong>
                <span style="<?= $mv['quantity'] < 0 ? 'color:var(--color-danger);' : 'color:var(--color-success);' ?>margin-left:auto;font-weight:700;">
                    <?= $mv['quantity'] >= 0 ? '+' : '' ?><?= number_format((float) $mv['quantity'], 2) ?> <?= e($mv['unit']) ?>
                </span>
            </div>
            <div class="hr-meta">
                <span><i class="fa-regular fa-clock"></i> <?= date('d M, h:i A', strtotime($mv['created_at'])) ?></span>
                <span><i class="fa-solid fa-user"></i> <?= e($mv['created_by_name'] ?? 'System') ?></span>
                <?php if ($mv['notes']): ?><span><i class="fa-solid fa-note-sticky"></i> <?= e($mv['notes']) ?></span><?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
        <?php if (empty($allMovements)): ?>
        <div style="text-align:center;color:var(--color-text-muted);padding:30px 0;font-size:13px;">No stock movements yet.</div>
        <?php endif; ?>
        </div>
    </div>
</div>

<!-- ===== Quick Adjust Modal (header button — pick any material) ===== -->
<?php if (Auth::can('stock', 'edit')): ?>
<div class="rms-modal-overlay" id="rmsQuickAdjustModal">
    <div class="rms-modal" style="max-width:380px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-sliders" style="color:var(--color-accent);margin-right:6px;"></i>Adjust Stock</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsQuickAdjustModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('stock/adjust') ?>">
            <?= $csrf ?>
            <div class="form-group">
                <label>Material</label>
                <select name="id" class="form-control" required>
                    <?php foreach ($materials as $m): ?>
                    <option value="<?= $m['id'] ?>"><?= e($m['material_name']) ?> (<?= number_format((float) $m['current_stock'], 2) ?> <?= e($m['unit']) ?>)</option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Direction</label>
                <div style="display:flex;gap:8px;">
                    <label style="flex:1;display:flex;align-items:center;gap:6px;font-size:12.5px;font-weight:600;border:1px solid var(--color-border);border-radius:8px;padding:8px;">
                        <input type="radio" name="direction" value="add" checked> Add
                    </label>
                    <label style="flex:1;display:flex;align-items:center;gap:6px;font-size:12.5px;font-weight:600;border:1px solid var(--color-border);border-radius:8px;padding:8px;">
                        <input type="radio" name="direction" value="remove"> Remove
                    </label>
                </div>
            </div>
            <div class="form-group">
                <label>Reason</label>
                <select name="adjust_type" class="form-control">
                    <option value="ADJUSTMENT">Manual Adjustment</option>
                    <option value="WASTAGE">Wastage / Spoilage</option>
                </select>
            </div>
            <div class="form-group"><label>Quantity</label><input type="number" step="0.001" name="quantity" class="form-control" required></div>
            <div class="form-group"><label>Notes</label><input type="text" name="notes" class="form-control"></div>
            <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-check"></i> Save Adjustment</button>
        </form>
    </div>
</div>
<?php endif; ?>

<?php foreach ($materials as $m): ?>

<!-- Stock In Modal -->
<div class="rms-modal-overlay" id="rmsStockInModal<?= $m['id'] ?>">
    <div class="rms-modal" style="max-width:380px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-arrow-down-to-bracket" style="color:var(--color-success);margin-right:6px;"></i>Stock In — <?= e($m['material_name']) ?></h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsStockInModal<?= $m['id'] ?>')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('stock/stock-in') ?>">
            <?= $csrf ?>
            <input type="hidden" name="id" value="<?= $m['id'] ?>">
            <div class="form-group"><label>Quantity Received (<?= e($m['unit']) ?>)</label><input type="number" step="0.001" name="quantity" class="form-control" required></div>
            <div class="form-group"><label>Unit Cost (Rs.) — leave blank to keep current</label><input type="number" step="0.01" name="unit_cost" class="form-control" placeholder="<?= number_format((float) $m['unit_cost'], 2) ?>"></div>
            <div class="form-group"><label>New Expiry Date (optional)</label><input type="date" name="expiry_date" class="form-control" value="<?= e($m['expiry_date'] ?? '') ?>"></div>
            <div class="form-group"><label>Notes</label><input type="text" name="notes" class="form-control" placeholder="e.g. Purchased from ABC Traders"></div>
            <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-check"></i> Add Stock</button>
        </form>
    </div>
</div>

<!-- Adjust Modal -->
<div class="rms-modal-overlay" id="rmsAdjustModal<?= $m['id'] ?>">
    <div class="rms-modal" style="max-width:380px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-sliders" style="color:var(--color-accent);margin-right:6px;"></i>Adjust — <?= e($m['material_name']) ?></h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsAdjustModal<?= $m['id'] ?>')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('stock/adjust') ?>">
            <?= $csrf ?>
            <input type="hidden" name="id" value="<?= $m['id'] ?>">
            <div class="form-group">
                <label>Direction</label>
                <div style="display:flex;gap:8px;">
                    <label style="flex:1;display:flex;align-items:center;gap:6px;font-size:12.5px;font-weight:600;border:1px solid var(--color-border);border-radius:8px;padding:8px;">
                        <input type="radio" name="direction" value="add" checked> Add
                    </label>
                    <label style="flex:1;display:flex;align-items:center;gap:6px;font-size:12.5px;font-weight:600;border:1px solid var(--color-border);border-radius:8px;padding:8px;">
                        <input type="radio" name="direction" value="remove"> Remove
                    </label>
                </div>
            </div>
            <div class="form-group">
                <label>Reason</label>
                <select name="adjust_type" class="form-control">
                    <option value="ADJUSTMENT">Manual Adjustment (e.g. stock count correction)</option>
                    <option value="WASTAGE">Wastage / Spoilage</option>
                </select>
            </div>
            <div class="form-group"><label>Quantity (<?= e($m['unit']) ?>)</label><input type="number" step="0.001" name="quantity" class="form-control" required></div>
            <div class="form-group"><label>Notes</label><input type="text" name="notes" class="form-control" placeholder="Reason for adjustment"></div>
            <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-check"></i> Save Adjustment</button>
        </form>
    </div>
</div>

<!-- Edit Modal -->
<div class="rms-modal-overlay" id="rmsEditModal<?= $m['id'] ?>">
    <div class="rms-modal" style="max-width:380px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-pen" style="color:var(--color-teal);margin-right:6px;"></i>Edit — <?= e($m['material_name']) ?></h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsEditModal<?= $m['id'] ?>')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('stock/update') ?>">
            <?= $csrf ?>
            <input type="hidden" name="id" value="<?= $m['id'] ?>">
            <div class="form-group"><label>Material Name</label><input type="text" name="material_name" class="form-control" value="<?= e($m['material_name']) ?>" required></div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                <div class="form-group">
                    <label>Unit</label>
                    <select name="unit" class="form-control">
                        <?php foreach (['kg','g','l','ml','pcs'] as $u): ?>
                        <option value="<?= $u ?>" <?= $m['unit'] === $u ? 'selected' : '' ?>><?= $u ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group"><label>Unit Cost (Rs.)</label><input type="number" step="0.01" name="unit_cost" class="form-control" value="<?= e((string)$m['unit_cost']) ?>"></div>
            </div>
            <div class="form-group"><label>Reorder Level</label><input type="number" step="0.001" name="reorder_level" class="form-control" value="<?= e((string)$m['reorder_level']) ?>"></div>
            <div class="form-group"><label>Expiry Date</label><input type="date" name="expiry_date" class="form-control" value="<?= e($m['expiry_date'] ?? '') ?>"></div>
            <div style="font-size:11px;color:var(--color-text-muted);margin-bottom:12px;">
                Current stock (<?= number_format((float)$m['current_stock'],2) ?> <?= e($m['unit']) ?>) can only be changed via Stock In / Adjust — this keeps an audit trail.
            </div>
            <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-floppy-disk"></i> Save Changes</button>
        </form>
    </div>
</div>

<!-- History Modal -->
<div class="rms-modal-overlay" id="rmsHistoryModal<?= $m['id'] ?>">
    <div class="rms-modal" style="max-width:520px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-clock-rotate-left" style="color:var(--color-teal);margin-right:6px;"></i><?= e($m['material_name']) ?> — Transaction History</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsHistoryModal<?= $m['id'] ?>')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <div style="max-height:60vh;overflow-y:auto;">
            <?php
            $typeMeta2 = [
                'PURCHASE_IN'   => ['label' => 'Purchase In',   'badge' => 'badge-green', 'icon' => 'fa-arrow-down-to-bracket'],
                'SALE_DEDUCT'   => ['label' => 'Sale',          'badge' => 'badge-blue',  'icon' => 'fa-receipt'],
                'ADJUSTMENT'    => ['label' => 'Adjustment',    'badge' => 'badge-gold',  'icon' => 'fa-sliders'],
                'WASTAGE'       => ['label' => 'Wastage',       'badge' => 'badge-red',   'icon' => 'fa-trash'],
                'KITCHEN_ISSUE' => ['label' => 'Kitchen Issue', 'badge' => 'badge-blue',  'icon' => 'fa-kitchen-set'],
            ];
            $history = $historyByMaterial[$m['id']] ?? [];
            ?>
            <?php foreach ($history as $h): $tm = $typeMeta2[$h['transaction_type']] ?? ['label' => $h['transaction_type'], 'badge' => 'badge-gray', 'icon' => 'fa-circle']; ?>
            <div class="history-row">
                <div class="hr-top">
                    <span class="badge <?= $tm['badge'] ?>"><i class="fa-solid <?= $tm['icon'] ?>"></i> <?= e($tm['label']) ?></span>
                    <strong style="<?= $h['quantity'] < 0 ? 'color:var(--color-danger);' : 'color:var(--color-success);' ?>">
                        <?= $h['quantity'] >= 0 ? '+' : '' ?><?= number_format((float) $h['quantity'], 2) ?> <?= e($m['unit']) ?>
                    </strong>
                    <span class="hr-amount"><?= date('d M, h:i A', strtotime($h['created_at'])) ?></span>
                </div>
                <div class="hr-meta">
                    <?php if ($h['notes']): ?><span><i class="fa-solid fa-note-sticky"></i> <?= e($h['notes']) ?></span><?php endif; ?>
                    <span><i class="fa-solid fa-user"></i> <?= e($h['created_by_name'] ?? 'System') ?></span>
                </div>
            </div>
            <?php endforeach; ?>
            <?php if (empty($history)): ?>
            <div style="text-align:center;color:var(--color-text-muted);padding:30px 0;font-size:13px;">No transactions yet.</div>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php endforeach; ?>

<style>
.history-row { padding: 10px 0; border-bottom: 1px solid var(--color-border); font-size: 12.5px; }
.hr-top { display: flex; align-items: center; gap: 8px; margin-bottom: 4px; flex-wrap: wrap; }
.hr-amount { margin-left: auto; color: var(--color-text-muted); font-size: 11.5px; }
.hr-meta { display: flex; gap: 14px; color: var(--color-text-muted); flex-wrap: wrap; margin-top: 2px; }

/* ---- Stock header banner ---- */
.stock-header {
    display: flex; align-items: center; gap: 16px;
    background: linear-gradient(120deg, #0F6E5E 0%, #0A4F44 100%);
    color: #fff; border-radius: var(--radius); padding: 20px 24px; margin-bottom: 20px; flex-wrap: wrap;
}
.stock-header .sth-icon { width: 44px; height: 44px; border-radius: 11px; background: rgba(255,255,255,0.16); display: flex; align-items: center; justify-content: center; font-size: 19px; flex-shrink: 0; }
.stock-header .sth-text { flex: 1; min-width: 200px; }
.stock-header h2 { font-size: 19px; margin: 0 0 2px; }
.stock-header .sth-sub { font-size: 12.5px; color: rgba(255,255,255,0.8); }
.stock-header .sth-actions { display: flex; gap: 8px; flex-wrap: wrap; }
.sth-btn { background: rgba(255,255,255,0.14); color: #fff; border: 1px solid rgba(255,255,255,0.25); font-size: 12.5px; }
.sth-btn:hover { background: rgba(255,255,255,0.24); }

/* ---- Bordered mini stat cards ---- */
.stat-mini-grid { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; }
.stat-mini { flex: 1; min-width: 130px; background: #fff; border: 1.5px solid; border-radius: 10px; padding: 14px 12px; text-align: center; }
.stat-mini .sm-value { font-size: 22px; font-weight: 700; font-family: var(--font-display); }
.stat-mini .sm-label { font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.04em; color: var(--color-text-muted); font-weight: 700; margin-top: 2px; }
.sm-blue  { border-color: #B7CDEE; } .sm-blue .sm-value { color: var(--stat-blue-2); }
.sm-red   { border-color: #F0BEBE; } .sm-red .sm-value { color: var(--color-danger); }
.sm-gold  { border-color: #EAD3A0; } .sm-gold .sm-value { color: #8A611F; }
.sm-green { border-color: #C3DBB4; } .sm-green .sm-value { color: var(--color-success); }

/* ---- Alert chips ---- */
.alert-chips { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 16px; }
.alert-chip { display: inline-flex; align-items: center; gap: 6px; padding: 7px 14px; border-radius: 100px; font-size: 12px; font-weight: 700; }
.ac-red { background: var(--color-danger); color: #fff; }
.ac-gold { background: var(--color-accent); color: #fff; }
.ac-blue { background: var(--stat-blue); color: #fff; }

.quick-actions { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 20px; }
.qa-btn {
    flex: 1; min-width: 140px; display: flex; align-items: center; justify-content: center; gap: 8px;
    padding: 12px 14px; background: var(--color-surface); border: 1px solid var(--color-border); border-radius: 10px;
    font-size: 12.5px; font-weight: 700; color: var(--color-text); box-shadow: var(--shadow-sm);
    transition: transform 0.15s ease, box-shadow 0.15s ease;
}
.qa-btn:hover { transform: translateY(-2px); box-shadow: var(--shadow-md); color: var(--color-teal); }
.qa-btn i { color: var(--color-accent); }

/* ---- Filter bar ---- */
.filter-bar { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; margin-bottom: 16px; background: var(--color-surface); border: 1px solid var(--color-border); border-radius: 10px; padding: 10px 14px; }
.fb-search { display: flex; align-items: center; gap: 8px; background: var(--color-bg); border-radius: 8px; padding: 8px 12px; flex: 1; min-width: 180px; color: var(--color-text-muted); }
.fb-search input { border: none; background: transparent; outline: none; font-size: 13px; width: 100%; color: var(--color-text); }
.fb-pills { display: flex; gap: 6px; flex-wrap: wrap; }
.fb-pill { padding: 7px 13px; border-radius: 100px; border: 1px solid var(--color-border); background: #fff; font-size: 12px; font-weight: 700; color: var(--color-text-muted); cursor: pointer; display: flex; align-items: center; gap: 5px; }
.fb-pill.active { background: var(--color-text); color: #fff; border-color: var(--color-text); }
.fb-pill.fp-green.active { background: var(--stat-green); border-color: var(--stat-green); }
.fb-pill.fp-gold.active { background: var(--color-accent); border-color: var(--color-accent); }
.fb-pill.fp-red.active { background: var(--color-danger); border-color: var(--color-danger); }

/* ---- Dark table header panel ---- */
.dark-table-panel { border-radius: var(--radius); overflow: hidden; box-shadow: var(--shadow-sm); margin-bottom: 20px; }
.dtp-head { background: #1C2333; color: #fff; padding: 12px 18px; display: flex; justify-content: space-between; align-items: center; font-size: 13px; font-weight: 700; }
.dtp-count { background: rgba(255,255,255,0.15); font-size: 11px; padding: 3px 10px; border-radius: 100px; font-weight: 700; }
.dark-table-panel .data-table { margin: 0; background: #fff; }
.dark-table-panel .data-table th { background: #fff; }

/* ---- Stock level bar ---- */
.stock-level-cell { display: flex; flex-direction: column; gap: 4px; min-width: 70px; }
.stock-bar { width: 100%; height: 5px; background: var(--color-border); border-radius: 4px; overflow: hidden; }
.stock-bar-fill { height: 100%; border-radius: 4px; }

/* ---- Compact colored icon buttons ---- */
.icon-btn {
    display: inline-flex; align-items: center; justify-content: center; width: 30px; height: 30px; border-radius: 7px;
    border: none; cursor: pointer; margin-right: 3px; font-size: 12.5px;
}
.icon-btn-blue { background: rgba(59,120,216,0.14); color: #2E5FB0; }
.icon-btn-gold { background: rgba(193,135,46,0.14); color: #8A611F; }
.icon-btn-teal { background: rgba(29,122,140,0.14); color: #1D7A8C; }
.icon-btn-red  { background: rgba(178,58,58,0.14); color: #8A2A2A; }
.icon-btn-gray { background: rgba(20,25,40,0.06); color: var(--color-text-muted); }
.icon-btn:hover { filter: brightness(0.92); }
</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script>
<script>
const rmsTrendColors = ['#1D7A8C', '#C1872E', '#7A2E2E', '#4B6B3A', '#7C4DBE'];
const rmsTrendDatasets = <?= json_encode($trendDatasets) ?>.map((d, i) => ({
    label: d.label, data: d.data, borderColor: rmsTrendColors[i % rmsTrendColors.length],
    backgroundColor: 'transparent', tension: 0.35, pointRadius: 3,
}));
new Chart(document.getElementById('rmsConsumptionChart'), {
    type: 'line',
    data: { labels: <?= json_encode($trendLabels) ?>, datasets: rmsTrendDatasets },
    options: {
        responsive: true,
        plugins: { legend: { position: 'bottom', labels: { boxWidth: 10, font: { size: 11 } } } },
        scales: { y: { beginAtZero: true }, x: { grid: { display: false } } }
    }
});

let rmsStatusFilter = 'all';
let rmsExpiryFilter = 'all';

function rmsSetStatusFilter(val, btn) {
    rmsStatusFilter = val;
    document.querySelectorAll('#rmsStatusPills .fb-pill').forEach(p => p.classList.remove('active'));
    btn.classList.add('active');
    rmsApplyStockFilters();
}
function rmsSetExpiryFilter(val, btn) {
    rmsExpiryFilter = val;
    document.querySelectorAll('#rmsExpiryPills .fb-pill').forEach(p => p.classList.remove('active'));
    btn.classList.add('active');
    rmsApplyStockFilters();
}
function rmsFilterStockTable() { rmsApplyStockFilters(); }

function rmsApplyStockFilters() {
    const q = document.getElementById('rmsStockSearch').value.toLowerCase();
    let visible = 0;
    document.querySelectorAll('.rms-stock-row').forEach(row => {
        const matchesName = row.dataset.name.includes(q);
        const matchesStatus = rmsStatusFilter === 'all' || row.dataset.status === rmsStatusFilter;
        const matchesExpiry = rmsExpiryFilter === 'all' || row.dataset.expiry === rmsExpiryFilter;
        const show = matchesName && matchesStatus && matchesExpiry;
        row.style.display = show ? '' : 'none';
        if (show) visible++;
    });
    document.getElementById('rmsStockCount').textContent = visible + ' materials';
}
function rmsClearStockFilters() {
    document.getElementById('rmsStockSearch').value = '';
    rmsStatusFilter = 'all'; rmsExpiryFilter = 'all';
    document.querySelectorAll('.fb-pill').forEach(p => p.classList.remove('active'));
    document.querySelector('#rmsStatusPills .fb-pill[data-filter="all"]').classList.add('active');
    document.querySelector('#rmsExpiryPills .fb-pill[data-expiry="all"]').classList.add('active');
    rmsApplyStockFilters();
}
</script>
