<?php include '../store_keeper/auth_check.php'; ?>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Inventory Management - Granny Restaurant">
    <link href="../assets/images/favicon/favicon.png" rel="icon">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="./store-keeper-theme.css?v=1.1">
    <title>Inventory Management</title>
</head>
<body>
<?php include 'sidebar.php'; ?>

<div class="dashboard-container">
    <div class="main-content">
    <div class="page-header">
        <div class="page-header-content">
            <h1>Inventory Management</h1>
            <p>Track and manage current stock levels</p>
        </div>
        <div class="page-actions">
            <button class="btn btn-primary" onclick="openAdjustModal()">
                <i class="fas fa-edit"></i> Adjust Stock
            </button>
        </div>
    </div>

    <!-- FILTERS -->
    <div class="card" style="margin-bottom: 20px;">
        <div class="card-body">
            <div class="form-row">
                <div class="form-group">
                    <label for="searchIngredient">Search Ingredient</label>
                    <input type="text" id="searchIngredient" placeholder="Search by name..." onkeyup="filterTable()">
                </div>
                <div class="form-group">
                    <label for="filterStatus">Stock Status</label>
                    <select id="filterStatus" onchange="filterTable()">
                        <option value="">All</option>
                        <option value="low">Low</option>
                        <option value="normal">Normal</option>
                        <option value="adequate">Adequate</option>
                    </select>
                </div>
                <div class="form-group" style="display: flex; align-items: flex-end;">
                    <button class="btn btn-secondary" onclick="clearFilters()"><i class="fas fa-redo"></i> Clear</button>
                </div>
            </div>
        </div>
    </div>

    <!-- INVENTORY TABLE -->
    <div class="card">
        <div class="card-header">
            <h2><i class="fas fa-boxes"></i> Current Inventory</h2>
        </div>
        <div class="card-body">
            <table class="table" id="inventoryTable">
                <thead>
                    <tr>
                        <th>Ingredient</th>
                        <th>Current Stock</th>
                        <th>Minimum</th>
                        <th>Unit Cost</th>
                        <th>Stock Value</th>
                        <th>Status</th>
                        <th>Last Updated</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="inventoryList">
                    <tr>
                        <td colspan="8" style="text-align: center; padding: 30px;">
                            <i class="fas fa-spinner fa-spin"></i> Loading...
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- ADJUST STOCK MODAL -->
<div id="adjustModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2><i class="fas fa-edit"></i> Adjust Stock</h2>
            <button class="modal-close" onclick="closeAdjustModal()">&times;</button>
        </div>
        <div class="modal-body">
            <form id="adjustForm">
                <div class="form-group">
                    <label for="adjIngredient">Ingredient *</label>
                    <select id="adjIngredient" required onchange="onAdjustIngredientSelect()">
                        <option value="">Select an ingredient...</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Current Stock</label>
                    <input type="text" id="adjCurrentStock" readonly style="background: #f0f0f0;">
                </div>

                <div class="form-group">
                    <label for="adjAction">Action *</label>
                    <select id="adjAction" required>
                        <option value="add">Add Stock</option>
                        <option value="subtract">Remove Stock</option>
                        <option value="adjust">Manual Adjustment</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="adjQuantity">Quantity *</label>
                    <input type="number" id="adjQuantity" step="0.01" min="0" required placeholder="Enter quantity">
                </div>

                <div class="form-group">
                    <label for="adjReason">Reason *</label>
                    <select id="adjReason" required>
                        <option value="">Select reason...</option>
                        <option value="stock_received">Stock Received</option>
                        <option value="stock_used">Stock Used</option>
                        <option value="stock_damaged">Stock Damaged</option>
                        <option value="inventory_count">Physical Count Variance</option>
                        <option value="stock_transfer">Transfer to Another Location</option>
                        <option value="returned_to_supplier">Returned to Supplier</option>
                        <option value="other">Other</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="adjReference">Reference Document</label>
                    <input type="text" id="adjReference" placeholder="PO #, Invoice #, Order ID, etc.">
                </div>

                <div class="form-group">
                    <label for="adjNotes">Notes</label>
                    <textarea id="adjNotes" placeholder="Additional details..."></textarea>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeAdjustModal()">Cancel</button>
            <button class="btn btn-primary" onclick="submitAdjustForm()">
                <i class="fas fa-check"></i> Confirm Adjustment
            </button>
        </div>
    </div>
</div>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        loadInventory();
        loadIngredientsList();
    });

    async function loadIngredientsList() {
        try {
            const response = await fetch('../backend/admin_ingredients_api.php?action=get_ingredients&status=active', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                console.error('Ingredients API error - HTTP', response.status);
                return;
            }
            
            const data = await response.json();
            
            if (data.success) {
                const select = document.getElementById('adjIngredient');
                select.innerHTML = '<option value="">Select an ingredient...</option>';
                data.data.forEach(ingredient => {
                    select.innerHTML += `
                        <option value="${ingredient.id}" 
                                data-current="${ingredient.current_stock}"
                                data-unit="${ingredient.unit}">
                            ${ingredient.name}
                        </option>
                    `;
                });
            }
        } catch (error) {
            console.error('Error loading ingredients:', error);
        }
    }

    async function loadInventory() {
        try {
            const response = await fetch('../backend/store_keeper_api.php?action=get_inventory', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                console.error('Inventory API error - HTTP', response.status);
                document.getElementById('inventoryList').innerHTML = '<tr><td colspan="8" class="alert alert-danger">Error loading inventory</td></tr>';
                return;
            }
            
            const data = await response.json();
            
            const tbody = document.getElementById('inventoryList');
            
            if (data.success && data.data && data.data.length > 0) {
                tbody.innerHTML = data.data.map(item => {
                    const statusClass = item.stock_status === 'low' ? 'danger' : 
                                      item.stock_status === 'adequate' ? 'success' : 'warning';
                    const statusLabel = item.stock_status === 'low' ? 'Low' : 
                                      item.stock_status === 'adequate' ? 'Adequate' : 'Normal';
                    const stockValue = (parseFloat(item.current_stock) * parseFloat(item.unit_cost)).toFixed(2);
                    
                    // Determine expiry and perishable warnings
                    let expiryWarning = '';
                    if (item.is_perishable === 1 || item.is_perishable === '1') {
                        if (!item.expiry_date) {
                            expiryWarning = '<span class="badge warning" title="Missing expiry date for perishable item"><i class="fas fa-exclamation-triangle"></i> No Expiry Date</span>';
                        } else {
                            const today = new Date();
                            const expiryDate = new Date(item.expiry_date);
                            const daysLeft = Math.floor((expiryDate - today) / (1000 * 60 * 60 * 24));
                            
                            if (daysLeft < 0) {
                                expiryWarning = '<span class="badge danger" title="Item has already expired"><i class="fas fa-skull-crossbones"></i> EXPIRED</span>';
                            } else if (daysLeft <= 3) {
                                expiryWarning = `<span class="badge danger" title="Expires in ${daysLeft} days"><i class="fas fa-hourglass-end"></i> Expires Soon (${daysLeft}d)</span>`;
                            }
                        }
                    }
                    
                    return `
                        <tr>
                            <td>
                                <strong>${item.name}</strong>
                                ${expiryWarning ? '<br>' + expiryWarning : ''}
                            </td>
                            <td>${parseFloat(item.current_stock).toFixed(2)}</td>
                            <td>${parseFloat(item.minimum_stock).toFixed(2)} ${item.unit}</td>
                            <td>₹${parseFloat(item.unit_cost).toFixed(2)}</td>
                            <td>₹${stockValue}</td>
                            <td><span class="badge ${statusClass}">${statusLabel}</span></td>
                            <td>${item.last_updated || '-'}</td>
                            <td>
                                <button class="btn btn-sm btn-primary" onclick="openAdjustForItem(${item.id}, '${item.name}', ${item.current_stock}, '${item.unit}')">
                                    <i class="fas fa-edit"></i> Adjust
                                </button>
                            </td>
                        </tr>
                    `;
                }).join('');
            } else {
                tbody.innerHTML = '<tr><td colspan="8" style="text-align: center; padding: 30px;">No inventory items found</td></tr>';
            }
        } catch (error) {
            console.error('Error loading inventory:', error);
            document.getElementById('inventoryList').innerHTML = '<tr><td colspan="8" class="alert alert-danger">Error loading inventory</td></tr>';
        }
    }

    function openAdjustModal() {
        document.getElementById('adjustForm').reset();
        document.getElementById('adjCurrentStock').value = '';
        document.getElementById('adjustModal').classList.add('active');
    }

    function openAdjustForItem(id, name, current, unit) {
        document.getElementById('adjustForm').reset();
        document.getElementById('adjIngredient').value = id;
        document.getElementById('adjCurrentStock').value = `${parseFloat(current).toFixed(2)} ${unit}`;
        document.getElementById('adjustModal').classList.add('active');
    }

    function onAdjustIngredientSelect() {
        const select = document.getElementById('adjIngredient');
        const option = select.options[select.selectedIndex];
        if (option.value) {
            document.getElementById('adjCurrentStock').value = `${parseFloat(option.dataset.current).toFixed(2)} ${option.dataset.unit}`;
        }
    }

    function closeAdjustModal() {
        document.getElementById('adjustModal').classList.remove('active');
    }

    async function submitAdjustForm() {
        const ingredientId = document.getElementById('adjIngredient').value;
        const quantity = document.getElementById('adjQuantity').value;
        const action = document.getElementById('adjAction').value;
        const reason = document.getElementById('adjReason').value;

        if (!ingredientId || !quantity || !reason) {
            Swal.fire('Error', 'Please fill required fields', 'error');
            return;
        }

        try {
            const response = await fetch('../backend/store_keeper_api.php?action=adjust_inventory', {
                method: 'POST',
                credentials: 'include',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    ingredient_id: ingredientId,
                    quantity_changed: quantity,
                    action: action,
                    reason: reason,
                    reference_doc: document.getElementById('adjReference').value,
                    notes: document.getElementById('adjNotes').value
                })
            });

            if (!response.ok) {
                Swal.fire('Error', 'HTTP ' + response.status + ': Failed to adjust inventory', 'error');
                return;
            }

            const data = await response.json();
            
            if (data.success) {
                Swal.fire('Success', 'Inventory adjusted successfully!', 'success');
                closeAdjustModal();
                loadInventory();
            } else {
                Swal.fire('Error', data.message || 'Failed to adjust inventory', 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            Swal.fire('Error', 'An error occurred', 'error');
        }
    }

    function filterTable() {
        const search = document.getElementById('searchIngredient').value.toLowerCase();
        const status = document.getElementById('filterStatus').value;
        const table = document.getElementById('inventoryTable');
        const rows = table.getElementsByTagName('tr');
        
        for (let i = 1; i < rows.length; i++) {
            const cells = rows[i].getElementsByTagName('td');
            const name = cells[0].textContent.toLowerCase();
            const statusCell = cells[5].textContent.toLowerCase();
            
            const matchSearch = name.includes(search);
            const matchStatus = !status || statusCell.includes(status.toLowerCase());
            
            rows[i].style.display = (matchSearch && matchStatus) ? '' : 'none';
        }
    }

    function clearFilters() {
        document.getElementById('searchIngredient').value = '';
        document.getElementById('filterStatus').value = '';
        filterTable();
    }

    function handleLogout() {
        Swal.fire({
            title: 'Logout',
            text: 'Are you sure you want to logout?',
            icon: 'question',
            showCancelButton: true
        }).then((result) => {
            if (result.isConfirmed) {
                fetch('../backend/store_keeper_login.php?action=logout', {
                    method: 'POST',
                    credentials: 'include',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }).then(() => {
                    window.location.href = 'index.php';
                }).catch(error => console.error('Logout error:', error));
            }
        });
    }
</script>

<script src="store-keeper-sidebar.js"></script>
</body>
</html>