<?php
require_once 'includes/db.php';
$inventory = fetchAll("SELECT i.*, s.name as supplier_name FROM inventory_items i LEFT JOIN suppliers s ON i.supplier_id = s.id WHERE i.company_id = ? ORDER BY i.created_at DESC", [$_SESSION['company_id']]);
$suppliers = fetchAll("SELECT * FROM suppliers WHERE company_id = ? AND status = 'Active'", [$_SESSION['company_id']]);
$units = fetchAll("SELECT * FROM units ORDER BY name ASC");
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; gap: 1rem; flex-wrap: wrap;">
    <div style="position: relative; flex: 1; max-width: 400px; min-width: 300px;">
        <i class="fas fa-search" style="position: absolute; left: 1rem; top: 50%; transform: translateY(-50%); color: var(--text-muted); opacity: 0.5;"></i>
        <input type="text" id="inventorySearch" class="form-control" placeholder="Search by name, SKU, or supplier..." style="padding-left: 2.75rem; border-radius: 50px; background: var(--bg-card); border: 1px solid var(--border); box-shadow: var(--shadow);">
    </div>
    <div style="display: flex; gap: 1rem; align-items: center;">
        <div style="background: var(--bg-dark); padding: 0.5rem 1rem; border-radius: 12px; border: 1px solid var(--border); display: flex; align-items: center; gap: 0.5rem;">
            <span style="font-size: 0.75rem; color: var(--text-muted);">Total Items:</span>
            <span id="item-count-badge" style="font-weight: 700; color: var(--primary);"><?php echo count($inventory); ?></span>
        </div>
        <button class="btn btn-primary" onclick="openAddInventoryModal()">
            <i class="fas fa-plus"></i> Add Item
        </button>
    </div>
</div>

<div class="card" style="padding: 0; overflow: hidden; border-radius: 20px;">
    <!-- Desktop Table View -->
    <div class="table-container desktop-only">
        <table>
            <thead>
                <tr>
                    <th style="padding-left: 1.5rem;">SKU</th>
                    <th>Item Name</th>
                    <th>Category</th>
                    <th>Stock Level</th>
                    <th>Reserved Qty</th>
                    <th>Status</th>
                    <th>Supplier</th>
                    <th>Unit Price</th>
                    <th style="text-align: right; padding-right: 1.5rem;">Action</th>
                </tr>
            </thead>
            <tbody id="inventory-table-body">
                <!-- Rows injected by JS -->
            </tbody>
        </table>
    </div>

    <!-- Mobile Card View -->
    <div id="inventory-cards-body" class="mobile-only" style="display: none; flex-direction: column; gap: 1rem; padding: 1rem;">
        <!-- Cards injected by JS -->
    </div>

    <!-- Pagination Footer -->
    <div style="padding: 1.5rem; display: flex; justify-content: space-between; align-items: center; border-top: 1px solid var(--border); background: var(--bg-dark);">
        <div style="font-size: 0.85rem; color: var(--text-muted);" id="pagination-info">
            Showing 0 to 0 of 0 items
        </div>
        <div style="display: flex; gap: 0.5rem;" id="pagination-controls">
            <!-- Buttons injected by JS -->
        </div>
    </div>
</div>

<!-- Inventory Modal -->
<div id="inventoryModal" class="modal-overlay">
    <div class="modal-content">
        <div class="modal-header">
            <h2 id="modalTitle">Add New Item</h2>
            <button class="btn" style="background: none; color: var(--text-muted);" onclick="closeModal('inventoryModal')">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <form id="inventoryForm">
            <input type="hidden" id="item_id" name="id">
            <div class="modal-body">
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Item SKU <span class="required-mark">*</span></label>
                        <input type="text" id="item_sku" name="sku" class="form-control" placeholder="SKU-12345678" readonly required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Item Name <span class="required-mark">*</span></label>
                        <input type="text" id="item_name" name="name" class="form-control" placeholder="e.g. Blue Denim Fabric" required>
                    </div>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Category <span class="required-mark">*</span></label>
                        <select id="item_category" name="category" class="form-control" required>
                            <option value="Fabric">Fabric</option>
                            <option value="Buttons">Buttons</option>
                            <option value="Thread">Thread</option>
                            <option value="Zippers">Zippers</option>
                            <option value="Packaging">Packaging</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Unit <span class="required-mark">*</span></label>
                        <select id="item_unit" name="unit" class="form-control" required>
                            <option value="">Select Unit</option>
                            <?php foreach ($units as $unit): ?>
                            <option value="<?php echo $unit['name']; ?>"><?php echo $unit['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Current Stock (Read-Only)</label>
                        <input type="number" id="item_stock" name="stock" class="form-control" step="0.0001" readonly style="background: var(--bg-dark); color: var(--text-muted); border-color: transparent;">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Stock Addition <span class="required-mark">*</span></label>
                        <input type="number" id="item_stock_addition" name="stock_addition" class="form-control" step="0.0001" value="0" required>
                        <small style="font-size: 0.7rem; color: var(--primary); font-weight: 600; margin-top: 0.25rem; display: block;">Enter quantity to add to current stock</small>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Min Level (Alert) <span class="required-mark">*</span></label>
                        <input type="number" id="item_min_level" name="min_level" class="form-control" step="0.0001" required>
                    </div>
                    <div class="form-group" style="grid-column: span 2;">
                        <label class="form-label">Buying Unit Price <span class="required-mark">*</span></label>
                        <div style="display: flex; align-items: stretch; width: 100%;">
                            <span style="background: var(--bg-dark); border: 1px solid rgba(0,0,0,0.1); border-right: none; padding: 0.625rem 0.875rem; border-radius: 10px 0 0 10px; font-weight: 700; color: var(--text-muted); display: inline-flex; align-items: center; font-size: 0.95rem; white-space: nowrap;"><?php echo $_SESSION['company_currency'] ?? '$'; ?></span>
                            <input type="number" id="item_buying_price" name="buying_unit_price" class="form-control" step="0.01" placeholder="0.00" style="border-top-left-radius: 0; border-bottom-left-radius: 0; flex: 1;" required>
                        </div>
                    </div>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Primary Supplier <span class="required-mark">*</span></label>
                        <select id="item_supplier" name="supplier_id" class="form-control" required>
                            <option value="">Select Supplier</option>
                            <?php foreach ($suppliers as $supplier): ?>
                            <option value="<?php echo $supplier['id']; ?>"><?php echo $supplier['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Status</label>
                        <select id="item_status" name="status" class="form-control">
                            <option value="In-Stock">In-Stock</option>
                            <option value="Out of Stock">Out of Stock</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn" style="background: var(--glass-bg);" onclick="closeModal('inventoryModal')">Cancel</button>
                <button type="submit" class="btn btn-primary">Save Item</button>
            </div>
        </form>
    </div>
</div>

<!-- Withdraw Modal -->
<div id="withdrawModal" class="modal-overlay">
    <div class="modal-content" style="max-width: 450px;">
        <div class="modal-header">
            <h2>Withdraw Stock</h2>
            <button class="btn" style="background: none; color: var(--text-muted);" onclick="closeModal('withdrawModal')">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <form id="withdrawForm">
            <input type="hidden" id="withdraw_item_id" name="id">
            <div class="modal-body">
                <div style="background: var(--bg-dark); padding: 1rem; border-radius: 12px; margin-bottom: 1.5rem; display: flex; justify-content: space-between; align-items: center;">
                    <div>
                        <div style="font-size: 0.75rem; color: var(--text-muted);">Item</div>
                        <div id="withdraw_item_name" style="font-weight: 700; color: var(--text-main);"></div>
                    </div>
                    <div style="text-align: right;">
                        <div style="font-size: 0.75rem; color: var(--text-muted);">Available</div>
                        <div id="withdraw_available_stock" style="font-weight: 700; color: var(--primary);"></div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Withdraw Amount <span class="required-mark">*</span></label>
                    <div style="position: relative;">
                        <input type="number" id="withdraw_amount" name="amount" class="form-control" step="0.01" placeholder="0.00" required>
                        <span id="withdraw_unit" style="position: absolute; right: 1rem; top: 50%; transform: translateY(-50%); font-size: 0.85rem; color: var(--text-muted); font-weight: 600;"></span>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Reason / Comments <span class="required-mark">*</span></label>
                    <textarea id="withdraw_reason" name="reason" class="form-control" rows="3" placeholder="Why is this stock being withdrawn? (e.g., Assigned to Production Line #04)" required></textarea>
                </div>

                <div id="withdraw_preview" style="margin-top: 1rem; padding: 0.75rem; border-radius: 8px; font-size: 0.85rem; display: none;">
                    <!-- Stock preview calculated by JS -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn" style="background: var(--glass-bg);" onclick="closeModal('withdrawModal')">Cancel</button>
                <button type="submit" class="btn" style="background: var(--warning); color: white;">
                    <i class="fas fa-minus-circle"></i> Confirm Withdrawal
                </button>
            </div>
        </form>
    </div>
</div>

<script>
const SYSTEM_CURRENCY = '<?php echo $_SESSION['company_currency'] ?? '$'; ?>';
const allInventory = <?php echo json_encode($inventory); ?>;
let filteredInventory = [...allInventory];
const itemsPerPage = 20;
let currentPage = 1;

function renderInventory() {
    const tbody = document.getElementById('inventory-table-body');
    const cardsBody = document.getElementById('inventory-cards-body');
    const start = (currentPage - 1) * itemsPerPage;
    const end = start + itemsPerPage;
    const pageItems = filteredInventory.slice(start, end);

    // Render Table (Desktop)
    tbody.innerHTML = pageItems.map(item => {
        const isLowStock = parseFloat(item.stock) <= parseFloat(item.min_level);
        return `
            <tr class="data-row">
                <td style="padding-left: 1.5rem; font-family: monospace; font-weight: 700; color: var(--primary);">${item.sku}</td>
                <td>
                    <div style="font-weight: 600; color: var(--text-main);">${item.name}</div>
                    <div style="font-size: 0.75rem; color: var(--text-muted);">${item.category}</div>
                </td>
                <td>${item.category}</td>
                <td>
                    <div style="font-weight: 700; color: ${isLowStock ? 'var(--danger)' : 'var(--text-main)'};">
                        ${parseFloat(item.stock).toFixed(4)} <span style="font-size: 0.75rem; color: var(--text-muted); font-weight: 500;">${item.unit}</span>
                    </div>
                    ${isLowStock ? '<div style="font-size: 0.65rem; color: var(--warning); font-weight: 700;"><i class="fas fa-exclamation-triangle"></i> LOW STOCK</div>' : ''}
                </td>
                <td>
                    <div style="font-weight: 700; color: var(--warning);">
                        ${parseFloat(item.reserved_stock || 0).toFixed(4)} <span style="font-size: 0.75rem; color: var(--text-muted); font-weight: 500;">${item.unit}</span>
                    </div>
                </td>
                <td>
                    <span class="btn" style="padding: 0.2rem 0.6rem; font-size: 0.65rem; background: ${item.status === 'In-Stock' ? 'rgba(16, 185, 129, 0.1)' : 'rgba(239, 68, 68, 0.1)'}; color: ${item.status === 'In-Stock' ? 'var(--success)' : 'var(--danger)'}; font-weight: 800; text-transform: uppercase; border-radius: 50px;">
                        ${item.status}
                    </span>
                </td>
                <td style="font-size: 0.85rem; color: var(--text-muted);">${item.supplier_name || 'N/A'}</td>
                <td style="font-weight: 600; color: var(--primary);">${SYSTEM_CURRENCY}${parseFloat(item.buying_unit_price).toLocaleString(undefined, {minimumFractionDigits: 2})}</td>
                <td style="text-align: right; padding-right: 1.5rem;">
                    <div style="display: flex; gap: 0.5rem; justify-content: flex-end;">
                        <button class="btn" style="background: rgba(245, 158, 11, 0.1); color: var(--warning); padding: 0.4rem;" onclick='openWithdrawModal(${JSON.stringify(item)})' title="Withdraw Stock">
                            <i class="fas fa-minus-circle"></i>
                        </button>
                        <button class="btn" style="background: var(--bg-dark); padding: 0.4rem;" onclick='editInventoryItem(${JSON.stringify(item)})'>
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn" style="background: rgba(239, 68, 68, 0.1); color: var(--danger); padding: 0.4rem;" onclick="deleteInventoryItem(${item.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    }).join('');

    // Render Cards (Mobile)
    cardsBody.innerHTML = pageItems.map(item => {
        const isLowStock = parseFloat(item.stock) <= parseFloat(item.min_level);
        return `
            <div class="data-card" style="padding: 1.25rem;">
                <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 1rem;">
                    <div>
                        <div style="font-family: monospace; color: var(--primary); font-weight: 700; font-size: 0.8rem;">${item.sku}</div>
                        <h3 style="font-size: 1.125rem; font-weight: 700;">${item.name}</h3>
                    </div>
                    <span style="padding: 0.25rem 0.75rem; font-size: 0.7rem; background: ${item.status === 'In-Stock' ? 'rgba(16, 185, 129, 0.1)' : 'rgba(239, 68, 68, 0.1)'}; color: ${item.status === 'In-Stock' ? 'var(--success)' : 'var(--danger)'}; font-weight: 800; text-transform: uppercase; border-radius: 50px;">
                        ${item.status}
                    </span>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; background: var(--bg-dark); padding: 1rem; border-radius: 12px; margin-bottom: 1rem;">
                    <div>
                        <div style="font-size: 0.75rem; color: var(--text-muted);">Current Stock</div>
                        <div style="font-size: 1.15rem; font-weight: 700; color: ${isLowStock ? 'var(--danger)' : 'var(--text-main)'};">
                            ${parseFloat(item.stock).toFixed(4)} <span style="font-size: 0.8rem; font-weight: 500;">${item.unit}</span>
                        </div>
                    </div>
                    <div>
                        <div style="font-size: 0.75rem; color: var(--text-muted);">Reserved</div>
                        <div style="font-size: 1.15rem; font-weight: 700; color: var(--warning);">
                            ${parseFloat(item.reserved_stock || 0).toFixed(4)} <span style="font-size: 0.8rem; font-weight: 500;">${item.unit}</span>
                        </div>
                    </div>
                    ${isLowStock ? '<div style="grid-column: span 2; font-size: 0.7rem; color: var(--warning); font-weight: 700; margin-top: 0.25rem;"><i class="fas fa-exclamation-triangle"></i> LOW STOCK ALERT</div>' : ''}
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; font-size: 0.85rem; margin-bottom: 1rem;">
                    <div>
                        <div style="color: var(--text-muted);">Category</div>
                        <div style="font-weight: 600;">${item.category}</div>
                    </div>
                    <div>
                        <div style="color: var(--text-muted);">Unit Price</div>
                        <div style="font-weight: 600; color: var(--primary);">${SYSTEM_CURRENCY}${parseFloat(item.buying_unit_price).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div>
                    </div>
                </div>
                <div style="display: flex; gap: 0.5rem; border-top: 1px solid var(--border); padding-top: 1rem;">
                    <button class="btn" style="flex: 1; background: rgba(245, 158, 11, 0.1); color: var(--warning);" onclick='openWithdrawModal(${JSON.stringify(item)})'>
                        <i class="fas fa-minus-circle"></i> Withdraw
                    </button>
                    <button class="btn" style="flex: 1; background: var(--bg-dark);" onclick='editInventoryItem(${JSON.stringify(item)})'>
                        <i class="fas fa-edit"></i> Edit
                    </button>
                    <button class="btn" style="background: rgba(239, 68, 68, 0.1); color: var(--danger);" onclick="deleteInventoryItem(${item.id})">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `;
    }).join('');

    if (filteredInventory.length === 0) {
        const emptyState = `
            <div style="text-align: center; padding: 4rem; color: var(--text-muted);">
                <i class="fas fa-box-open fa-3x" style="margin-bottom: 1.5rem; opacity: 0.3;"></i>
                <h3>No inventory records found</h3>
                <p>Try a different search term or add a new item.</p>
            </div>
        `;
        tbody.innerHTML = `<tr><td colspan="8">${emptyState}</td></tr>`;
        cardsBody.innerHTML = emptyState;
    }

    updatePagination();
}

function updatePagination() {
    const totalItems = filteredInventory.length;
    const totalPages = Math.ceil(totalItems / itemsPerPage);
    const start = totalItems === 0 ? 0 : (currentPage - 1) * itemsPerPage + 1;
    const end = Math.min(currentPage * itemsPerPage, totalItems);
    
    document.getElementById('pagination-info').innerText = `Showing ${start} to ${end} of ${totalItems} items`;
    document.getElementById('item-count-badge').innerText = totalItems;

    const controls = document.getElementById('pagination-controls');
    let html = '';
    
    if (totalPages > 1) {
        html += `<button class="btn-page" ${currentPage === 1 ? 'disabled' : ''} onclick="goToPage(${currentPage - 1})"><i class="fas fa-chevron-left"></i></button>`;
        
        for (let i = 1; i <= totalPages; i++) {
            if (i === 1 || i === totalPages || (i >= currentPage - 1 && i <= currentPage + 1)) {
                html += `<button class="btn-page ${i === currentPage ? 'active' : ''}" onclick="goToPage(${i})">${i}</button>`;
            } else if (i === currentPage - 2 || i === currentPage + 2) {
                html += `<span style="padding: 0 0.5rem; color: var(--text-muted);">...</span>`;
            }
        }
        
        html += `<button class="btn-page" ${currentPage === totalPages ? 'disabled' : ''} onclick="goToPage(${currentPage + 1})"><i class="fas fa-chevron-right"></i></button>`;
    }
    
    controls.innerHTML = html;
}

function goToPage(page) {
    currentPage = page;
    renderInventory();
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

// Search Logic
document.getElementById('inventorySearch').addEventListener('input', function(e) {
    const term = e.target.value.toLowerCase();
    filteredInventory = allInventory.filter(item => 
        item.name.toLowerCase().includes(term) || 
        item.sku.toLowerCase().includes(term) || 
        (item.supplier_name && item.supplier_name.toLowerCase().includes(term)) ||
        item.category.toLowerCase().includes(term)
    );
    currentPage = 1;
    renderInventory();
});

function openWithdrawModal(item) {
    document.getElementById('withdraw_item_id').value = item.id;
    document.getElementById('withdraw_item_name').innerText = item.name;
    document.getElementById('withdraw_available_stock').innerText = `${parseFloat(item.stock).toFixed(2)} ${item.unit}`;
    document.getElementById('withdraw_unit').innerText = item.unit;
    document.getElementById('withdraw_amount').value = '';
    document.getElementById('withdraw_reason').value = '';
    document.getElementById('withdraw_preview').style.display = 'none';
    
    // Setup real-time preview
    const amountInput = document.getElementById('withdraw_amount');
    amountInput.oninput = () => {
        const amount = parseFloat(amountInput.value) || 0;
        const available = parseFloat(item.stock);
        const remaining = available - amount;
        const preview = document.getElementById('withdraw_preview');
        
        if (amount > 0) {
            preview.style.display = 'block';
            if (remaining < 0) {
                preview.style.background = 'rgba(239, 68, 68, 0.1)';
                preview.style.color = 'var(--danger)';
                preview.innerHTML = `<i class="fas fa-times-circle"></i> <b>Insufficient Stock:</b> You are trying to withdraw ${amount.toFixed(2)} but only ${available.toFixed(2)} is available.`;
            } else {
                preview.style.background = 'rgba(16, 185, 129, 0.1)';
                preview.style.color = 'var(--success)';
                preview.innerHTML = `<i class="fas fa-check-circle"></i> <b>Stock Preview:</b> Remaining stock will be ${remaining.toFixed(2)} ${item.unit}`;
            }
        } else {
            preview.style.display = 'none';
        }
    };
    
    openModal('withdrawModal');
}

document.getElementById('withdrawForm').onsubmit = async (e) => {
    e.preventDefault();
    const btn = e.target.querySelector('button[type="submit"]');
    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData.entries());
    
    // Client-side validation for sufficient stock
    const availableText = document.getElementById('withdraw_available_stock').innerText;
    const available = parseFloat(availableText);
    const amount = parseFloat(data.amount);
    
    if (amount > available) {
        notify('Cannot withdraw more than available stock', 'error');
        return;
    }

    const result = await apiCall('inventory', { 
        data: { 
            action: 'withdraw', 
            id: data.id,
            amount: data.amount,
            reason: data.reason
        }, 
        btn: btn 
    });
    
    if (result.success) {
        notify(result.message);
        setTimeout(() => location.reload(), 1000);
    } else {
        notify(result.message, 'error');
    }
};

function openAddInventoryModal() {
    document.getElementById('modalTitle').innerText = 'Add New Item';
    document.getElementById('inventoryForm').reset();
    document.getElementById('item_id').value = '';
    document.getElementById('item_stock').value = '0.00';
    document.getElementById('item_stock_addition').value = '0';
    const random8 = Math.floor(10000000 + Math.random() * 90000000);
    document.getElementById('item_sku').value = 'SKU-' + random8;
    document.getElementById('item_buying_price').value = '0.00';
    openModal('inventoryModal');
}

function editInventoryItem(item) {
    document.getElementById('modalTitle').innerText = 'Edit Item';
    document.getElementById('item_id').value = item.id;
    document.getElementById('item_sku').value = item.sku;
    document.getElementById('item_name').value = item.name;
    document.getElementById('item_category').value = item.category;
    document.getElementById('item_unit').value = item.unit;
    document.getElementById('item_stock').value = parseFloat(item.stock || 0).toFixed(4);
    document.getElementById('item_stock_addition').value = '0';
    document.getElementById('item_min_level').value = parseFloat(item.min_level || 0).toFixed(4);
    document.getElementById('item_supplier').value = item.supplier_id || '';
    document.getElementById('item_status').value = item.status;
    document.getElementById('item_buying_price').value = parseFloat(item.buying_unit_price || 0).toFixed(2);
    openModal('inventoryModal');
}

document.getElementById('inventoryForm').onsubmit = async (e) => {
    e.preventDefault();
    const btn = e.target.querySelector('button[type="submit"]');
    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData.entries());
    
    const result = await apiCall('inventory', { data: { action: 'save', item: data }, btn: btn });
    if (result.success) {
        notify(result.message);
        setTimeout(() => location.reload(), 1000);
    } else {
        notify(result.message, 'error');
    }
};

async function deleteInventoryItem(id) {
    if (await confirmAction({ title: 'Delete Item', message: 'Are you sure you want to delete this inventory item?' })) {
        const result = await apiCall('inventory', { action: 'delete', id: id });
        if (result.success) {
            notify(result.message);
            setTimeout(() => location.reload(), 1000);
        } else {
            notify(result.message, 'error');
        }
    }
}

// Initial render
window.addEventListener('DOMContentLoaded', renderInventory);
</script>
