<?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="Low Stock Ingredients - 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>Low Stock Ingredients</title>
</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>Low Stock Ingredients</h1>
            <p>Items below minimum stock level that need replenishment</p>
        </div>
    </div>

    <!-- ALERT -->
    <div id="alertContainer" style="margin-bottom: 20px;"></div>

    <!-- STATS ROW -->
    <div class="metric-strip">
        <div class="metric-card">
            <div class="label">Low Stock Items</div>
            <div class="value" id="lowStockCount">0</div>
        </div>
        <div class="metric-card">
            <div class="label">Total Units Needed</div>
            <div class="value" id="totalNeeded">0</div>
        </div>
        <div class="metric-card">
            <div class="label">Avg Suppliers/Item</div>
            <div class="value" id="avgSuppliers">0</div>
        </div>
    </div>

    <!-- TABLE -->
    <div class="table-wrapper">
        <table>
            <thead>
                <tr>
                    <th width="18%">Ingredient Name</th>
                    <th width="10%">Current Stock</th>
                    <th width="10%">Minimum Stock</th>
                    <th width="12%">Quantity Needed</th>
                    <th width="10%">Unit</th>
                    <th width="10%">Unit Cost</th>
                    <th width="12%">Suppliers Available</th>
                    <th width="12%">Actions</th>
                </tr>
            </thead>
            <tbody id="stockBody">
                <tr><td colspan="8" class="empty-state"><i class="fas fa-spinner"></i> Loading low stock items...</td></tr>
            </tbody>
        </table>
    </div>
</div>

<!-- SUPPLIERS MODAL -->
<div class="modal" id="suppliersModal">
    <div class="modal-content">
        <div class="modal-header">
            <span id="suppliersTitle">Available Suppliers</span>
            <button class="close" type="button" onclick="closeSuppliersModal()">&times;</button>
        </div>
        <div style="padding: 24px;">
            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>
                            <th width="20%">Supplier</th>
                            <th width="15%">Unit Price</th>
                            <th width="15%">Lead Time</th>
                            <th width="15%">Min Order</th>
                            <th width="15%">Status</th>
                            <th width="20%">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="suppliersBody">
                        <tr><td colspan="6" class="empty-state">No suppliers available</td></tr>
                    </tbody>
                </table>
            </div>
            <div style="margin-top: 20px;">
                <button class="btn-secondary" onclick="closeSuppliersModal()" style="width: 100%;">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- PURCHASE ORDER PREVIEW MODAL -->
<div class="modal" id="poPreviewModal">
    <div class="modal-content">
        <div class="modal-header">
            <span id="poTitle">Create Purchase Order</span>
            <button class="close" type="button" onclick="closePoPreviewModal()">&times;</button>
        </div>
        <form id="poForm" onsubmit="createPurchaseOrder(event)">
            <input type="hidden" id="poIngredientId">
            <input type="hidden" id="poQuantityNeeded">
            
            <div style="padding: 24px;">
                <div class="form-group">
                    <label><i class="fas fa-leaf"></i> Ingredient</label>
                    <input id="poIngredientName" disabled style="background: #f5f5f5;">
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label><i class="fas fa-cubes"></i> Quantity Needed</label>
                        <input id="poQtyNeeded" type="number" step="0.01" disabled style="background: #f5f5f5;">
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-balance-scale"></i> Unit</label>
                        <input id="poUnit" disabled style="background: #f5f5f5;">
                    </div>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label><i class="fas fa-store"></i> Supplier *</label>
                        <select id="poSupplier" required onchange="onSupplierSelected()">
                            <option value="">Select supplier...</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-money-bill"></i> Unit Price</label>
                        <input id="poSupplierPrice" type="number" step="0.01" disabled style="background: #f5f5f5;">
                    </div>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label><i class="fas fa-cube"></i> Order Quantity *</label>
                        <input id="poOrderQty" type="number" step="0.01" required placeholder="Quantity to order">
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-money-bill"></i> Total Cost</label>
                        <input id="poTotalCost" type="number" step="0.01" disabled style="background: #f5f5f5;">
                    </div>
                </div>

                <div class="form-group">
                    <label><i class="fas fa-calendar-days"></i> Expected Delivery</label>
                    <input id="poExpectedDelivery" type="date" disabled style="background: #f5f5f5;">
                </div>

                <div class="form-group">
                    <label><i class="fas fa-note-sticky"></i> Notes</label>
                    <textarea id="poNotes" rows="2" placeholder="Any special instructions..."></textarea>
                </div>

                <div style="display: flex; gap: 12px; justify-content: flex-end; margin-top: 20px;">
                    <button type="button" class="btn-secondary" onclick="closePoPreviewModal()">Cancel</button>
                    <button type="submit" class="btn-primary"><i class="fas fa-check"></i> Create Order</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script>
    let lowStockItems = [];
    let selectedSuppliers = [];
    let currentIngredientId = null;
    let supplierPricesMap = {};

    function findLowStockItemById(ingredientId) {
        const targetId = Number(ingredientId);
        return lowStockItems.find(i => Number(i.id) === targetId);
    }

    function normalizeSuppliers(rows) {
        if (!Array.isArray(rows)) return [];
        return rows.map(row => ({
            ...row,
            supplier_id: Number(row.supplier_id || row.id || 0),
            supplier_name: row.supplier_name || row.name || 'Unknown',
            unit_price: Number(row.unit_price || row.price || 0),
            lead_time_days: Number(row.lead_time_days || row.supplier_lead_time || 0),
            minimum_order_qty: Number(row.minimum_order_qty ?? row.minimum_order_quantity ?? 1)
        })).filter(row => row.supplier_id > 0);
    }

    async function enrichMissingSupplierCounts(items) {
        const missing = (items || []).filter(item => Number(item.supplier_count || 0) <= 0);
        if (!missing.length) return;

        await Promise.all(missing.map(async item => {
            try {
                const response = await fetch(`../backend/supplier_products_api.php?action=get_supplier_products_for_ingredient&ingredient_id=${item.id}`);
                const data = await response.json();
                const suppliers = normalizeSuppliers(data.products || []);
                const uniqueSupplierIds = new Set(
                    suppliers
                        .map(s => Number(s.supplier_id || 0))
                        .filter(id => id > 0)
                );
                item.supplier_count = uniqueSupplierIds.size;
            } catch (e) {
                // Keep current supplier_count when lookup fails.
            }
        }));
    }

    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 || 'PM';
        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;
        loadLowStockItems();
    }

    async function loadLowStockItems() {
        try {
            // Primary source: ingredient stock API (does not depend on supplier-product mapping).
            const stockResponse = await fetch('../backend/admin_ingredients_api.php?action=get_low_stock');
            const stockData = await stockResponse.json();

            const lowItems = (stockData.success && stockData.data?.items)
                ? stockData.data.items.map(item => ({
                    ...item,
                    quantity_needed: Number(item.shortage_amount || 0),
                    supplier_count: 0,
                    unit_cost: Number(item.unit_cost || 0)
                }))
                : [];

            // Optional enrichment: merge supplier counts from supplier-products endpoint.
            try {
                const supplierResponse = await fetch('../backend/supplier_products_api.php?action=get_low_stock_ingredients');
                const supplierData = await supplierResponse.json();
                if (supplierData.success && Array.isArray(supplierData.ingredients)) {
                    const supplierMap = new Map(
                        supplierData.ingredients.map(it => [Number(it.id), {
                            supplier_count: Number(it.supplier_count || 0),
                            unit_cost: Number(it.unit_cost || 0),
                            quantity_needed: Number(it.quantity_needed || 0)
                        }])
                    );

                    lowItems.forEach(item => {
                        const extra = supplierMap.get(Number(item.id));
                        if (!extra) return;
                        item.supplier_count = extra.supplier_count;
                        if (extra.unit_cost > 0) item.unit_cost = extra.unit_cost;
                        if (extra.quantity_needed > 0) item.quantity_needed = extra.quantity_needed;
                    });
                }
            } catch (e) {
                // Keep base low-stock data even when supplier enrichment fails.
            }

            // Backfill supplier count from the same endpoint used by "View Suppliers" / "Create order".
            await enrichMissingSupplierCounts(lowItems);

            lowStockItems = lowItems;
            displayItems(lowItems);
            updateStats();
        } catch (error) {
            console.error('Error loading low stock items:', error);
            Swal.fire('Error', 'Failed to load low stock items', 'error');
        }
    }

    function displayItems(items) {
        const tbody = document.getElementById('stockBody');

        if (!items || items.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8" class="empty-state"><i class="fas fa-check-circle"></i> All ingredients are well stocked!</td></tr>';
            return;
        }

        tbody.innerHTML = items.map(item => {
            const totalCost = (item.quantity_needed * item.unit_cost).toFixed(2);
            const supplierColor = item.supplier_count > 0 ? '#10b981' : '#f97316';
            
            return `
            <tr>
                <td><strong>${escapeHtml(item.name)}</strong></td>
                <td><span style="background: #fee2e2; padding: 4px 8px; border-radius: 4px;">${Number(item.current_stock).toFixed(2)}</span></td>
                <td>${Number(item.minimum_stock).toFixed(2)}</td>
                <td><span style="background: #fef3c7; padding: 4px 8px; border-radius: 4px; font-weight: 600;">${Number(item.quantity_needed).toFixed(2)}</span></td>
                <td>${escapeHtml(item.unit)}</td>
                <td>$${Number(item.unit_cost).toFixed(2)}</td>
                <td><span style="color: ${supplierColor}; font-weight: 600;"><i class="fas fa-store"></i> ${item.supplier_count}</span></td>
                <td>
                    <div class="action-buttons">
                        <button class="action-btn view" onclick="showSuppliers(${item.id})" title="View suppliers"><i class="fas fa-list"></i></button>
                        <button class="action-btn" style="background: #10b981;" onclick="quickOrder(${item.id})" title="Create order"><i class="fas fa-shopping-cart"></i></button>
                    </div>
                </td>
            </tr>
        `;
        }).join('');
    }

    function updateStats() {
        const count = lowStockItems.length;
        const totalQtyNeeded = lowStockItems.reduce((sum, item) => sum + parseFloat(item.quantity_needed), 0);
        const avgSuppliers = count > 0 ? (lowStockItems.reduce((sum, item) => sum + parseInt(item.supplier_count), 0) / count).toFixed(1) : 0;

        document.getElementById('lowStockCount').textContent = count;
        document.getElementById('totalNeeded').textContent = totalQtyNeeded.toFixed(2);
        document.getElementById('avgSuppliers').textContent = avgSuppliers;

        if (count > 0) {
            const alertHtml = `<div style="background: #fef3c7; border: 1px solid #fcd34d; border-radius: 8px; padding: 12px 16px; color: #854d0e;"><i class="fas fa-exclamation-circle"></i> <strong>${count}</strong> ingredient(s) below minimum stock level</div>`;
            document.getElementById('alertContainer').innerHTML = alertHtml;
        } else {
            document.getElementById('alertContainer').innerHTML = '';
        }
    }

    async function showSuppliers(ingredientId) {
        currentIngredientId = Number(ingredientId);
        const item = findLowStockItemById(ingredientId);
        if (!item) return;

        document.getElementById('suppliersTitle').textContent = `Suppliers for ${item.name}`;

        try {
            const response = await fetch(`../backend/supplier_products_api.php?action=get_supplier_products_for_ingredient&ingredient_id=${item.id}`);
            const data = await response.json();

            selectedSuppliers = normalizeSuppliers(data.products || []);
            
            if (selectedSuppliers.length === 0) {
                document.getElementById('suppliersBody').innerHTML = '<tr><td colspan="6" class="empty-state">No suppliers available for this ingredient. Add suppliers first!</td></tr>';
                document.getElementById('suppliersModal').classList.add('show');
                return;
            }

            displaySuppliers(selectedSuppliers);
            document.getElementById('suppliersModal').classList.add('show');

            // Pre-populate suppliers map
            supplierPricesMap = {};
            selectedSuppliers.forEach(s => {
                supplierPricesMap[s.supplier_id] = {
                    name: s.supplier_name,
                    price: s.unit_price,
                    leadDays: s.lead_time_days
                };
            });

        } catch (error) {
            console.error('Error loading suppliers:', error);
            Swal.fire('Error', 'Failed to load suppliers', 'error');
        }
    }

    function displaySuppliers(suppliers) {
        const tbody = document.getElementById('suppliersBody');

        if (!suppliers || suppliers.length === 0) {
            tbody.innerHTML = '<tr><td colspan="6" class="empty-state">No suppliers available</td></tr>';
            return;
        }

        tbody.innerHTML = suppliers.map(s => `
            <tr>
                <td><strong>${escapeHtml(s.supplier_name || 'Unknown')}</strong></td>
                <td>$${Number(s.unit_price || s.price || 0).toFixed(2)}</td>
                <td>${s.lead_time_days || 0} days</td>
                <td>${Number(s.minimum_order_qty || 1).toFixed(2)}</td>
                <td><span class="status-badge status-available">${s.availability || 'Available'}</span></td>
                <td>
                    <button class="btn-primary" onclick="prepareOrder(${s.supplier_id})" style="width: auto;"><i class="fas fa-edit"></i> Order</button>
                </td>
            </tr>
        `).join('');
    }

    async function quickOrder(ingredientId) {
        currentIngredientId = Number(ingredientId);
        const item = findLowStockItemById(ingredientId);
        if (!item) return;

        try {
            const response = await fetch(`../backend/supplier_products_api.php?action=get_supplier_products_for_ingredient&ingredient_id=${item.id}`);
            const data = await response.json();

            if (data.success && data.products?.length) {
                selectedSuppliers = normalizeSuppliers(data.products);
                openPoModal(item.id);
            } else {
                Swal.fire('Info', 'No suppliers available. Please add supplier products first.', 'info');
            }
        } catch (error) {
            console.error('Error:', error);
            Swal.fire('Error', 'Failed to load supplier information', 'error');
        }
    }

    function prepareOrder(supplierId) {
        closeSuppliersModal();
        
        const supplier = selectedSuppliers.find(s => Number(s.supplier_id) === Number(supplierId));
        if (!supplier) return;

        const item = findLowStockItemById(currentIngredientId);
        if (!item) return;

        openPoModal(item.id, Number(supplierId));
    }

    function openPoModal(ingredientId, supplierId = null) {
        const item = findLowStockItemById(ingredientId);
        if (!item) return;

        document.getElementById('poIngredientId').value = ingredientId;
        document.getElementById('poQuantityNeeded').value = item.quantity_needed;
        document.getElementById('poIngredientName').value = item.name;
        document.getElementById('poQtyNeeded').value = Number(item.quantity_needed).toFixed(2);
        document.getElementById('poUnit').value = item.unit;
        document.getElementById('poOrderQty').value = Number(item.quantity_needed).toFixed(2);
        document.getElementById('poNotes').value = '';

        // Populate suppliers dropdown
        const select = document.getElementById('poSupplier');
        select.innerHTML = '<option value="">Select supplier...</option>' +
            selectedSuppliers.map(s => `<option value="${s.supplier_id}" data-price="${s.unit_price}" data-lead="${s.lead_time_days || 0}">${escapeHtml(s.supplier_name)}</option>`).join('');

        if (supplierId) {
            select.value = String(supplierId);
            onSupplierSelected();
        }

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

    function closePoPreviewModal() {
        document.getElementById('poPreviewModal').classList.remove('show');
    }

    function onSupplierSelected() {
        const select = document.getElementById('poSupplier');
        const option = select.options[select.selectedIndex];
        const price = parseFloat(option.dataset.price) || 0;
        const leadDays = parseInt(option.dataset.lead) || 0;

        document.getElementById('poSupplierPrice').value = price.toFixed(2);

        const qty = parseFloat(document.getElementById('poOrderQty').value) || 0;
        const total = (qty * price).toFixed(2);
        document.getElementById('poTotalCost').value = total;

        // Set expected delivery date
        const today = new Date();
        const deliveryDate = new Date(today);
        deliveryDate.setDate(deliveryDate.getDate() + leadDays);
        document.getElementById('poExpectedDelivery').value = deliveryDate.toISOString().split('T')[0];

        // Update total when quantity changes
        document.getElementById('poOrderQty').addEventListener('input', () => {
            const newQty = parseFloat(document.getElementById('poOrderQty').value) || 0;
            const newTotal = (newQty * price).toFixed(2);
            document.getElementById('poTotalCost').value = newTotal;
        });
    }

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

        const ingredientId = parseInt(document.getElementById('poIngredientId').value);
        const supplierId = parseInt(document.getElementById('poSupplier').value);
        const quantity = parseFloat(document.getElementById('poOrderQty').value);
        const unitPrice = parseFloat(document.getElementById('poSupplierPrice').value);
        const notes = document.getElementById('poNotes').value;
        const expectedDelivery = document.getElementById('poExpectedDelivery').value;

        const item = findLowStockItemById(ingredientId);
        if (!item) return;

        try {
            const response = await fetch('../backend/purchase_orders_api.php?action=create', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'create',
                    supplier_id: supplierId,
                    ingredient_id: ingredientId,
                    item_name: item.name,
                    quantity: quantity,
                    unit: item.unit,
                    unit_price: unitPrice,
                    expected_delivery_date: expectedDelivery,
                    notes: notes
                })
            });

            const data = await response.json();
            if (data.success) {
                Swal.fire('Success!', 'Purchase order created successfully', 'success');
                closePoPreviewModal();
                window.location.href = 'purchase_orders.php?new=' + data.po_id;
            } else {
                Swal.fire('Error', data.message || 'Failed to create purchase order', 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            Swal.fire('Error', 'Request failed', 'error');
        }
    }

    function closeSuppliersModal() {
        document.getElementById('suppliersModal').classList.remove('show');
    }

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

    async function handleLogout() {
        const result = await Swal.fire({
            title: 'Logout',
            text: 'Are you sure?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, logout',
            confirmButtonColor: '#dc2626'
        });

        if (result.isConfirmed) {
            await fetch('../backend/purchase_manager_logout.php');
            window.location.href = 'login.php';
        }
    }

    async function updateNewIngredientsBadge() {
        try {
            const response = await fetch('../backend/admin_new_ingredient_request_api.php?action=get_requests&status=pending');
            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');
        }
    }

    // Event listeners
    document.getElementById('suppliersModal')?.addEventListener('click', e => {
        if (e.target === e.currentTarget) closeSuppliersModal();
    });
    document.getElementById('poPreviewModal')?.addEventListener('click', e => {
        if (e.target === e.currentTarget) closePoPreviewModal();
    });

    document.addEventListener('DOMContentLoaded', function() {
        checkSession();
        updateNewIngredientsBadge();
        setInterval(updateNewIngredientsBadge, 30000);
    });
</script>

<script src="./pm-sidebar.js"></script>
</body>
</html>
    </div>
