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

<div class="dashboard-container">
    <div class="main-content">
    <div class="page-header">
        <div class="page-header-content">
            <h1>Stock Receiving</h1>
            <p>Log and track received inventory</p>
        </div>
        <div class="page-actions">
            <button class="btn btn-primary" onclick="openReceiveModal()">
                <i class="fas fa-box-open"></i> New Receipt
            </button>
        </div>
    </div>

    <!-- PENDING SHIPMENTS SECTION -->
    <div class="card" style="margin-bottom: 20px; border-left: 4px solid #f59e0b;">
        <div class="card-header" style="background: #fffbeb;">
            <h2><i class="fas fa-truck"></i> Pending Shipments from Purchase Orders</h2>
            <p style="margin: 0; font-size: 0.9em; color: #666; margin-top: 5px;">Orders marked as shipped by Purchase Manager. Click to receive them.</p>
        </div>
        <div class="card-body">
            <div id="pendingShipmentsContainer" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); gap: 15px;">
                <div style="text-align: center; padding: 20px; color: #999;">
                    <i class="fas fa-spinner fa-spin"></i> Loading pending shipments...
                </div>
            </div>
        </div>
    </div>

    <!-- SEARCH & FILTER -->
    <div class="card" style="margin-bottom: 20px;">
        <div class="card-body">
            <div class="form-row">
                <div class="form-group">
                    <label for="filterDate">Filter by Date</label>
                    <input type="date" id="filterDate" onchange="loadReceivingHistory()">
                </div>
                <div class="form-group">
                    <label for="filterIngredient">Filter by Ingredient</label>
                    <input type="text" id="filterIngredient" placeholder="Search ingredient..." onkeyup="filterTable()">
                </div>
                <div class="form-group" style="display: flex; align-items: flex-end;">
                    <button class="btn btn-secondary" onclick="clearFilters()"><i class="fas fa-redo"></i> Clear</button>
                </div>
            </div>
        </div>
    </div>

    <!-- RECEIVING HISTORY TABLE -->
    <div class="card">
        <div class="card-header">
            <h2><i class="fas fa-list"></i> Receiving History</h2>
        </div>
        <div class="card-body">
            <table class="table" id="receivingTable">
                <thead>
                    <tr>
                        <th>Date & Time</th>
                        <th>Ingredient</th>
                        <th>Ordered</th>
                        <th>Quantity</th>
                        <th>Remaining</th>
                        <th>Supplier</th>
                        <th>Invoice #</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="receivingList">
                    <tr>
                        <td colspan="9" style="text-align: center; padding: 30px;">
                            <i class="fas fa-spinner fa-spin"></i> Loading...
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- RECEIVE STOCK MODAL -->
<div id="receiveModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2><i class="fas fa-box-open"></i> Receive Stock</h2>
            <button class="modal-close" onclick="closeReceiveModal()">&times;</button>
        </div>
        <div class="modal-body">
            <form id="receiveForm">
                <!-- PO LINK INDICATOR -->
                <div id="poLinkInfo" style="display: none; padding: 12px; margin-bottom: 15px; background: #e0f2fe; border-left: 4px solid #0ea5e9; border-radius: 4px; color: #0369a1;">
                    <strong>Linked to Purchase Order:</strong>
                    <div style="font-size: 0.9em; margin-top: 5px;">
                        PO <span id="linkedPoNumber"></span> - 
                        <span id="linkedPoSupplier"></span>
                        <br>
                        Ordered: <span id="linkedPoQuantity"></span> <span id="linkedPoUnit"></span>
                        | Already Received: <span id="linkedPoReceived"></span>
                        | Remaining: <span id="linkedPoRemaining"></span>
                    </div>
                </div>

                <input type="hidden" id="poId">
                
                <div class="form-group">
                    <label for="ingredientSelect">Ingredient *</label>
                    <select id="ingredientSelect" required onchange="onIngredientSelect()">
                        <option value="">Select an ingredient...</option>
                    </select>
                </div>

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

                <div class="form-group">
                    <label for="unitReceived">Unit</label>
                    <input type="text" id="unitReceived" readonly placeholder="Unit will auto-fill">
                </div>

                <div class="form-group">
                    <label for="supplierName">Supplier Name</label>
                    <input type="text" id="supplierName" placeholder="Enter supplier name">
                </div>

                <div class="form-group">
                    <label for="invoiceNumber">Invoice Number</label>
                    <input type="text" id="invoiceNumber" placeholder="Enter invoice number">
                </div>

                <div class="form-group">
                    <label for="receivedDate">Date Received *</label>
                    <input type="date" id="receivedDate" required>
                </div>

                <div class="form-group">
                    <label for="receivedTime">Time Received</label>
                    <input type="time" id="receivedTime">
                </div>

                <div class="form-group">
                    <label for="expiryDate">Expiry Date</label>
                    <input type="date" id="expiryDate" placeholder="Batch expiry date">
                </div>

                <div class="form-group">
                    <label for="batchNumber">Batch Number</label>
                    <input type="text" id="batchNumber" placeholder="Batch/Lot number">
                </div>

                <div class="form-group">
                    <label for="receiveNotes">Notes</label>
                    <textarea id="receiveNotes" placeholder="Any additional notes..."></textarea>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeReceiveModal()">Cancel</button>
            <button class="btn btn-primary" onclick="submitReceiveForm()">
                <i class="fas fa-check"></i> Confirm Receipt
            </button>
        </div>
    </div>
</div>

<!-- VIEW RECEIPT MODAL -->
<div id="viewModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2><i class="fas fa-receipt"></i> Receipt Details</h2>
            <button class="modal-close" onclick="closeViewModal()">&times;</button>
        </div>
        <div class="modal-body" id="viewModalBody">
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeViewModal()">Close</button>
        </div>
    </div>
</div>
</div>
</div>

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

<script>
    let remainingPromptShown = false;

    // Set today's date on load
    document.addEventListener('DOMContentLoaded', () => {
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('receivedDate').value = today;
        loadReceivingHistory();
        loadIngredientsList();
        loadPendingShipments();
    });

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

    function onIngredientSelect() {
        const select = document.getElementById('ingredientSelect');
        const option = select.options[select.selectedIndex];
        const iisPerishable = option.dataset.perishable === '1';
        const lastReceived = option.dataset['lastReceived'];
        
        document.getElementById('unitReceived').value = option.dataset.unit || '';
        
        const expiryField = document.getElementById('expiryDate');
        const label = expiryField.previousElementSibling;
        
        if (iisPerishable) {
            expiryField.required = true;
            expiryField.style.borderColor = '#f59e0b';
            expiryField.style.backgroundColor = '#fffbeb';
            label.innerHTML = 'Expiry Date <span style="color: #ef4444; font-weight: bold;">*</span> <span style="font-size: 0.85em; color: #d97706;">(Required for Perishables)</span>';
            label.style.fontWeight = '600';
        } else {
            expiryField.required = false;
            expiryField.style.borderColor = '';
            expiryField.style.backgroundColor = '';
            label.innerHTML = 'Expiry Date';
            label.style.fontWeight = 'normal';
        }
        
        // Pre-fill with last received date if available
        if (lastReceived) {
            expiryField.placeholder = `Last received: ${lastReceived}`;
        }
    }

    function openReceiveModal() {
        document.getElementById('receiveForm').reset();
        document.getElementById('poId').value = '';
        document.getElementById('poLinkInfo').style.display = 'none';
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('receivedDate').value = today;
        const now = new Date().toTimeString().slice(0, 5);
        document.getElementById('receivedTime').value = now;
        document.getElementById('receiveModal').classList.add('active');
    }

    function closeReceiveModal() {
        document.getElementById('receiveModal').classList.remove('active');
    }

    async function submitReceiveForm() {
        const ingredientId = document.getElementById('ingredientSelect').value;
        const quantityReceived = document.getElementById('quantityReceived').value;
        const expiryDate = document.getElementById('expiryDate').value;
        const receivedDate = document.getElementById('receivedDate').value;
        const select = document.getElementById('ingredientSelect');
        const option = select.options[select.selectedIndex];
        const isPerishable = option.dataset.perishable === '1';
        
        // Validate required fields
        if (!ingredientId || !quantityReceived) {
            Swal.fire('Error', 'Please fill required fields', 'error');
            return;
        }
        
        // Validate expiry date for perishables
        if (isPerishable && !expiryDate) {
            Swal.fire('Error', 'Expiry date is required for perishable items', 'error');
            document.getElementById('expiryDate').focus();
            return;
        }
        
        // Check if item is already expired
        if (expiryDate && receivedDate > expiryDate) {
            const result = await Swal.fire({
                title: 'Entered Expiry Date Is Already Past',
                html: `<p>Received Date: <strong>${receivedDate}</strong></p>
                       <p>Expiry Date: <strong>${expiryDate}</strong></p>
                       <p>This batch is marked as expired.</p>
                       <p style="margin-top: 8px; color: #6b7280;">To restock in normal state, edit expiry date to a future date.</p>`,
                icon: 'warning',
                showDenyButton: true,
                showCancelButton: true,
                confirmButtonText: 'Log as Wastage',
                denyButtonText: 'Receive Anyway',
                cancelButtonText: 'Edit Date'
            });

            if (result.isConfirmed) {
                // Auto-log as wastage instead
                await logExpiredAsWastage(ingredientId, quantityReceived, expiryDate, receivedDate);
                return;
            }

            if (!result.isDenied) {
                return;
            }
        }

        // Warning for items expiring within 3 days
        if (expiryDate) {
            const expDate = new Date(expiryDate);
            const recDate = new Date(receivedDate);
            const daysUntilExpiry = Math.floor((expDate - recDate) / (1000 * 60 * 60 * 24));
            
            if (daysUntilExpiry >= 0 && daysUntilExpiry <= 3) {
                const showWarning = await Swal.fire({
                    title: '⏰ Quick Expiry Warning',
                    html: `<p>This item will expire in <strong>${daysUntilExpiry} days</strong> on <strong>${expiryDate}</strong>.</p><p>Continue receiving?</p>`,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Continue',
                    cancelButtonText: 'Cancel'
                });
                
                if (!showWarning.isConfirmed) {
                    return;
                }
            }
        }

        try {
            const poId = document.getElementById('poId').value;
            const response = await fetch('../backend/store_keeper_api.php?action=add_stock_receiving', {
                method: 'POST',
                credentials: 'include',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    ingredient_id: ingredientId,
                    quantity_received: quantityReceived,
                    supplier_name: document.getElementById('supplierName').value,
                    invoice_number: document.getElementById('invoiceNumber').value,
                    received_date: document.getElementById('receivedDate').value,
                    received_time: document.getElementById('receivedTime').value,
                    expiry_date: expiryDate,
                    batch_number: document.getElementById('batchNumber').value,
                    notes: document.getElementById('receiveNotes').value,
                    po_id: poId ? parseInt(poId) : null
                })
            });

            if (!response.ok) {
                throw new Error('HTTP ' + response.status + ': Failed to receive stock');
            }

            const data = await response.json();
            
            if (data.success) {
                Swal.fire('Success', 'Stock received and logged successfully!', 'success');
                closeReceiveModal();
                loadReceivingHistory();
                loadPendingShipments();
            } else {
                Swal.fire('Error', data.message || 'Failed to receive stock', 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            Swal.fire('Error', 'An error occurred', 'error');
        }
    }

    async function logExpiredAsWastage(ingredientId, quantity, expiryDate, wastageDate) {
        try {
            const response = await fetch('../backend/store_keeper_api.php?action=log_wastage', {
                method: 'POST',
                credentials: 'include',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    ingredient_id: ingredientId,
                    type: 'expiry',
                    quantity: quantity,
                    wastage_date: wastageDate,
                    reason: 'Received already expired stock',
                    expiry_date: expiryDate,
                    batch_number: document.getElementById('batchNumber').value || null,
                    cost_impact: 0,
                    notes: 'Automatically logged - received expired item'
                })
            });

            if (!response.ok) {
                throw new Error('HTTP ' + response.status + ': Failed to log wastage');
            }

            const data = await response.json();
            
            if (data.success) {
                Swal.fire('Logged as Wastage', 'The expired item has been marked as wastage and will not be added to inventory.', 'success');
                closeReceiveModal();
                loadReceivingHistory();
                loadPendingShipments();
            } else {
                Swal.fire('Error', data.message || 'Failed to log wastage', 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            Swal.fire('Error', 'An error occurred while logging wastage', 'error');
        }
    }

    async function loadReceivingHistory() {
        try {
            const filterDate = document.getElementById('filterDate').value;
            const url = filterDate ? 
                `../backend/store_keeper_api.php?action=get_stock_receiving&date=${filterDate}` :
                '../backend/store_keeper_api.php?action=get_stock_receiving';
            
            const response = await fetch(url);
            const rawText = await response.text();
            let data;
            try {
                data = JSON.parse(rawText);
            } catch (parseError) {
                throw new Error(`Invalid JSON response (HTTP ${response.status})`);
            }

            if (!response.ok) {
                throw new Error(data?.message || `Request failed with status ${response.status}`);
            }
            
            const tbody = document.getElementById('receivingList');
            
            if (data.success && data.data && data.data.length > 0) {
                const displayRows = [];
                const poRows = new Map();

                data.data.forEach((receipt) => {
                    const qty = parseFloat(receipt.quantity_received || 0);

                    if (receipt.po_id) {
                        const poKey = String(receipt.po_id);
                        if (!poRows.has(poKey)) {
                            const row = {
                                ...receipt,
                                display_quantity: qty,
                                receipt_count: 1
                            };
                            poRows.set(poKey, row);
                            displayRows.push(row);
                        } else {
                            const row = poRows.get(poKey);
                            row.display_quantity += qty;
                            row.receipt_count += 1;
                            if ((!row.invoice_number || row.invoice_number === '-') && receipt.invoice_number) {
                                row.invoice_number = receipt.invoice_number;
                            }
                        }
                    } else {
                        displayRows.push({
                            ...receipt,
                            display_quantity: qty,
                            receipt_count: 1
                        });
                    }
                });

                tbody.innerHTML = displayRows.map(receipt => `
                    <tr>
                        <td>${new Date(receipt.created_at).toLocaleString()}</td>
                        <td><strong>${receipt.ingredient_name}</strong></td>
                        <td>${receipt.po_quantity ? `${parseFloat(receipt.po_quantity).toFixed(2)} ${receipt.unit}` : '-'}</td>
                        <td>${parseFloat(receipt.display_quantity || 0).toFixed(2)} ${receipt.unit}</td>
                        <td>${receipt.po_quantity ? `${parseFloat(receipt.remaining_after_receipt || 0).toFixed(2)} ${receipt.unit}` : '-'}</td>
                        <td>${receipt.supplier_name || '-'}</td>
                        <td>${receipt.invoice_number || '-'}</td>
                        <td><span class="badge success">${receipt.po_quantity && parseFloat(receipt.remaining_after_receipt || 0) > 0 ? 'Partially Received' : 'Received'}</span></td>
                        <td>
                            ${(() => {
                                const remainingQty = parseFloat(receipt.current_po_remaining || 0);
                                const poStatus = String(receipt.po_status || '').toLowerCase();
                                if (receipt.po_id && remainingQty > 0 && poStatus !== 'cancelled') {
                                    return `
                                        <button class="btn btn-sm btn-primary" style="margin-right: 6px;" onclick="receiveRemainingFromHistory(${receipt.po_id})">
                                            <i class="fas fa-box-open"></i> Receive Remaining
                                        </button>
                                        <button class="btn btn-sm btn-secondary" style="margin-right: 6px;" onclick="shortClosePO(${receipt.po_id})">
                                            <i class="fas fa-ban"></i> Short Close
                                        </button>
                                    `;
                                }
                                return '';
                            })()}
                            <button class="btn btn-sm btn-info" onclick="viewReceipt(${receipt.id})">
                                <i class="fas fa-eye"></i> View
                            </button>
                        </td>
                    </tr>
                `).join('');

                if (!remainingPromptShown) {
                    const firstWithRemaining = displayRows.find(r => r.po_id && parseFloat(r.remaining_after_receipt || 0) > 0);
                    if (firstWithRemaining) {
                        remainingPromptShown = true;
                        const remainingQty = parseFloat(firstWithRemaining.remaining_after_receipt || 0).toFixed(2);
                        Swal.fire({
                            title: 'Remaining Quantity Pending',
                            text: `${firstWithRemaining.ingredient_name}: ${remainingQty} ${firstWithRemaining.unit} still needs to be received. Open receive popup now?`,
                            icon: 'info',
                            showCancelButton: true,
                            confirmButtonText: 'Open Receive Popup'
                        }).then((result) => {
                            if (result.isConfirmed) {
                                receiveRemainingFromHistory(firstWithRemaining.po_id);
                            }
                        });
                    }
                }
            } else {
                tbody.innerHTML = '<tr><td colspan="9" style="text-align: center; padding: 30px; color: var(--text-secondary);">No receiving records found</td></tr>';
            }
        } catch (error) {
            console.error('Error loading history:', error);
            document.getElementById('receivingList').innerHTML = '<tr><td colspan="9" class="alert alert-danger">Error loading history</td></tr>';
        }
    }

    async function viewReceipt(id) {
        try {
            const response = await fetch(`../backend/store_keeper_api.php?action=get_receipt&id=${id}`, {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                throw new Error('HTTP ' + response.status + ': Failed to fetch receipt');
            }
            
            const data = await response.json();
            
            if (data.success && data.data) {
                const receipt = data.data;
                document.getElementById('viewModalBody').innerHTML = `
                    <div style="padding: 20px;">
                        <p><strong>Ingredient:</strong> ${receipt.ingredient_name}</p>
                        <p><strong>Quantity:</strong> ${parseFloat(receipt.quantity_received).toFixed(2)} ${receipt.unit}</p>
                        <p><strong>Supplier:</strong> ${receipt.supplier_name || '-'}</p>
                        <p><strong>Invoice:</strong> ${receipt.invoice_number || '-'}</p>
                        <p><strong>Date Received:</strong> ${new Date(receipt.created_at).toLocaleString()}</p>
                        <p><strong>Batch Number:</strong> ${receipt.batch_number || '-'}</p>
                        <p><strong>Expiry Date:</strong> ${receipt.expiry_date || '-'}</p>
                        <p><strong>Notes:</strong> ${receipt.notes || '-'}</p>
                    </div>
                `;
                document.getElementById('viewModal').classList.add('active');
            }
        } catch (error) {
            console.error('Error viewing receipt:', error);
            Swal.fire('Error', 'Failed to load receipt', 'error');
        }
    }

    function closeViewModal() {
        document.getElementById('viewModal').classList.remove('active');
    }

    function filterTable() {
        const input = document.getElementById('filterIngredient');
        const table = document.getElementById('receivingTable');
        const rows = table.getElementsByTagName('tr');
        
        for (let i = 1; i < rows.length; i++) {
            const text = rows[i].textContent.toLowerCase();
            rows[i].style.display = text.includes(input.value.toLowerCase()) ? '' : 'none';
        }
    }

    function clearFilters() {
        document.getElementById('filterDate').value = '';
        document.getElementById('filterIngredient').value = '';
        loadReceivingHistory();
    }

    async function receiveRemainingFromHistory(poId) {
        try {
            const response = await fetch(`../backend/store_keeper_api.php?action=get_po_for_receiving&po_id=${poId}`);
            const rawText = await response.text();
            let data;
            try {
                data = JSON.parse(rawText);
            } catch (parseError) {
                throw new Error(`Invalid JSON response (HTTP ${response.status})`);
            }

            if (!response.ok || !data.success) {
                throw new Error(data?.message || `Request failed with status ${response.status}`);
            }

            const po = data.data;
            const remainingQty = Math.max(0, parseFloat(po.remaining_quantity || 0));
            if (remainingQty <= 0) {
                Swal.fire('Info', 'No remaining quantity left for this PO.', 'info');
                loadReceivingHistory();
                loadPendingShipments();
                return;
            }
            if (String(po.status || '').toLowerCase() === 'cancelled') {
                Swal.fire('Info', 'This PO is cancelled. Create a new PO for additional quantity.', 'info');
                return;
            }

            openReceiveFromPO(
                po.po_id,
                po.ingredient_id,
                po.item_name,
                po.quantity,
                po.unit,
                po.supplier_name || '',
                po.received_quantity || 0,
                po.invoice_number || '',
                po.po_last_expiry_date || ''
            );
        } catch (error) {
            console.error('Error opening remaining receive popup:', error);
            Swal.fire('Error', error.message || 'Failed to load pending shipment details', 'error');
        }
    }

    async function shortClosePO(poId) {
        try {
            const pendingResponse = await fetch('../backend/store_keeper_api.php?action=get_pending_shipments', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (!pendingResponse.ok) {
                throw new Error('HTTP ' + pendingResponse.status + ': Failed to fetch shipments');
            }
            
            const pendingText = await pendingResponse.text();
            let pendingData;
            try {
                pendingData = JSON.parse(pendingText);
            } catch (parseError) {
                throw new Error(`Invalid JSON response (HTTP ${pendingResponse.status})`);
            }

            if (!pendingResponse.ok || !pendingData.success) {
                throw new Error(pendingData?.message || `Request failed with status ${pendingResponse.status}`);
            }

            const shipment = (pendingData.data || []).find(s => Number(s.po_id) === Number(poId));
            if (!shipment) {
                Swal.fire('Info', 'This PO is no longer pending.', 'info');
                loadPendingShipments();
                loadReceivingHistory();
                return;
            }

            const ordered = parseFloat(shipment.quantity || 0);
            const received = parseFloat(shipment.received_quantity || 0);
            const remaining = Math.max(0, ordered - received);

            const result = await Swal.fire({
                title: 'Short Close Remaining Quantity',
                html: `
                    <div style="text-align:left;">
                        <p style="margin: 0 0 8px 0;"><strong>PO:</strong> ${shipment.po_number || shipment.po_id}</p>
                        <p style="margin: 0 0 8px 0;"><strong>Item:</strong> ${shipment.item_name}</p>
                        <p style="margin: 0 0 12px 0;"><strong>Remaining:</strong> ${remaining.toFixed(2)} ${shipment.unit || ''}</p>
                        <textarea id="shortCloseReason" class="swal2-textarea" placeholder="Reason for closing remaining quantity" style="margin:0;"></textarea>
                    </div>
                `,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Close Remaining',
                preConfirm: () => {
                    const reason = (document.getElementById('shortCloseReason')?.value || '').trim();
                    if (!reason) {
                        Swal.showValidationMessage('Reason is required');
                        return false;
                    }
                    return { reason };
                }
            });

            if (!result.isConfirmed) {
                return;
            }

            const closeResponse = await fetch('../backend/store_keeper_api.php?action=close_remaining_shipment', {
                method: 'POST',
                credentials: 'include',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    po_id: poId,
                    reason: result.value.reason
                })
            });

            if (!closeResponse.ok) {
                throw new Error('HTTP ' + closeResponse.status + ': Failed to close shipment');
            }

            const closeText = await closeResponse.text();
            let closeData;
            try {
                closeData = JSON.parse(closeText);
            } catch (parseError) {
                throw new Error(`Invalid JSON response (HTTP ${closeResponse.status})`);
            }

            if (!closeResponse.ok || !closeData.success) {
                throw new Error(closeData?.message || `Request failed with status ${closeResponse.status}`);
            }

            Swal.fire('Closed', 'Remaining quantity has been short closed.', 'success');
            loadPendingShipments();
            loadReceivingHistory();
        } catch (error) {
            console.error('Error short closing PO:', error);
            Swal.fire('Error', error.message || 'Failed to close remaining quantity', 'error');
        }
    }

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

    // PENDING SHIPMENTS FUNCTIONALITY
    async function loadPendingShipments() {
        try {
            const response = await fetch('../backend/store_keeper_api.php?action=get_pending_shipments', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                throw new Error('HTTP ' + response.status + ': Failed to fetch shipments');
            }
            
            const rawText = await response.text();
            let data;
            try {
                data = JSON.parse(rawText);
            } catch (parseError) {
                throw new Error(`Invalid JSON response (HTTP ${response.status})`);
            }

            const container = document.getElementById('pendingShipmentsContainer');

            if (data.success && data.data && data.data.length > 0) {
                container.innerHTML = data.data.map(shipment => {
                    const remaining = shipment.quantity - shipment.received_quantity;
                    const progress = (shipment.received_quantity / shipment.quantity) * 100;
                    return `
                        <div class="shipment-card" style="
                            border: 1px solid #e5e7eb;
                            border-radius: 8px;
                            padding: 15px;
                            background: white;
                            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
                            cursor: pointer;
                            transition: all 0.3s;
                        " onclick="openReceiveFromPO(${shipment.po_id}, ${shipment.ingredient_id}, '${shipment.item_name}', ${shipment.quantity}, '${shipment.unit}', '${shipment.supplier_name || ''}', ${shipment.received_quantity}, '${shipment.invoice_number || ''}', '${shipment.po_last_expiry_date || ''}')">
                            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 10px;">
                                <div>
                                    <h3 style="margin: 0 0 5px 0; color: #1f2937; font-size: 1.1em;">${shipment.item_name}</h3>
                                    <p style="margin: 0; color: #666; font-size: 0.9em;">
                                        <i class="fas fa-truck"></i> ${shipment.supplier_name || 'Unknown Supplier'}
                                    </p>
                                </div>
                                <span style="background: #dbeafe; color: #1e40af; padding: 4px 8px; border-radius: 4px; font-size: 0.85em; font-weight: bold;">
                                    PO #${shipment.po_number || shipment.po_id}
                                </span>
                            </div>
                            
                            <div style="margin-bottom: 10px;">
                                <div style="display: flex; justify-content: space-between; margin-bottom: 5px; font-size: 0.9em;">
                                    <span>Order: ${parseFloat(shipment.quantity).toFixed(2)} ${shipment.unit}</span>
                                    <span>Remaining: ${parseFloat(remaining).toFixed(2)}</span>
                                </div>
                                <div style="background: #e5e7eb; height: 6px; border-radius: 3px; overflow: hidden;">
                                    <div style="background: #10b981; height: 100%; width: ${progress}%;" title="${progress.toFixed(0)}% received"></div>
                                </div>
                                <div style="font-size: 0.8em; color: #666; margin-top: 3px;">
                                    Received: ${parseFloat(shipment.received_quantity).toFixed(2)} ${shipment.unit}
                                </div>
                            </div>

                            <div style="display: flex; gap: 8px; margin-top: 10px;">
                                <button class="btn btn-sm btn-primary" onclick="event.stopPropagation(); openReceiveFromPO(${shipment.po_id}, ${shipment.ingredient_id}, '${shipment.item_name}', ${shipment.quantity}, '${shipment.unit}', '${shipment.supplier_name || ''}', ${shipment.received_quantity}, '${shipment.invoice_number || ''}', '${shipment.po_last_expiry_date || ''}')">
                                    <i class="fas fa-box-open"></i> Receive
                                </button>
                                <button class="btn btn-sm btn-secondary" onclick="event.stopPropagation(); shortClosePO(${shipment.po_id})">
                                    <i class="fas fa-ban"></i> Short Close
                                </button>
                            </div>

                            ${shipment.expected_delivery_date ? `
                                <div style="font-size: 0.85em; color: #666; padding-top: 10px; border-top: 1px solid #e5e7eb;">
                                    <i class="fas fa-calendar"></i> Expected: ${new Date(shipment.expected_delivery_date).toLocaleDateString()}
                                </div>
                            ` : ''}
                        </div>
                    `;
                }).join('');
            } else {
                container.innerHTML = `
                    <div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #999;">
                        <i class="fas fa-inbox" style="font-size: 2em; margin-bottom: 10px;"></i>
                        <p>No pending shipments. Orders marked as shipped will appear here.</p>
                    </div>
                `;
            }
        } catch (error) {
            console.error('Error loading pending shipments:', error);
            document.getElementById('pendingShipmentsContainer').innerHTML = `
                <div style="text-align: center; padding: 20px; color: #ef4444;">
                    <i class="fas fa-exclamation-triangle"></i> Error loading shipments
                </div>
            `;
        }
    }

    function openReceiveFromPO(poId, ingredientId, itemName, orderedQty, unit, supplier, receivedQty, invoiceNum, expiryDate) {
        // Clear and reset form
        document.getElementById('receiveForm').reset();
        const remainingQty = Math.max(0, parseFloat(orderedQty) - parseFloat(receivedQty));
        
        // Set PO info
        document.getElementById('poId').value = poId;
        
        // Show PO link indicator
        document.getElementById('poLinkInfo').style.display = 'block';
        document.getElementById('linkedPoNumber').textContent = poId;
        document.getElementById('linkedPoSupplier').textContent = supplier;
        document.getElementById('linkedPoQuantity').textContent = parseFloat(orderedQty).toFixed(2);
        document.getElementById('linkedPoUnit').textContent = unit;
        document.getElementById('linkedPoReceived').textContent = parseFloat(receivedQty).toFixed(2);
        document.getElementById('linkedPoRemaining').textContent = `${remainingQty.toFixed(2)} ${unit}`;
        
        // Set basic fields
        document.getElementById('ingredientSelect').value = ingredientId;
        onIngredientSelect();
        document.getElementById('supplierName').value = supplier;
        document.getElementById('invoiceNumber').value = invoiceNum || '';
        document.getElementById('quantityReceived').value = remainingQty > 0 ? remainingQty.toFixed(2) : '';
        
        // Reset any previous inline styles first
        document.getElementById('expiryDate').style.background = '';
        document.getElementById('expiryDate').style.borderColor = '';

        // Auto-fill expiry date only from previous receipts of this same PO
        if (expiryDate) {
            document.getElementById('expiryDate').value = expiryDate;
            document.getElementById('expiryDate').style.background = '#dbeafe';
            document.getElementById('expiryDate').style.borderColor = '#0ea5e9';
        }
        
        // Set dates
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('receivedDate').value = today;
        const now = new Date().toTimeString().slice(0, 5);
        document.getElementById('receivedTime').value = now;
        
        // Focus on quantity field (main thing to fill in)
        setTimeout(() => {
            document.getElementById('quantityReceived').focus();
        }, 100);
        
        // Open modal
        document.getElementById('receiveModal').classList.add('active');
    }

    function clearPoLink() {
        document.getElementById('poId').value = '';
        document.getElementById('poLinkInfo').style.display = 'none';
    }
</script>

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