<?php include '../purchase_manager/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="Ingredients Stock - Purchase Manager">
    <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="./pm-sidebar-styles.css">
    <link rel="stylesheet" href="./pm-theme-enhanced.css">
    <title>Ingredients Stock</title>
    <style>
        .stock-bar {
            width: 100%;
            height: 8px;
            background: #e5e7eb;
            border-radius: 4px;
            overflow: hidden;
            margin-top: 4px;
        }
        .stock-bar-fill {
            height: 100%;
            transition: width 0.3s ease;
        }
        .stock-low .stock-bar-fill { background: #ef4444; }
        .stock-normal .stock-bar-fill { background: #f59e0b; }
        .stock-adequate .stock-bar-fill { background: #10b981; }
        .stock-badge {
            display: inline-block;
            font-size: 11px;
            padding: 4px 10px;
            border-radius: 12px;
            font-weight: 600;
            margin-top: 6px;
        }
        .stock-low .stock-badge { background: #fee2e2; color: #991b1b; }
        .stock-normal .stock-badge { background: #fef3c7; color: #92400e; }
        .stock-adequate .stock-badge { background: #dcfce7; color: #166534; }
    </style>
</head>
<body>
<?php include 'pm-sidebar.php'; ?>
<div class="pm-main-container">
    <div class="container">
    <div class="page-header">
        <div class="page-header-content">
            <h1><i class="fas fa-leaf"></i> Ingredients & Stock Management</h1>
            <p>Manage ingredients, process stock requests from Admin, and track deliveries</p>
        </div>
        <div style="display: flex; gap: 10px;">
            <!-- <button class="btn-primary" onclick="viewPendingRequests()" style="background: #f59e0b;">
                <i class="fas fa-bell"></i> Pending Requests <span id="pendingBadge" style="background: #ef4444; color: white; border-radius: 50%; width: 22px; height: 22px; display: inline-flex; align-items: center; justify-content: center; font-size: 12px; margin-left: 5px;">0</span>
            </button> -->
            <button class="btn-primary" onclick="openAddIngredientModal()"><i class="fas fa-plus"></i> Add Ingredient</button>
        </div>
    </div>

    <!-- FILTERS & SEARCH -->
    <div class="toolbar">
        <div class="search-box">
            <i class="fas fa-search"></i>
            <input type="text" id="searchInput" placeholder="Search ingredients by name or unit...">
        </div>
        <select id="stockFilter" class="filter-btn" style="border: 1px solid var(--border-color); padding: 10px 14px; border-radius: 8px; background: white;">
            <option value="">All Stock Levels</option>
            <option value="low">Low Stock</option>
            <option value="normal">Normal Stock</option>
            <option value="adequate">Adequate Stock</option>
        </select>
        <button class="filter-btn" onclick="viewSmartReorderSuggestions()" style="background: #eef2ff; border-color: #c7d2fe; color: #3730a3;">
            <i class="fas fa-robot"></i> AI Reorder
        </button>
        <button class="filter-btn" onclick="exportIngredients()"><i class="fas fa-download"></i> Export</button>
        <button class="btn-secondary" onclick="loadIngredients()"><i class="fas fa-rotate"></i> Refresh</button>
    </div>

    <!-- STATS ROW -->
    <div class="metric-strip">
        <div class="metric-card">
            <div class="label">Total Ingredients</div>
            <div class="value" id="totalCount">0</div>
        </div>
        <div class="metric-card">
            <div class="label">Low Stock</div>
            <div class="value" id="lowStockCount">0</div>
        </div>
        <div class="metric-card">
            <div class="label">Avg Stock Value</div>
            <div class="value" id="avgValue">₹0</div>
        </div>
        <div class="metric-card">
            <div class="label">Total Inventory Value</div>
            <div class="value" id="totalValue">₹0</div>
        </div>
    </div>

    <!-- TABLE -->
    <div class="table-wrapper">
        <table>
            <thead>
                <tr>
                    <th width="20%">Ingredient</th>
                    <th width="12%">Unit</th>
                    <th width="18%">Stock Level</th>
                    <th width="15%">Min Level</th>
                    <th width="12%">Unit Cost</th>
                    <th width="15%">Total Value</th>
                    <th width="12%">Status</th>
                    <th width="20%">Actions</th>
                </tr>
            </thead>
            <tbody id="ingredientBody">
                <tr><td colspan="8" class="empty-state"><i class="fas fa-spinner fa-spin"></i> Loading ingredients...</td></tr>
            </tbody>
        </table>
    </div>
</div>

<!-- ADD/EDIT INGREDIENT MODAL -->
<div class="modal" id="addEditIngredientModal">
    <div class="modal-content">
        <div class="modal-header">
            <span id="addEditTitle">Add New Ingredient</span>
            <button class="close" type="button" onclick="closeAddEditModal()">&times;</button>
        </div>
        <form id="ingredientForm" onsubmit="saveIngredient(event)">
            <input type="hidden" id="ingredientId">
            <div class="form-grid">
                <div class="form-group">
                    <label><i class="fas fa-tag"></i> Ingredient Name *</label>
                    <input id="addName" required placeholder="e.g., Tomato, Onion, Salt">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-info"></i> Description</label>
                    <textarea id="addDescription" placeholder="e.g., Fresh red tomatoes" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label><i class="fas fa-cube"></i> Unit *</label>
                    <input id="addUnit" required placeholder="e.g., kg, liter, pieces">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-warehouse"></i> Supplier</label>
                    <select id="addSupplier">
                        <option value="">Select supplier...</option>
                    </select>
                </div>
                <div class="form-group">
                    <label><i class="fas fa-box-open"></i> Supplier Product</label>
                    <select id="addSupplierProduct">
                        <option value="">Select supplier first...</option>
                    </select>
                    <small id="addSupplierProductHint" style="display:block; margin-top:6px; color: var(--text-secondary);">Pick a supplier product to auto-fill ingredient details.</small>
                </div>
                <div class="form-group">
                    <label><i class="fas fa-boxes"></i> Current Stock *</label>
                    <input id="addCurrentStock" type="number" min="0" step="0.01" required placeholder="0.00">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-bell"></i> Minimum Stock Level *</label>
                    <input id="addMinimumStock" type="number" min="0" step="0.01" required placeholder="e.g., 20">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-dollar-sign"></i> Unit Cost (₹) *</label>
                    <input id="addUnitCost" type="number" min="0.01" step="0.01" required placeholder="0.00">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-toggle-on"></i> Status</label>
                    <select id="addStatus">
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>
            </div>
            <div style="margin-top: 20px; display: flex; gap: 10px; justify-content: flex-end;">
                <button type="button" class="btn-secondary" onclick="closeAddEditModal()">Cancel</button>
                <button type="submit" class="btn-primary">Save Ingredient</button>
            </div>
        </form>
    </div>
</div>

<!-- INGREDIENT DETAIL MODAL -->
<div class="modal" id="ingredientModal">
    <div class="modal-content">
        <div class="modal-header">
            <span id="modalTitle">Ingredient Details</span>
            <button class="close" type="button" onclick="closeIngredientModal()">&times;</button>
        </div>
        <div style="padding: 20px;">
            <div class="form-grid">
                <div class="form-group">
                    <label><i class="fas fa-tag"></i> Name</label>
                    <input id="ingredientName" readonly placeholder="Ingredient name">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-info"></i> Description</label>
                    <textarea id="ingredientDesc" readonly placeholder="Description" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label><i class="fas fa-cube"></i> Unit</label>
                    <input id="ingredientUnit" readonly placeholder="Unit">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-warehouse"></i> Supplier</label>
                    <input id="ingredientSupplier" readonly placeholder="Supplier name">
                </div>
            </div>

            <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid var(--border-color);">
                <h3 style="margin-bottom: 15px; color: var(--text-primary);">Stock Information</h3>
                <div class="form-grid">
                    <div class="form-group">
                        <label><i class="fas fa-boxes"></i> Current Stock</label>
                        <input id="ingredientCurrentStock" readonly type="number" placeholder="0">
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-bell"></i> Minimum Stock</label>
                        <input id="ingredientMinStock" readonly type="number" placeholder="0">
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-dollar-sign"></i> Unit Cost</label>
                        <input id="ingredientUnitCost" readonly type="number" placeholder="0" step="0.01">
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-calculator"></i> Total Value</label>
                        <input id="ingredientTotalValue" readonly type="number" placeholder="0" step="0.01">
                    </div>
                </div>

                <div style="margin-top: 15px;">
                    <label style="display: block; margin-bottom: 10px; font-weight: 600; font-size: 13px; color: var(--text-primary);">Stock Status</label>
                    <div id="ingredientStockStatus" style="padding: 12px; background: var(--bg-secondary); border-radius: 8px; border-left: 4px solid var(--primary);"></div>
                </div>
            </div>

            <div style="margin-top: 20px; display: flex; gap: 10px; justify-content: flex-end;">
                <button class="action-btn view" onclick="selectAndCreatePO()" title="Create Purchase Order">
                    <i class="fas fa-shopping-cart"></i> Create PO
                </button>
                <button class="action-btn delete" onclick="closeIngredientModal()" title="Close">
                    <i class="fas fa-times"></i> Close
                </button>
            </div>
        </div>
    </div>
</div>

<!-- SMART REORDER (AI) MODAL -->
<div class="modal" id="smartReorderModal">
    <div class="modal-content" style="max-width: 1100px;">
        <div class="modal-header">
            <span><i class="fas fa-robot"></i> Smart Reorder Suggestions</span>
            <button class="close" type="button" onclick="closeSmartReorderModal()">&times;</button>
        </div>
        <div style="padding: 20px; max-height: 75vh; overflow-y: auto;">
            <div id="smartReorderSummary" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px; margin-bottom: 16px;"></div>
            <div id="smartReorderBody">
                <p style="text-align:center; color:#999; padding:20px;">Click AI Reorder to generate suggestions.</p>
            </div>
            <p style="margin-top: 12px; color: #6b7280; font-size: 12px;">
                Suggestions are AI-assisted and should be reviewed before placing purchase orders.
            </p>
        </div>
    </div>
</div>

<!-- PENDING STOCK REQUESTS MODAL -->
<div class="modal" id="pendingRequestsModal">
    <div class="modal-content" style="max-width: 800px;">
        <div class="modal-header">
            <span id="modalTitle"><i class="fas fa-list"></i> Pending Stock Requests from Admin</span>
            <button class="close" type="button" onclick="closePendingRequestsModal()">&times;</button>
        </div>
        <div style="padding: 20px; max-height: 70vh; overflow-y: auto;" id="pendingRequestsBody">
            <div style="text-align: center; color: #ccc; padding: 40px;">
                <i class="fas fa-inbox" style="font-size: 48px; margin-bottom: 10px;"></i>
                <p>No pending requests</p>
            </div>
        </div>
    </div>
</div>

<!-- RECEIVE DELIVERY MODAL -->
<div class="modal" id="receiveDeliveryModal">
    <div class="modal-content">
        <div class="modal-header">
            <span id="modalTitle"><i class="fas fa-truck"></i> Receive Delivery</span>
            <button class="close" type="button" onclick="closeReceiveModal()">&times;</button>
        </div>
        <form id="receiveDeliveryForm" onsubmit="confirmDeliveryReceipt(event)">
            <input type="hidden" id="receiveRequestId">
            <input type="hidden" id="receiveIngredientId">
            <input type="hidden" id="receiveQuantityOrdered">
            <div class="form-grid">
                <div class="form-group">
                    <label><i class="fas fa-tag"></i> Ingredient</label>
                    <input id="receiveIngredientName" readonly>
                </div>
                <div class="form-group">
                    <label><i class="fas fa-cube"></i> Unit</label>
                    <input id="receiveUnit" readonly>
                </div>
                <div class="form-group">
                    <label><i class="fas fa-boxes"></i> Current Stock</label>
                    <input id="receiveCurrentStock" type="number" readonly>
                </div>
                <div class="form-group">
                    <label><i class="fas fa-check"></i> Quantity Delivered *</label>
                    <input id="receiveQuantityDelivered" type="number" step="0.01" required>
                </div>
            </div>
            <div class="form-group">
                <label><i class="fas fa-file-invoice"></i> Invoice/Document Reference</label>
                <input id="receiveInvoiceRef" placeholder="Invoice #, PO #, etc.">
            </div>
            <div style="margin-top: 20px; display: flex; gap: 10px; justify-content: flex-end;">
                <button type="button" class="btn-secondary" onclick="closeReceiveModal()">Cancel</button>
                <button type="submit" class="btn-primary">Confirm Receipt & Update Stock</button>
            </div>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script>
    let allIngredients = [];
    let currentIngredientId = null;
    let supplierOptions = [];
    let supplierProductsForAdd = [];

    async function checkSession() {
        const response = await fetch('../backend/purchase_manager_session_check.php');
        const data = await response.json();
        if (!data.valid) {
            window.location.href = 'login.php';
            return;
        }
        const name = data.purchase_manager_name || 'Purchase Manager';
        const initials = name.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase();
        
        // Update sidebar user info
        const sidebarUserName = document.getElementById('userNameSidebar');
        const sidebarUserAvatar = document.getElementById('userAvatarSidebar');
        if (sidebarUserName) sidebarUserName.textContent = name;
        if (sidebarUserAvatar) sidebarUserAvatar.textContent = initials;
    }

    async function loadIngredients() {
        try {
            const response = await fetch('../backend/admin_ingredients_api.php?action=get_ingredients&status=active');
            const data = await response.json();

            if (!data.success || !data.data) {
                showError('Failed to load ingredients');
                return;
            }

            allIngredients = data.data;
            renderTable(allIngredients);
            updateMetrics();
        } catch (error) {
            console.error('Error loading ingredients:', error);
            showError('Error loading ingredients: ' + error.message);
        }
    }

    async function loadSupplierOptions() {
        try {
            const response = await fetch('../backend/suppliers_api.php?action=get_all');
            const data = await response.json();
            supplierOptions = data.success && Array.isArray(data.suppliers) ? data.suppliers : [];
            renderSupplierOptions();
        } catch (error) {
            supplierOptions = [];
            renderSupplierOptions();
        }
    }

    function renderSupplierOptions(selectedName = '') {
        const select = document.getElementById('addSupplier');
        if (!select) return;

        let options = '<option value="">Select supplier...</option>';
        options += supplierOptions.map(s => `<option value="${escapeHtml(s.name)}" data-id="${s.id}">${escapeHtml(s.name)}</option>`).join('');

        if (selectedName && !supplierOptions.some(s => (s.name || '').toLowerCase() === selectedName.toLowerCase())) {
            options += `<option value="${escapeHtml(selectedName)}">${escapeHtml(selectedName)} (Custom)</option>`;
        }

        select.innerHTML = options;
        if (selectedName) {
            select.value = selectedName;
        }
    }

    async function onAddSupplierChange() {
        const supplierSelect = document.getElementById('addSupplier');
        const supplierId = Number(supplierSelect.options[supplierSelect.selectedIndex]?.dataset?.id || 0);
        const productSelect = document.getElementById('addSupplierProduct');
        const hint = document.getElementById('addSupplierProductHint');

        if (!supplierId) {
            supplierProductsForAdd = [];
            productSelect.innerHTML = '<option value="">Select supplier first...</option>';
            if (hint) hint.textContent = 'Pick a supplier product to auto-fill ingredient details.';
            return;
        }

        try {
            const response = await fetch(`../backend/supplier_products_api.php?action=get_supplier_products&supplier_id=${supplierId}`);
            const data = await response.json();
            const products = data.success && Array.isArray(data.products) ? data.products : [];

            supplierProductsForAdd = products.map((p, idx) => {
                const productName = (p.ingredient_name || p.supplier_product_name || p.product_name || '').trim();
                const unit = (p.unit || '').trim();
                const unitPrice = Number(p.unit_price || 0);
                const hasLinkedIngredient = !!p.ingredient_id;
                const existsByName = allIngredients.some(i => (i.name || '').trim().toLowerCase() === productName.toLowerCase());
                const isNew = !hasLinkedIngredient && !existsByName;
                return {
                    key: `${supplierId}_${idx}`,
                    name: productName,
                    unit,
                    unit_price: unitPrice,
                    is_new: isNew
                };
            }).filter(p => p.name);

            if (!supplierProductsForAdd.length) {
                productSelect.innerHTML = '<option value="">No products found for this supplier</option>';
                if (hint) hint.textContent = 'No supplier products found. You can still enter ingredient details manually.';
                return;
            }

            productSelect.innerHTML = '<option value="">Select supplier product...</option>' + supplierProductsForAdd.map(p => {
                const label = `${escapeHtml(p.name)} (${escapeHtml(p.unit || '-')}) - ₹${Number(p.unit_price || 0).toFixed(2)}${p.is_new ? ' [NEW]' : ''}`;
                return `<option value="${escapeHtml(p.key)}">${label}</option>`;
            }).join('');

            const newCount = supplierProductsForAdd.filter(p => p.is_new).length;
            if (hint) hint.textContent = newCount > 0
                ? `${newCount} product(s) marked [NEW] are not yet in ingredients list.`
                : 'All listed products are already mapped in ingredients.';
        } catch (error) {
            supplierProductsForAdd = [];
            productSelect.innerHTML = '<option value="">Failed to load supplier products</option>';
            if (hint) hint.textContent = 'Could not fetch supplier products. Enter details manually.';
        }
    }

    function onAddSupplierProductChange() {
        const selectedKey = document.getElementById('addSupplierProduct').value;
        if (!selectedKey) return;
        const product = supplierProductsForAdd.find(p => p.key === selectedKey);
        if (!product) return;

        document.getElementById('addName').value = product.name || '';
        document.getElementById('addUnit').value = product.unit || '';
        if (Number(product.unit_price || 0) > 0) {
            document.getElementById('addUnitCost').value = Number(product.unit_price).toFixed(2);
        }
        if (product.is_new) {
            document.getElementById('addDescription').value = document.getElementById('addDescription').value || 'Added from supplier product catalog';
        }
    }

    function renderTable(ingredients) {
        const tbody = document.getElementById('ingredientBody');
        
        if (!ingredients.length) {
            tbody.innerHTML = '<tr><td colspan="8" class="empty-state">No ingredients found</td></tr>';
            return;
        }

        tbody.innerHTML = ingredients.map(ing => {
            const stockPercentage = Math.min(100, (ing.current_stock / (ing.minimum_stock * 2)) * 100) || 0;
            const stockClass = ing.stock_status === 'low' ? 'stock-low' : (ing.stock_status === 'adequate' ? 'stock-adequate' : 'stock-normal');
            const statusText = {
                'low': 'Low Stock',
                'adequate': 'Adequate',
                'normal': 'Normal'
            }[ing.stock_status] || 'Unknown';

            return `
                <tr class="${stockClass}">
                    <td>
                        <div style="font-weight: 600; color: var(--text-primary);">${escapeHtml(ing.name)}</div>
                        <div style="font-size: 12px; color: var(--text-secondary); margin-top: 4px;">${escapeHtml(ing.description || '-')}</div>
                    </td>
                    <td>${escapeHtml(ing.unit)}</td>
                    <td>
                        <div style="margin-bottom: 8px;">
                            <strong>${Number(ing.current_stock).toFixed(2)}</strong>
                        </div>
                        <div class="stock-bar">
                            <div class="stock-bar-fill" style="width: ${stockPercentage}%;"></div>
                        </div>
                    </td>
                    <td>${Number(ing.minimum_stock).toFixed(2)}</td>
                    <td>₹${Number(ing.unit_cost).toFixed(2)}</td>
                    <td>₹${Number(ing.total_value || 0).toFixed(2)}</td>
                    <td>
                        <span class="stock-badge">${statusText}</span>
                    </td>
                    <td>
                        <div class="action-buttons">
                            <button class="action-btn view" onclick="viewIngredient(${ing.id})" title="View Details">
                                <i class="fas fa-eye"></i> View
                            </button>
                            <button class="action-btn edit" onclick="editIngredient(${ing.id})" title="Edit Ingredient">
                                <i class="fas fa-edit"></i> Edit
                            </button>
                            <button class="action-btn delete" onclick="deleteIngredient(${ing.id})" title="Delete Ingredient">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </div>
                    </td>
                </tr> 
            `;
        }).join('');
    }

    function viewIngredient(ingredientId) {
        const ingredient = allIngredients.find(i => i.id === ingredientId);
        if (!ingredient) return;

        currentIngredientId = ingredientId;
        
        document.getElementById('ingredientName').value = ingredient.name;
        document.getElementById('ingredientDesc').value = ingredient.description || '';
        document.getElementById('ingredientUnit').value = ingredient.unit;
        document.getElementById('ingredientSupplier').value = ingredient.supplier || '-';
        document.getElementById('ingredientCurrentStock').value = Number(ingredient.current_stock).toFixed(2);
        document.getElementById('ingredientMinStock').value = Number(ingredient.minimum_stock).toFixed(2);
        document.getElementById('ingredientUnitCost').value = Number(ingredient.unit_cost).toFixed(2);
        document.getElementById('ingredientTotalValue').value = Number(ingredient.total_value || 0).toFixed(2);

        const statusText = {
            'low': '⚠️ Low Stock - Urgent order needed',
            'adequate': '✓ Adequate Stock - Supply sufficient',
            'normal': '⚠️ Normal Stock - Monitor for reordering'
        }[ingredient.stock_status] || 'Unknown Status';

        const statusColor = ingredient.stock_status === 'low' ? '#ef4444' : (ingredient.stock_status === 'adequate' ? '#10b981' : '#f59e0b');
        document.getElementById('ingredientStockStatus').innerHTML = `
            <div style="color: ${statusColor}; font-weight: 600;">
                ${statusText}
            </div>
            <div style="font-size: 13px; color: var(--text-secondary); margin-top: 8px;">
                Current: <strong>${Number(ingredient.current_stock).toFixed(2)} ${ingredient.unit}</strong> | 
                Minimum: <strong>${Number(ingredient.minimum_stock).toFixed(2)}</strong>
            </div>
        `;

        document.getElementById('ingredientModal').classList.add('show');
    }

    function closeIngredientModal() {
        document.getElementById('ingredientModal').classList.remove('show');
        currentIngredientId = null;
    }

    async function selectAndCreatePO() {
        if (!currentIngredientId) return;
        const ingredient = allIngredients.find(i => i.id === currentIngredientId);
        if (!ingredient) return;

        const quantity = await Swal.fire({
            title: `Create Purchase Order`,
            html: `
                <div style="text-align: left;">
                    <p><strong>Ingredient:</strong> ${escapeHtml(ingredient.name)}</p>
                    <p><strong>Unit:</strong> ${escapeHtml(ingredient.unit)}</p>
                    <p><strong>Current Stock:</strong> ${Number(ingredient.current_stock).toFixed(2)}</p>
                    <p><strong>Minimum Stock:</strong> ${Number(ingredient.minimum_stock).toFixed(2)}</p>
                    <p><strong>Unit Cost:</strong> ₹${Number(ingredient.unit_cost).toFixed(2)}</p>
                </div>
                <input id="poQuantity" type="number" class="swal2-input" min="1" step="0.01" placeholder="Quantity to order" value="${Number(ingredient.minimum_stock).toFixed(2)}">
            `,
            showCancelButton: true,
            confirmButtonText: 'Create Order',
            preConfirm: () => {
                const qty = document.getElementById('poQuantity').value;
                if (!qty || qty <= 0) {
                    Swal.showValidationMessage('Please enter a valid quantity');
                }
                return qty;
            }
        });

        if (quantity.isConfirmed && quantity.value) {
            // Store ingredient info for PO page
            sessionStorage.setItem('ingredientForPO', JSON.stringify({
                ingredient_id: ingredient.id,
                ingredient_name: ingredient.name,
                unit: ingredient.unit,
                quantity: quantity.value,
                unit_cost: ingredient.unit_cost,
                supplier: ingredient.supplier
            }));
            window.location.href = 'purchase_orders.php?from=ingredients';
        }

        closeIngredientModal();
    }

    async function createPOForIngredient(ingredientId) {
        const ingredient = allIngredients.find(i => i.id === ingredientId);
        if (!ingredient) return;

        const {value: quantity} = await Swal.fire({
            title: 'Create Purchase Order for: ' + ingredient.name,
            html: `
                <div style="text-align: left; margin-bottom: 15px;">
                    <p><strong>Current Stock:</strong> ${Number(ingredient.current_stock).toFixed(2)} ${ingredient.unit}</p>
                    <p><strong>Minimum Required:</strong> ${Number(ingredient.minimum_stock).toFixed(2)} ${ingredient.unit}</p>
                    <p><strong>Unit Cost:</strong> ₹${Number(ingredient.unit_cost).toFixed(2)}</p>
                </div>
                <label style="display: block; text-align: left; margin-bottom: 8px; font-weight: 600;">Order Quantity:</label>
                <input id="poQty" type="number" class="swal2-input" min="1" step="0.01" placeholder="Enter quantity" value="${Number(ingredient.minimum_stock).toFixed(2)}">
            `,
            showCancelButton: true,
            confirmButtonText: 'Create PO',
            preConfirm: () => {
                const qty = document.getElementById('poQty').value;
                if (!qty || qty <= 0) {
                    Swal.showValidationMessage('Invalid quantity');
                    return false;
                }
                return qty;
            }
        });

        if (quantity) {
            sessionStorage.setItem('ingredientForPO', JSON.stringify({
                ingredient_id: ingredient.id,
                ingredient_name: ingredient.name,
                unit: ingredient.unit,
                quantity: quantity,
                unit_cost: ingredient.unit_cost,
                supplier: ingredient.supplier
            }));
            window.location.href = 'purchase_orders.php?from=ingredients';
        }
    }

    async function createPOForLowStock() {
        const lowStockItems = allIngredients.filter(i => i.stock_status === 'low');
        
        if (!lowStockItems.length) {
            Swal.fire('No Low Stock Items', 'All ingredients have adequate stock levels', 'info');
            return;
        }

        const itemsHtml = lowStockItems.map((ing, idx) => `
            <div style="padding: 10px; margin: 8px 0; background: #fee2e2; border-radius: 6px; border-left: 4px solid #ef4444;">
                <strong>${escapeHtml(ing.name)}</strong> - 
                Current: ${Number(ing.current_stock).toFixed(2)} ${ing.unit}, 
                Min: ${Number(ing.minimum_stock).toFixed(2)}
            </div>
        `).join('');

        Swal.fire({
            title: 'Create POs for Low Stock Items',
            html: `
                <div style="text-align: left; max-height: 300px; overflow-y: auto;">
                    <p>Found <strong>${lowStockItems.length}</strong> ingredient(s) with low stock:</p>
                    ${itemsHtml}
                </div>
            `,
            showCancelButton: true,
            confirmButtonText: 'Go to Purchase Orders',
            cancelButtonText: 'Cancel'
        }).then(result => {
            if (result.isConfirmed) {
                sessionStorage.setItem('lowStockIngredients', JSON.stringify(lowStockItems));
                window.location.href = 'purchase_orders.php?from=ingredients&lowstock=1';
            }
        });
    }

    function updateMetrics() {
        const total = allIngredients.length;
        const lowStock = allIngredients.filter(i => i.stock_status === 'low').length;
        const totalValue = allIngredients.reduce((sum, i) => sum + (Number(i.total_value) || 0), 0);
        const avgValue = total > 0 ? totalValue / total : 0;

        document.getElementById('totalCount').textContent = total;
        document.getElementById('lowStockCount').textContent = lowStock;
        document.getElementById('avgValue').textContent = '₹' + avgValue.toFixed(2);
        document.getElementById('totalValue').textContent = '₹' + totalValue.toFixed(2);
    }

    document.getElementById('searchInput').addEventListener('keyup', (e) => {
        const term = e.target.value.toLowerCase();
        const filtered = allIngredients.filter(i => 
            i.name.toLowerCase().includes(term) || 
            i.description?.toLowerCase().includes(term) ||
            i.unit.toLowerCase().includes(term)
        );
        renderTable(filtered);
    });

    document.getElementById('stockFilter').addEventListener('change', (e) => {
        const filter = e.target.value;
        let filtered = allIngredients;
        if (filter) {
            filtered = allIngredients.filter(i => i.stock_status === filter);
        }
        renderTable(filtered);
    });

    function exportIngredients() {
        const csv = [
            ['Ingredient', 'Unit', 'Current Stock', 'Minimum Stock', 'Unit Cost', 'Total Value', 'Status', 'Supplier'],
            ...allIngredients.map(i => [
                i.name,
                i.unit,
                i.current_stock,
                i.minimum_stock,
                i.unit_cost,
                i.total_value || 0,
                i.stock_status,
                i.supplier || '-'
            ])
        ].map(row => row.map(cell => `"${cell}"`).join(',')).join('\n');

        const blob = new Blob([csv], {type: 'text/csv'});
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'ingredients-' + new Date().toISOString().split('T')[0] + '.csv';
        a.click();
    }

    function handleLogout() {
        Swal.fire({
            title: 'Logout?',
            text: 'Are you sure you want to logout?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, Logout',
            cancelButtonText: 'Cancel'
        }).then(result => {
            if (result.isConfirmed) {
                window.location.href = '../backend/admin_logout.php';
            }
        });
    }

    function escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function showError(message) {
        Swal.fire('Error', message, 'error');
    }

    // ===== ADD/EDIT INGREDIENT FUNCTIONS =====
    function openAddIngredientModal() {
        document.getElementById('ingredientId').value = '';
        document.getElementById('addEditTitle').textContent = 'Add New Ingredient';
        document.getElementById('ingredientForm').reset();
        renderSupplierOptions();
        supplierProductsForAdd = [];
        document.getElementById('addSupplierProduct').innerHTML = '<option value="">Select supplier first...</option>';
        document.getElementById('addSupplierProductHint').textContent = 'Pick a supplier product to auto-fill ingredient details.';
        document.getElementById('addEditIngredientModal').classList.add('show');
    }

    function closeAddEditModal() {
        document.getElementById('addEditIngredientModal').classList.remove('show');
        document.getElementById('ingredientForm').reset();
    }

    function editIngredient(ingredientId) {
        const ingredient = allIngredients.find(i => i.id === ingredientId);
        if (!ingredient) return;

        document.getElementById('ingredientId').value = ingredient.id;
        document.getElementById('addEditTitle').textContent = 'Edit Ingredient: ' + ingredient.name;
        document.getElementById('addName').value = ingredient.name;
        document.getElementById('addDescription').value = ingredient.description || '';
        document.getElementById('addUnit').value = ingredient.unit;
        renderSupplierOptions(ingredient.supplier || '');
        document.getElementById('addCurrentStock').value = ingredient.current_stock;
        document.getElementById('addMinimumStock').value = ingredient.minimum_stock;
        document.getElementById('addUnitCost').value = ingredient.unit_cost;
        document.getElementById('addStatus').value = ingredient.status || 'active';
        document.getElementById('addSupplierProduct').innerHTML = '<option value="">Auto-fill is available only while adding new ingredient</option>';
        document.getElementById('addSupplierProductHint').textContent = 'Edit mode: supplier product auto-fill is disabled.';

        document.getElementById('addEditIngredientModal').classList.add('show');
    }

    async function saveIngredient(event) {
        event.preventDefault();

        const ingredientId = document.getElementById('ingredientId').value;
        const name = document.getElementById('addName').value.trim();
        const description = document.getElementById('addDescription').value.trim();
        const unit = document.getElementById('addUnit').value.trim();
        const supplier = document.getElementById('addSupplier').value.trim();
        const currentStock = Number(document.getElementById('addCurrentStock').value);
        const minimumStock = Number(document.getElementById('addMinimumStock').value);
        const unitCost = Number(document.getElementById('addUnitCost').value);
        const status = document.getElementById('addStatus').value;

        if (!name || !unit || currentStock < 0 || minimumStock < 0 || unitCost < 0) {
            showError('Please fill all required fields with valid values');
            return;
        }

        try {
            const action = ingredientId ? 'update_ingredient' : 'create_ingredient';
            const payload = {
                name, description, unit, supplier, current_stock: currentStock,
                minimum_stock: minimumStock, unit_cost: unitCost, status
            };

            if (ingredientId) {
                payload.id = ingredientId;
            }

            const response = await fetch('../backend/admin_ingredients_api.php?action=' + action, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

            const data = await response.json();

            if (!data.success) {
                showError(data.message || 'Failed to save ingredient');
                return;
            }

            Swal.fire('Success', ingredientId ? 'Ingredient updated successfully' : 'Ingredient created successfully', 'success');
            closeAddEditModal();
            loadIngredients();
        } catch (error) {
            showError('Error saving ingredient: ' + error.message);
        }
    }

    async function deleteIngredient(ingredientId) {
        const ingredient = allIngredients.find(i => i.id === ingredientId);
        if (!ingredient) return;

        const result = await Swal.fire({
            title: 'Delete Ingredient?',
            text: `Are you sure you want to delete "${ingredient.name}"? This action cannot be undone.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, Delete',
            cancelButtonText: 'Cancel',
            confirmButtonColor: '#ef4444'
        });

        if (!result.isConfirmed) return;

        try {
            const response = await fetch('../backend/admin_ingredients_api.php?action=delete_ingredient', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id: ingredientId })
            });

            const data = await response.json();

            if (!data.success) {
                showError(data.message || 'Failed to delete ingredient');
                return;
            }

            Swal.fire('Deleted', 'Ingredient deleted successfully', 'success');
            loadIngredients();
        } catch (error) {
            showError('Error deleting ingredient: ' + error.message);
        }
    }

    async function viewSmartReorderSuggestions() {
        const modal = document.getElementById('smartReorderModal');
        const summaryEl = document.getElementById('smartReorderSummary');
        const bodyEl = document.getElementById('smartReorderBody');

        summaryEl.innerHTML = '';
        bodyEl.innerHTML = '<p style="text-align:center; color:#6b7280; padding:20px;"><i class="fas fa-spinner fa-spin"></i> Generating smart reorder suggestions...</p>';
        modal.classList.add('show');

        try {
            const response = await fetch('../backend/ai_reorder_api.php?action=get_suggestions&horizon_days=14');
            const data = await response.json();

            if (!data.success) {
                throw new Error(data.message || 'Failed to generate suggestions');
            }

            const summary = data.summary || {};
            summaryEl.innerHTML = `
                <div style="background:#f8fafc; border:1px solid #e2e8f0; border-radius:10px; padding:12px;">
                    <div style="font-size:12px; color:#64748b;">Suggested Items</div>
                    <div style="font-size:24px; font-weight:800; color:#0f172a;">${Number(summary.total_items || 0)}</div>
                </div>
                <div style="background:#fff7ed; border:1px solid #fed7aa; border-radius:10px; padding:12px;">
                    <div style="font-size:12px; color:#9a3412;">Critical</div>
                    <div style="font-size:24px; font-weight:800; color:#c2410c;">${Number(summary.critical_items || 0)}</div>
                </div>
                <div style="background:#ecfdf5; border:1px solid #a7f3d0; border-radius:10px; padding:12px;">
                    <div style="font-size:12px; color:#065f46;">Estimated Budget</div>
                    <div style="font-size:24px; font-weight:800; color:#047857;">Rs.${Number(summary.estimated_total_cost || 0).toFixed(2)}</div>
                </div>
            `;

            const suggestions = Array.isArray(data.suggestions) ? data.suggestions : [];
            if (!suggestions.length) {
                bodyEl.innerHTML = '<p style="text-align:center; color:#16a34a; padding:24px;"><i class="fas fa-check-circle"></i> Great news. No immediate reorder needed.</p>';
                return;
            }

            bodyEl.innerHTML = `
                <table class="requests-table">
                    <thead>
                        <tr>
                            <th>Ingredient</th>
                            <th>Current</th>
                            <th>Suggested Qty</th>
                            <th>Usage/Day</th>
                            <th>Lead Time</th>
                            <th>Supplier</th>
                            <th>Est. Cost</th>
                            <th>Urgency</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${suggestions.map(item => {
                            const urgencyStyles = {
                                critical: 'background:#fee2e2;color:#991b1b;',
                                high: 'background:#ffedd5;color:#9a3412;',
                                medium: 'background:#fef3c7;color:#92400e;',
                                low: 'background:#dcfce7;color:#166534;'
                            };
                            const urgencyStyle = urgencyStyles[item.urgency] || urgencyStyles.medium;
                            return `
                                <tr>
                                    <td>
                                        <div style="font-weight:700;">${escapeHtml(item.ingredient_name)}</div>
                                        <div style="font-size:12px; color:#64748b;">${escapeHtml(item.reason || '')}</div>
                                    </td>
                                    <td>${Number(item.current_stock || 0).toFixed(2)} ${escapeHtml(item.unit || '')}</td>
                                    <td><strong>${Number(item.suggested_order_qty || 0).toFixed(2)} ${escapeHtml(item.unit || '')}</strong></td>
                                    <td>${Number(item.avg_daily_usage || 0).toFixed(2)}</td>
                                    <td>${Number(item.lead_time_days || 0)} day(s)</td>
                                    <td>${escapeHtml(item.supplier_name || 'Not mapped')}</td>
                                    <td>Rs.${Number(item.estimated_cost || 0).toFixed(2)}</td>
                                    <td><span class="badge" style="${urgencyStyle}">${escapeHtml((item.urgency || 'medium').toUpperCase())}</span></td>
                                    <td>
                                        <button class="btn btn-sm btn-success" onclick="openPurchaseOrderForIngredient(${Number(item.ingredient_id || 0)})">
                                            <i class="fas fa-cart-plus"></i> Create PO
                                        </button>
                                    </td>
                                </tr>
                            `;
                        }).join('')}
                    </tbody>
                </table>
            `;
        } catch (error) {
            bodyEl.innerHTML = `<p style="text-align:center; color:#dc2626; padding:20px;">${escapeHtml(error.message || 'Failed to load suggestions')}</p>`;
        }
    }

    function closeSmartReorderModal() {
        document.getElementById('smartReorderModal').classList.remove('show');
    }

    function openPurchaseOrderForIngredient(ingredientId) {
        window.location.href = `purchase_orders.php?ingredient_id=${ingredientId}`;
    }

    // View pending stock requests from admin
    async function viewPendingRequests() {
        try {
            const response = await fetch('../backend/admin_stock_request_api.php?action=get_requests', {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.message || 'Failed to fetch pending requests');
            }

            const requests = data.requests || [];
            const modalBody = document.getElementById('pendingRequestsBody');
            
            if (requests.length === 0) {
                modalBody.innerHTML = '<p style="text-align:center; color:#999; padding:20px;">No pending requests</p>';
            } else {
                let html = '<table class="requests-table">';
                html += '<thead><tr>';
                html += '<th>Ingredient</th>';
                html += '<th>Quantity</th>';
                html += '<th>Priority</th>';
                html += '<th>Requested</th>';
                html += '<th>Notes</th>';
                html += '<th>Action</th>';
                html += '</tr></thead><tbody>';

                requests.forEach(req => {
                    const createdDate = new Date(req.created_at).toLocaleDateString('en-US', {
                        month: 'short',
                        day: 'numeric',
                        hour: '2-digit',
                        minute: '2-digit'
                    });
                    const priorityClass = req.priority === 'high' ? 'priority-high' : req.priority === 'medium' ? 'priority-medium' : 'priority-low';
                    
                    html += `<tr>
                        <td>${escapeHtml(req.ingredient_name)}</td>
                        <td>${parseFloat(req.quantity_requested).toFixed(2)} ${req.unit}</td>
                        <td><span class="badge ${priorityClass}">${req.priority.toUpperCase()}</span></td>
                        <td>${createdDate}</td>
                        <td>${escapeHtml(req.notes || '-')}</td>
                        <td>
                            <button class="btn btn-sm btn-success" onclick="openReceiveModal('${req.id}', '${escapeHtml(req.ingredient_name)}', '${req.unit}', '${req.quantity_requested}')">
                                <i class="fas fa-check"></i> Receive
                            </button>
                        </td>
                    </tr>`;
                });

                html += '</tbody></table>';
                modalBody.innerHTML = html;
            }

            // Update badge count
            updatePendingBadge(requests.length);
            
            // Show modal using shared modal centering behavior
            document.getElementById('pendingRequestsModal').classList.add('show');
        } catch (error) {
            showError('Error loading pending requests: ' + error.message);
        }
    }

    // Update pending badge count
    function updatePendingBadge(count) {
        const badge = document.getElementById('pendingBadge');
        if (badge) {
            if (count > 0) {
                badge.textContent = count;
                badge.style.display = 'inline-block';
            } else {
                badge.style.display = 'none';
            }
        }
    }

    // Load pending count on page load
    async function loadPendingCount() {
        try {
            const response = await fetch('../backend/admin_stock_request_api.php?action=get_requests', {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            });

            const data = await response.json();
            const requests = data.requests || [];
            updatePendingBadge(requests.length);
        } catch (error) {
            console.log('Could not load pending count:', error.message);
        }
    }

    // Close pending requests modal
    function closePendingRequestsModal() {
        document.getElementById('pendingRequestsModal').classList.remove('show');
    }

    // Open receive delivery modal
    function openReceiveModal(requestId, ingredientName, unit, quantityRequested) {
        // Find current stock from allIngredients array
        const ingredient = allIngredients.find(ing => ing.name === ingredientName);
        const currentStock = ingredient ? parseFloat(ingredient.current_stock) : 0;

        document.getElementById('receiveRequestId').value = requestId;
        document.getElementById('receiveIngredientId').value = ingredient ? ingredient.id : '';
        document.getElementById('receiveIngredientName').value = ingredientName;
        document.getElementById('receiveUnit').value = unit;
        document.getElementById('receiveCurrentStock').value = currentStock.toFixed(2);
        document.getElementById('receiveQuantityOrdered').value = quantityRequested;
        document.getElementById('receiveQuantityDelivered').value = '';
        document.getElementById('receiveInvoiceRef').value = '';
        
        // Close pending modal
        closePendingRequestsModal();
        
        // Show receive modal using shared modal centering behavior
        document.getElementById('receiveDeliveryModal').classList.add('show');
    }

    // Close receive delivery modal
    function closeReceiveModal() {
        document.getElementById('receiveDeliveryModal').classList.remove('show');
    }

    // Confirm delivery receipt and auto-update stock
    async function confirmDeliveryReceipt(e) {
        e.preventDefault();
        
        const requestId = document.getElementById('receiveRequestId').value;
        const ingredientId = document.getElementById('receiveIngredientId').value;
        const ingredientName = document.getElementById('receiveIngredientName').value;
        const quantityDelivered = parseFloat(document.getElementById('receiveQuantityDelivered').value);
        const invoiceRef = document.getElementById('receiveInvoiceRef').value;

        if (!quantityDelivered || quantityDelivered <= 0) {
            showError('Please enter a valid quantity delivered');
            return;
        }

        if (!ingredientId) {
            showError('Ingredient not found');
            return;
        }

        try {
            // Update stock
            const updateResponse = await fetch('../backend/admin_ingredients_api.php?action=update_stock', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    id: ingredientId,
                    quantity_received: quantityDelivered
                })
            });

            const updateData = await updateResponse.json();

            if (!updateResponse.ok) {
                throw new Error(updateData.message || 'Failed to update stock');
            }

            // Mark request as fulfilled
            const fulfillResponse = await fetch('../backend/admin_stock_request_api.php?action=fulfill_request', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    request_id: requestId,
                    quantity_delivered: quantityDelivered,
                    invoice_ref: invoiceRef
                })
            });

            const fulfillData = await fulfillResponse.json();

            if (!fulfillResponse.ok) {
                throw new Error(fulfillData.message || 'Failed to mark request as fulfilled');
            }

            Swal.fire('Success', `Stock updated! Added ${quantityDelivered} units to ${ingredientName}`, 'success');
            
            closeReceiveModal();
            loadIngredients();
            loadPendingCount();
        } catch (error) {
            showError('Error confirming delivery: ' + error.message);
        }
    }

    // Modal close handlers
    // Update new ingredients notification badge
    async function updateNewIngredientsBadge() {
        try {
            const response = await fetch('../backend/admin_new_ingredient_request_api.php?action=get_requests&status=pending', {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            });

            const data = await response.json();
            const count = data.count || 0;
            const badge = document.getElementById('navNewIngredientsCount');

            if (badge) {
                if (count > 0) {
                    badge.textContent = count;
                    badge.style.display = 'flex';
                } else {
                    badge.style.display = 'none';
                }
            }
        } catch (error) {
            console.log('Could not load new ingredients count');
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
        const supplierSelect = document.getElementById('addSupplier');
        const supplierProductSelect = document.getElementById('addSupplierProduct');
        if (supplierSelect) supplierSelect.addEventListener('change', onAddSupplierChange);
        if (supplierProductSelect) supplierProductSelect.addEventListener('change', onAddSupplierProductChange);

        // Smart reorder modal close on outside click
        document.getElementById('smartReorderModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeSmartReorderModal();
            }
        });

        // Pending requests modal close on outside click
        document.getElementById('pendingRequestsModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closePendingRequestsModal();
            }
        });

        // Receive delivery modal close on outside click
        document.getElementById('receiveDeliveryModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeReceiveModal();
            }
        });

        // Receive form submit handler
        const receiveForm = document.getElementById('receiveDeliveryForm');
        if (receiveForm) {
            receiveForm.addEventListener('submit', confirmDeliveryReceipt);
        }
    });

    // Initialize on page load
    checkSession();
    loadIngredients();
    loadSupplierOptions();
    loadPendingCount();
    updateNewIngredientsBadge();
    setInterval(updateNewIngredientsBadge, 30000);
    setInterval(loadIngredients, 30000); // Refresh every 30 seconds
    setInterval(loadPendingCount, 60000); // Refresh pending count every 60 seconds
</script>
<script src="./pm-sidebar.js"></script>
</body>
</html>
