<?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="Purchase Orders - Purchase Manager">
    <link href="../assets/images/favicon/favicon.png" rel="icon">
    <link href="https://fonts.googleapis.com/css?family=Raleway:400,500,600,700,800" rel="stylesheet">
    <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>Purchase Orders</title>
</head>
<body>
<?php include 'pm-sidebar.php'; ?>
<div class="pm-main-container">
    <div class="container">
    <div class="page-header">
        <h1>Purchase Orders</h1>
        <p>Create from approved requisitions, track shipment, receive stock to inventory.</p>
    </div>

    <div class="toolbar">
        <button class="btn-primary" onclick="openOrderModal()"><i class="fas fa-plus"></i> New PO</button>
        <button class="btn-primary" onclick="startBulkLowStockPurchase()" style="background:#f59e0b;"><i class="fas fa-list-check"></i> Create From Low Stock</button>
        <button class="btn-secondary" onclick="loadOrders()"><i class="fas fa-rotate"></i> Refresh</button>
    </div>

    <div class="table-wrapper">
        <table>
            <thead>
            <tr>
                <th>PO</th>
                <th>Supplier</th>
                <th>Item</th>
                <th>Ordered</th>
                <th>Received</th>
                <th>Cost</th>
                <th>Status</th>
                <th>ETA</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody id="orderBody">
            <tr><td colspan="9" class="empty-state">Loading orders...</td></tr>
            </tbody>
        </table>
    </div>
</div>

<div class="modal" id="orderModal">
    <div class="modal-content">
        <div class="modal-header">
            <span>Create Purchase Order</span>
            <button class="close" type="button" onclick="closeOrderModal()">&times;</button>
        </div>
        <form id="orderForm" onsubmit="saveOrder(event)">
            <div class="form-grid">
                <div class="form-group">
                    <label>Approved Requisition</label>
                    <select id="requisitionId">
                        <option value="">Manual PO</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Supplier *</label>
                    <select id="supplierId" required></select>
                </div>
                <div class="form-group">
                    <label>Item Name *</label>
                    <input id="itemName" required>
                </div>
                <div class="form-group">
                    <label>Ingredient</label>
                    <select id="ingredientId">
                        <option value="">Manual item (not linked)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Quantity *</label>
                    <input id="quantity" type="number" step="0.001" min="0.001" required>
                </div>
                <div class="form-group">
                    <label>Unit *</label>
                    <input id="unit" required>
                </div>
                <div class="form-group">
                    <label>Unit Price</label>
                    <input id="unitPrice" type="number" step="0.01" min="0">
                </div>
                <div class="form-group">
                    <label>Expected Delivery Date</label>
                    <input id="expectedDeliveryDate" type="date">
                </div>
            </div>
            <div class="form-group">
                <label>Notes</label>
                <textarea id="notes" rows="3"></textarea>
            </div>
            <div id="manualBatchSection" style="display:none; margin-bottom:14px; border:1px solid var(--border-color); border-radius:10px; padding:12px;">
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px;">
                    <strong>Manual Item Batch</strong>
                    <button type="button" class="btn-secondary" onclick="addCurrentItemToBatch()"><i class="fas fa-plus"></i> Add Current Item</button>
                </div>
                <div class="table-wrapper" style="margin:0;">
                    <table>
                        <thead>
                        <tr>
                            <th>Supplier</th>
                            <th>Item</th>
                            <th>Qty</th>
                            <th>Unit</th>
                            <th>Price</th>
                            <th>Action</th>
                        </tr>
                        </thead>
                        <tbody id="manualBatchBody">
                        <tr><td colspan="6" class="empty-state">No items added yet.</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <button class="btn-primary" type="submit"><i class="fas fa-check"></i> Create PO</button>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script>
    let suppliers = [];
    let approvedRequisitions = [];
    let bulkLowStockQueue = [];
    let manualBatchItems = [];

    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 loadSuppliers() {
        const response = await fetch('../backend/purchase_orders_api.php?action=get_suppliers');
        const data = await response.json();
        suppliers = data.suppliers || [];
        setSupplierOptions(suppliers);
    }

    async function loadIngredientsForManual() {
        const response = await fetch('../backend/admin_ingredients_api.php?action=get_ingredients&status=active');
        const data = await response.json();
        const ingredients = data?.data || [];
        const select = document.getElementById('ingredientId');
        select.innerHTML = '<option value="">Manual item (not linked)</option>' + ingredients.map(i =>
            `<option value="${i.id}" data-name="${escapeHtmlAttr(i.name)}" data-unit="${escapeHtmlAttr(i.unit)}">${escapeHtml(i.name)} (${escapeHtml(i.unit)})</option>`
        ).join('');
    }

    function setSupplierOptions(list, preferredSupplierId = null) {
        const select = document.getElementById('supplierId');
        const safe = Array.isArray(list) ? list : [];
        select.innerHTML = safe.map(s => `<option value="${s.id}">${escapeHtml(s.name)}</option>`).join('');
        if (preferredSupplierId) {
            select.value = String(preferredSupplierId);
        }
    }

    async function onIngredientChange() {
        const ingredientSelect = document.getElementById('ingredientId');
        const selected = ingredientSelect.options[ingredientSelect.selectedIndex];
        const ingredientId = ingredientSelect.value;

        if (selected && ingredientId) {
            if (selected.dataset.name) document.getElementById('itemName').value = selected.dataset.name;
            if (selected.dataset.unit) document.getElementById('unit').value = selected.dataset.unit;
        }

        if (!ingredientId) {
            setSupplierOptions(suppliers);
            return;
        }

        try {
            const response = await fetch(`../backend/supplier_products_api.php?action=get_supplier_products_for_ingredient&ingredient_id=${ingredientId}`);
            const data = await response.json();
            const products = data.products || [];
            const bySupplier = new Map();

            products.forEach(p => {
                const sid = Number(p.supplier_id || 0);
                const sname = p.supplier_name || '';
                if (!sid || !sname) return;
                if (!bySupplier.has(sid)) {
                    bySupplier.set(sid, { id: sid, name: sname, unit_price: Number(p.unit_price || 0) });
                }
            });

            const filtered = Array.from(bySupplier.values());
            if (filtered.length > 0) {
                setSupplierOptions(filtered);
                if (filtered.length === 1) {
                    document.getElementById('supplierId').value = String(filtered[0].id);
                    if (!document.getElementById('unitPrice').value && filtered[0].unit_price > 0) {
                        document.getElementById('unitPrice').value = filtered[0].unit_price.toFixed(2);
                    }
                }
            } else {
                setSupplierOptions(suppliers);
            }
        } catch (e) {
            setSupplierOptions(suppliers);
        }
    }

    async function loadApprovedRequisitions() {
        const response = await fetch('../backend/purchase_orders_api.php?action=get_approved_requisitions');
        const data = await response.json();
        approvedRequisitions = data.requisitions || [];
        const select = document.getElementById('requisitionId');
        select.innerHTML = '<option value="">Manual PO</option>' + approvedRequisitions.map(r => {
            return `<option value="${r.id}" data-item="${escapeHtmlAttr(r.item_description)}" data-unit="${escapeHtmlAttr(r.unit)}" data-qty="${r.quantity}" data-ingredient="${r.ingredient_id || ''}">REQ-${String(r.id).padStart(5, '0')} - ${escapeHtml(r.item_description)}</option>`;
        }).join('');
    }

    async function loadOrders() {
        const response = await fetch('../backend/purchase_orders_api.php?action=get_all');
        const data = await response.json();
        const tbody = document.getElementById('orderBody');
        tbody.innerHTML = '';

        if (!data.success || !data.orders?.length) {
            tbody.innerHTML = '<tr><td colspan="9" class="empty-state">No purchase orders found.</td></tr>';
            return;
        }

        data.orders.forEach(order => {
            const orderedQty = Number(order.quantity || 0);
            const receivedQty = Number(order.received_quantity || 0);
            const remainingQty = Math.max(0, orderedQty - receivedQty);
            const orderStatusRaw = String(order.status ?? '').trim();
            const orderStatus = orderStatusRaw.toLowerCase();
            const hasUnknownStatus = orderStatus === '';
            let effectiveStatus;
            if (orderStatus === 'cancelled') {
                effectiveStatus = 'cancelled';
            } else if (receivedQty >= orderedQty && orderedQty > 0) {
                effectiveStatus = 'delivered';
            } else if (receivedQty > 0) {
                effectiveStatus = 'partially_received';
            } else {
                effectiveStatus = hasUnknownStatus ? 'confirmed' : orderStatus;
            }
            const effectiveStatusLabel = effectiveStatus === 'partially_received'
                ? 'PARTIALLY DELIVERED'
                : effectiveStatus.toUpperCase();
            const canMarkShipped = remainingQty > 0
                && receivedQty <= 0
                && (hasUnknownStatus || ['draft', 'confirmed'].includes(orderStatus));
            const actionButtons = [];

            if (canMarkShipped) {
                actionButtons.push(`<button class="action-btn btn-edit" onclick="updateStatus(${order.id}, 'shipped')">Mark Shipped</button>`);
            }
            tbody.innerHTML += `
                <tr>
                    <td>${escapeHtml(order.po_number || ('PO-' + String(order.id).padStart(5, '0')))}</td>
                    <td>${escapeHtml(order.supplier_name || 'N/A')}</td>
                    <td>${escapeHtml(order.item_name)}</td>
                    <td>${orderedQty.toFixed(3).replace(/\.?0+$/, '')} ${escapeHtml(order.unit || '')}</td>
                    <td>${receivedQty.toFixed(3).replace(/\.?0+$/, '')} ${escapeHtml(order.unit || '')}</td>
                    <td>₹${Number(order.total_cost || 0).toFixed(2)}</td>
                    <td><span class="status-badge status-${escapeHtml(effectiveStatus)}">${escapeHtml(effectiveStatusLabel)}</span></td>
                    <td>${escapeHtml(order.expected_delivery_date || '-')}</td>
                    <td>${actionButtons.join(' ') || '<span style="color:#9ca3af;">-</span>'}</td>
                </tr>
            `;
        });
    }

    function openOrderModal() {
        document.getElementById('orderForm').reset();
        manualBatchItems = [];
        renderManualBatch();
        handleRequisitionMode();
        setSupplierOptions(suppliers);
        document.getElementById('orderModal').classList.add('show');
    }

    function closeOrderModal() {
        document.getElementById('orderModal').classList.remove('show');
    }

    async function saveOrder(event) {
        event.preventDefault();
        const requisitionId = document.getElementById('requisitionId').value || null;

        if (requisitionId || manualBatchItems.length === 0) {
            const payload = buildCurrentFormPayload();
            const result = await createSinglePO(payload);
            if (!result.success) return;
            Swal.fire('Created', result.message || 'Purchase order created', 'success');
            closeOrderModal();
            loadApprovedRequisitions();
            loadOrders();
        } else {
            const batchPayload = {
                action: 'create_batch_document',
                expected_delivery_date: document.getElementById('expectedDeliveryDate').value || null,
                notes: document.getElementById('notes').value.trim(),
                items: manualBatchItems.map(item => ({
                    supplier_id: item.supplier_id,
                    item_name: item.item_name,
                    ingredient_id: item.ingredient_id || null,
                    quantity: item.quantity,
                    unit: item.unit,
                    unit_price: item.unit_price || 0,
                    expected_delivery_date: item.expected_delivery_date || null,
                    notes: item.notes || ''
                }))
            };

            const result = await createSinglePO(batchPayload);
            if (!result.success) {
                Swal.fire('Error', result.message || 'Failed to create combined purchase order', 'error');
                return;
            }
            Swal.fire('Created', `${result.po_number} created with ${result.line_count || manualBatchItems.length} line item(s)`, 'success');
            closeOrderModal();
            loadApprovedRequisitions();
            loadOrders();
        }

        if (bulkLowStockQueue.length > 0) {
            bulkLowStockQueue.shift();
            if (bulkLowStockQueue.length > 0) {
                const nextItem = bulkLowStockQueue[0];
                const continueResult = await Swal.fire({
                    title: 'Create Next PO?',
                    text: `${bulkLowStockQueue.length} selected item(s) remaining.`,
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: `Next: ${nextItem.name}`,
                    cancelButtonText: 'Stop'
                });
                if (continueResult.isConfirmed) {
                    openOrderModal();
                    prefillOrderFromLowStock(nextItem);
                } else {
                    bulkLowStockQueue = [];
                }
            }
        }
    }

    function buildCurrentFormPayload() {
        return {
            action: 'create',
            requisition_id: document.getElementById('requisitionId').value || null,
            supplier_id: document.getElementById('supplierId').value,
            item_name: document.getElementById('itemName').value.trim(),
            ingredient_id: document.getElementById('ingredientId').value || null,
            quantity: document.getElementById('quantity').value,
            unit: document.getElementById('unit').value.trim(),
            unit_price: document.getElementById('unitPrice').value || 0,
            expected_delivery_date: document.getElementById('expectedDeliveryDate').value || null,
            notes: document.getElementById('notes').value.trim()
        };
    }

    async function createSinglePO(payload) {
        const response = await fetch('../backend/purchase_orders_api.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(payload)
        });
        return await response.json();
    }

    function handleRequisitionMode() {
        const requisitionId = document.getElementById('requisitionId').value;
        const batchSection = document.getElementById('manualBatchSection');
        batchSection.style.display = requisitionId ? 'none' : 'block';
        updateFormRequiredState();
    }

    function addCurrentItemToBatch() {
        const requisitionId = document.getElementById('requisitionId').value;
        if (requisitionId) {
            Swal.fire('Info', 'Batch add is available for Manual PO mode only', 'info');
            return;
        }

        const supplierId = Number(document.getElementById('supplierId').value || 0);
        const supplierName = suppliers.find(s => Number(s.id) === supplierId)?.name || document.getElementById('supplierId').selectedOptions[0]?.text || 'Supplier';
        const itemName = document.getElementById('itemName').value.trim();
        const ingredientId = document.getElementById('ingredientId').value || null;
        const qty = Number(document.getElementById('quantity').value || 0);
        const unit = document.getElementById('unit').value.trim();
        const unitPrice = Number(document.getElementById('unitPrice').value || 0);
        const eta = document.getElementById('expectedDeliveryDate').value || null;
        const notes = document.getElementById('notes').value.trim();

        if (!supplierId || !itemName || qty <= 0 || !unit) {
            Swal.fire('Error', 'Supplier, item, quantity and unit are required to add batch item', 'error');
            return;
        }

        manualBatchItems.push({
            supplier_id: supplierId,
            supplier_name: supplierName,
            item_name: itemName,
            ingredient_id: ingredientId,
            quantity: qty,
            unit,
            unit_price: unitPrice,
            expected_delivery_date: eta,
            notes
        });

        renderManualBatch();
        document.getElementById('itemName').value = '';
        document.getElementById('ingredientId').value = '';
        document.getElementById('quantity').value = '';
        document.getElementById('unit').value = '';
        document.getElementById('unitPrice').value = '';
        updateFormRequiredState();
    }

    function removeBatchItem(index) {
        manualBatchItems.splice(index, 1);
        renderManualBatch();
        updateFormRequiredState();
    }

    function renderManualBatch() {
        const tbody = document.getElementById('manualBatchBody');
        if (!manualBatchItems.length) {
            tbody.innerHTML = '<tr><td colspan="6" class="empty-state">No items added yet.</td></tr>';
            return;
        }
        tbody.innerHTML = manualBatchItems.map((item, idx) => `
            <tr>
                <td>${escapeHtml(item.supplier_name || '')}</td>
                <td>${escapeHtml(item.item_name || '')}</td>
                <td>${Number(item.quantity || 0).toFixed(3).replace(/\.?0+$/, '')}</td>
                <td>${escapeHtml(item.unit || '')}</td>
                <td>₹${Number(item.unit_price || 0).toFixed(2)}</td>
                <td><button type="button" class="action-btn delete" onclick="removeBatchItem(${idx})"><i class="fas fa-trash"></i></button></td>
            </tr>
        `).join('');
        updateFormRequiredState();
    }

    function updateFormRequiredState() {
        const requisitionId = document.getElementById('requisitionId').value;
        const isManualWithBatch = !requisitionId && manualBatchItems.length > 0;

        const supplierField = document.getElementById('supplierId');
        const itemField = document.getElementById('itemName');
        const quantityField = document.getElementById('quantity');
        const unitField = document.getElementById('unit');

        if (isManualWithBatch) {
            supplierField.removeAttribute('required');
            itemField.removeAttribute('required');
            quantityField.removeAttribute('required');
            unitField.removeAttribute('required');
        } else {
            supplierField.setAttribute('required', 'required');
            itemField.setAttribute('required', 'required');
            quantityField.setAttribute('required', 'required');
            unitField.setAttribute('required', 'required');
        }
    }

    async function startBulkLowStockPurchase() {
        try {
            const response = await fetch('../backend/admin_ingredients_api.php?action=get_low_stock');
            const data = await response.json();
            const items = (data.success && data.data?.items) ? data.data.items : [];

            if (!items.length) {
                Swal.fire('No Low Stock Items', 'All ingredients are sufficiently stocked.', 'info');
                return;
            }

            const rows = items.map((item, idx) => {
                const qty = Math.max(0, Number(item.shortage_amount || 0));
                return `
                    <div style="display:grid; grid-template-columns: 24px 1fr 140px; gap:10px; align-items:center; margin:8px 0;">
                        <input type="checkbox" id="ls-check-${idx}" checked>
                        <label for="ls-check-${idx}" style="text-align:left;">
                            <strong>${escapeHtml(item.name)}</strong>
                            <div style="font-size:12px; color:#6b7280;">Current: ${Number(item.current_stock).toFixed(2)} ${escapeHtml(item.unit || '')} | Min: ${Number(item.minimum_stock).toFixed(2)}</div>
                        </label>
                        <input id="ls-qty-${idx}" type="number" min="0.001" step="0.001" value="${qty.toFixed(3)}" style="padding:6px 8px;">
                    </div>
                `;
            }).join('');

            const result = await Swal.fire({
                title: 'Select Low Stock Items',
                html: `<div style="max-height:320px; overflow-y:auto;">${rows}</div>`,
                width: 760,
                showCancelButton: true,
                confirmButtonText: 'Use Selected',
                cancelButtonText: 'Cancel',
                preConfirm: () => {
                    const selected = [];
                    items.forEach((item, idx) => {
                        const checked = document.getElementById(`ls-check-${idx}`)?.checked;
                        const qtyVal = Number(document.getElementById(`ls-qty-${idx}`)?.value || 0);
                        if (checked && qtyVal > 0) {
                            selected.push({
                                id: Number(item.id),
                                name: item.name,
                                unit: item.unit || '',
                                quantity: qtyVal
                            });
                        }
                    });
                    if (!selected.length) {
                        Swal.showValidationMessage('Select at least one item with valid quantity');
                        return false;
                    }
                    return selected;
                }
            });

            if (!result.isConfirmed) return;

            bulkLowStockQueue = result.value || [];
            openOrderModal();
            prefillOrderFromLowStock(bulkLowStockQueue[0]);
        } catch (error) {
            Swal.fire('Error', 'Failed to load low stock items for bulk PO', 'error');
        }
    }

    function prefillOrderFromLowStock(item) {
        if (!item) return;
        document.getElementById('itemName').value = item.name || '';
        const ingredientSelect = document.getElementById('ingredientId');
        const ingredientValue = String(item.id || '');
        if (ingredientValue && !Array.from(ingredientSelect.options).some(opt => opt.value === ingredientValue)) {
            ingredientSelect.innerHTML += `<option value="${ingredientValue}" data-name="${escapeHtmlAttr(item.name || '')}" data-unit="${escapeHtmlAttr(item.unit || '')}">${escapeHtml(item.name || '')} (${escapeHtml(item.unit || '')})</option>`;
        }
        ingredientSelect.value = ingredientValue;
        document.getElementById('quantity').value = Number(item.quantity || 0).toFixed(3).replace(/\.?0+$/, '');
        document.getElementById('unit').value = item.unit || '';
        const notes = document.getElementById('notes').value.trim();
        if (!notes) {
            document.getElementById('notes').value = 'Auto-filled from low stock selection';
        }
        ingredientSelect.dispatchEvent(new Event('change'));
    }

    async function updateStatus(id, status) {
        const response = await fetch('../backend/purchase_orders_api.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({action: 'update_status', id, status})
        });
        const data = await response.json();
        if (!data.success) {
            Swal.fire('Error', data.message, 'error');
            return;
        }
        loadOrders();
    }

    async function receiveStock(id, orderedQty, receivedQty) {
        const remaining = Math.max(0, orderedQty - receivedQty);
        const {value: formValues} = await Swal.fire({
            title: 'Receive Stock',
            html: `
                <div style="text-align:left;">
                    <label>Remaining Quantity: <strong>${remaining.toFixed(3).replace(/\.?0+$/, '')}</strong></label>
                    <input id="swal-receive-qty" class="swal2-input" type="number" min="0.001" step="0.001" placeholder="Received quantity">
                    <input id="swal-invoice" class="swal2-input" placeholder="Invoice number (optional)">
                    <input id="swal-notes" class="swal2-input" placeholder="Notes (optional)">
                </div>
            `,
            focusConfirm: false,
            showCancelButton: true,
            preConfirm: () => {
                const qty = Number(document.getElementById('swal-receive-qty').value || 0);
                const invoice = document.getElementById('swal-invoice').value || '';
                const notes = document.getElementById('swal-notes').value || '';
                if (!qty || qty <= 0) {
                    Swal.showValidationMessage('Received quantity is required');
                    return false;
                }
                return {qty, invoice, notes};
            }
        });

        if (!formValues) return;

        const response = await fetch('../backend/purchase_orders_api.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                action: 'receive_stock',
                id,
                received_quantity: formValues.qty,
                invoice_number: formValues.invoice,
                notes: formValues.notes
            })
        });
        const data = await response.json();
        if (!data.success) {
            Swal.fire('Error', data.message, 'error');
            return;
        }
        Swal.fire('Updated', 'Stock received and inventory updated', 'success');
        loadOrders();
    }

    function escapeHtml(value) {
        return String(value ?? '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function escapeHtmlAttr(value) {
        return escapeHtml(value).replace(/"/g, '&quot;');
    }

    document.getElementById('requisitionId').addEventListener('change', function() {
        const option = this.options[this.selectedIndex];
        handleRequisitionMode();
        if (!option || !option.dataset) return;
        if (option.dataset.item) document.getElementById('itemName').value = option.dataset.item;
        if (option.dataset.unit) document.getElementById('unit').value = option.dataset.unit;
        if (option.dataset.qty) document.getElementById('quantity').value = option.dataset.qty;
        if (option.dataset.ingredient) {
            const ingredientSelect = document.getElementById('ingredientId');
            const ingredientValue = String(option.dataset.ingredient);
            if (ingredientValue && !Array.from(ingredientSelect.options).some(opt => opt.value === ingredientValue)) {
                ingredientSelect.innerHTML += `<option value="${ingredientValue}" data-name="${escapeHtmlAttr(option.dataset.item || '')}" data-unit="${escapeHtmlAttr(option.dataset.unit || '')}">${escapeHtml(option.dataset.item || 'Requisition Ingredient')}</option>`;
            }
            ingredientSelect.value = ingredientValue;
            ingredientSelect.dispatchEvent(new Event('change'));
        }
    });
    document.getElementById('ingredientId').addEventListener('change', onIngredientChange);

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

    // 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', async () => {
        await checkSession();
        await loadSuppliers();
        await loadIngredientsForManual();
        await loadApprovedRequisitions();
        await loadOrders();
        await updateNewIngredientsBadge();
        setInterval(updateNewIngredientsBadge, 30000);

        const qs = new URLSearchParams(window.location.search);
        const requisitionId = qs.get('requisition_id');
        const ingredientId = qs.get('ingredient_id');
        if (requisitionId) {
            openOrderModal();
            document.getElementById('requisitionId').value = requisitionId;
            document.getElementById('requisitionId').dispatchEvent(new Event('change'));
        } else if (ingredientId) {
            openOrderModal();
            const ingredientSelect = document.getElementById('ingredientId');
            if (Array.from(ingredientSelect.options).some(opt => opt.value === ingredientId)) {
                ingredientSelect.value = ingredientId;
                ingredientSelect.dispatchEvent(new Event('change'));
            }
        }
    });
</script>

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