<?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="Expiry & Wastage Tracking - 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">
    <style>
        .metric-strip {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 16px;
            margin-bottom: 22px;
        }
        .metric-card {
            position: relative;
            overflow: hidden;
            border: 1px solid var(--border-color);
            border-radius: 16px;
            padding: 16px 16px 14px;
            background: radial-gradient(circle at top right, rgba(37, 99, 235, 0.12), transparent 42%),
                        linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
            box-shadow: 0 10px 24px rgba(15, 23, 42, 0.08);
            transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
        }
        .metric-card::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 4px;
            background: #2563eb;
        }
        .metric-card.warning::before { background: #f59e0b; }
        .metric-card.danger::before { background: #ef4444; }
        .metric-card.success::before { background: #10b981; }
        .metric-card.info::before { background: #0ea5e9; }
        .metric-card::after {
            content: "";
            position: absolute;
            right: -26px;
            bottom: -32px;
            width: 120px;
            height: 120px;
            border-radius: 50%;
            background: rgba(37, 99, 235, 0.08);
            pointer-events: none;
        }
        .metric-card.warning::after { background: rgba(245, 158, 11, 0.12); }
        .metric-card.danger::after { background: rgba(239, 68, 68, 0.12); }
        .metric-card.success::after { background: rgba(16, 185, 129, 0.12); }
        .metric-card.info::after { background: rgba(14, 165, 233, 0.12); }
        .metric-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 14px 28px rgba(15, 23, 42, 0.12);
        }
        .metric-head {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            margin-bottom: 8px;
        }
        .metric-card .label {
            font-size: 12px;
            font-weight: 700;
            letter-spacing: 0.02em;
            text-transform: uppercase;
            color: var(--text-secondary);
        }
        .metric-icon {
            width: 34px;
            height: 34px;
            border-radius: 10px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            background: rgba(37, 99, 235, 0.14);
            color: #1d4ed8;
            font-size: 14px;
            box-shadow: 0 6px 14px rgba(37, 99, 235, 0.18);
        }
        .metric-card.warning .metric-icon { background: rgba(245, 158, 11, 0.18); color: #b45309; box-shadow: 0 6px 14px rgba(245, 158, 11, 0.2); }
        .metric-card.danger .metric-icon { background: rgba(239, 68, 68, 0.16); color: #b91c1c; box-shadow: 0 6px 14px rgba(239, 68, 68, 0.18); }
        .metric-card.success .metric-icon { background: rgba(16, 185, 129, 0.18); color: #047857; box-shadow: 0 6px 14px rgba(16, 185, 129, 0.18); }
        .metric-card.info .metric-icon { background: rgba(14, 165, 233, 0.16); color: #0369a1; box-shadow: 0 6px 14px rgba(14, 165, 233, 0.18); }
        .metric-card .value {
            font-size: 38px;
            line-height: 1.1;
            font-weight: 900;
            letter-spacing: -0.02em;
            color: #0f172a;
            text-shadow: 0 2px 0 rgba(255, 255, 255, 0.65);
        }
        @media (max-width: 768px) {
            .metric-card .value { font-size: 30px; }
        }
        .expiry-editor {
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;
            padding: 4px 0;
        }
        .expiry-input-wrap {
            position: relative;
            display: inline-flex;
            align-items: center;
        }
        .expiry-input-icon {
            position: absolute;
            left: 12px;
            color: #0f766e;
            font-size: 13px;
            pointer-events: none;
        }
        .expiry-editor input[type="date"] {
            min-width: 182px;
            height: 40px;
            padding: 8px 12px 8px 34px;
            border: 1px solid #b8e2dc;
            border-radius: 12px;
            background: linear-gradient(180deg, #ffffff 0%, #f0fffb 100%);
            color: #0f172a;
            font-size: 14px;
            font-weight: 600;
            line-height: 1;
            outline: none;
            box-shadow: inset 0 1px 2px rgba(15, 23, 42, 0.06), 0 2px 6px rgba(15, 118, 110, 0.08);
            transition: border-color 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease, transform 0.15s ease;
        }
        .expiry-editor input[type="date"]:hover { border-color: #68c8bc; }
        .expiry-editor input[type="date"]:focus {
            border-color: #0d9488;
            box-shadow: 0 0 0 3px rgba(13, 148, 136, 0.2), 0 6px 14px rgba(13, 148, 136, 0.15);
            background: #f7fffd;
            transform: translateY(-1px);
        }
        .expiry-editor input[type="date"]::-webkit-calendar-picker-indicator {
            cursor: pointer;
            opacity: 0.9;
            filter: saturate(0.9);
        }
        .expiry-editor input[type="date"]::-webkit-datetime-edit {
            color: #0f172a;
        }
        .expiry-editor input[type="date"]::-webkit-datetime-edit-fields-wrapper {
            padding: 0;
        }
        .expiry-editor input[type="date"]::-webkit-date-and-time-value {
            text-align: left;
        }
        .expiry-editor .btn {
            height: 40px;
            padding: 8px 16px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 700;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }
        .expiry-editor .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            filter: grayscale(0.2);
        }
        .missing-expiry {
            color: #0f766e;
            font-weight: 700;
            font-size: 12px;
            background: #e7faf7;
            border: 1px solid #bde8e1;
            border-radius: 999px;
            padding: 4px 10px;
        }
        @media (max-width: 768px) {
            .expiry-editor input[type="date"] {
                min-width: 150px;
                height: 36px;
                font-size: 13px;
                padding-left: 30px;
            }
            .expiry-editor .btn {
                height: 36px;
                padding: 7px 12px;
            }
            .expiry-input-icon {
                left: 10px;
                font-size: 12px;
            }
        }
    </style>
    <title>Expiry & Wastage Tracking</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>Expiry & Wastage Tracking</h1>
                <p>Monitor and document product expiry and wastage</p>
            </div>
            <div class="page-actions">
                <button class="btn btn-primary" onclick="openWastageModal()">
                <i class="fas fa-trash"></i> Log Wastage
            </button>
            <!-- <button class="btn btn-warning" onclick="fixOldRecords()" title="Recalculate cost impact for old records">
                <i class="fas fa-wrench"></i> Fix Old Records
            </button> -->
        </div>
    </div>

    <!-- METRICS -->
    <div class="metric-strip">
        <div class="metric-card danger">
            <div class="metric-head">
                <div class="label">Expired Items</div>
                <span class="metric-icon"><i class="fas fa-skull-crossbones"></i></span>
            </div>
            <div class="value" id="expiredCount">0</div>
        </div>
        <div class="metric-card warning">
            <div class="metric-head">
                <div class="label">Expiring This Week</div>
                <span class="metric-icon"><i class="fas fa-hourglass-half"></i></span>
            </div>
            <div class="value" id="expiringThisWeekCount">0</div>
        </div>
        <div class="metric-card success">
            <div class="metric-head">
                <div class="label">Total Wastage (Today)</div>
                <span class="metric-icon"><i class="fas fa-trash"></i></span>
            </div>
            <div class="value" id="wastedToday">0</div>
        </div>
        <div class="metric-card info">
            <div class="metric-head">
                <div class="label">Financial Impact (This Month)</div>
                <span class="metric-icon"><i class="fas fa-indian-rupee-sign"></i></span>
            </div>
            <div class="value" id="costImpact">₹0</div>
        </div>
    </div>

    <!-- TABS -->
    <div style="margin-bottom: 20px; display: flex; gap: 10px; border-bottom: 2px solid var(--border-color);">
        <button id="expiryTabBtn" class="btn btn-secondary" onclick="switchTab('expiry')" style="border: none; border-bottom: 3px solid var(--primary-color); background: transparent; color: var(--text-primary);">
            <i class="fas fa-calendar-times"></i> Expiry Tracking
        </button>
        <button id="wastageTabBtn" class="btn btn-secondary" onclick="switchTab('wastage')" style="border: none; background: transparent; color: var(--text-secondary);">
            <i class="fas fa-trash"></i> Wastage & Spoilage
        </button>
    </div>

    <!-- EXPIRY TAB -->
    <div id="expiryTab" class="card">
        <div class="card-header">
            <h2><i class="fas fa-calendar-times"></i> Expiry Tracking</h2>
        </div>
        <div class="card-body">
            <table class="table">
                <thead>
                    <tr>
                        <th>Ingredient</th>
                        <th>Batch #</th>
                        <th>Quantity</th>
                        <th>Expiry Date</th>
                        <th>Days Left</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="expiryList">
                    <tr>
                        <td colspan="7" style="text-align: center; padding: 30px;">
                            <i class="fas fa-spinner fa-spin"></i> Loading...
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- WASTAGE TAB -->
    <div id="wastageTab" class="card" style="display: none;">
        <div class="card-header">
            <h2><i class="fas fa-trash"></i> Wastage & Spoilage Records</h2>
        </div>
        <div class="card-body">
            <table class="table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Ingredient</th>
                        <th>Type</th>
                        <th>Quantity</th>
                        <th>Reason</th>
                        <th>Cost Impact</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody id="wastageList">
                    <tr>
                        <td colspan="7" style="text-align: center; padding: 30px;">
                            <i class="fas fa-spinner fa-spin"></i> Loading...
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- LOG WASTAGE MODAL -->
<div id="wastageModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2><i class="fas fa-trash"></i> Log Wastage</h2>
            <button class="modal-close" onclick="closeWastageModal()">&times;</button>
        </div>
        <div class="modal-body">
            <form id="wastageForm">
                <div class="form-group">
                    <label for="wastIngredient">Ingredient *</label>
                    <select id="wastIngredient" required onchange="onWastageIngredientSelect()">
                        <option value="">Select an ingredient...</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="wastType">Type *</label>
                    <select id="wastType" required>
                        <option value="">Select type...</option>
                        <option value="expiry">Expired</option>
                        <option value="spoilage">Spoilage</option>
                        <option value="wastage">Wastage</option>
                        <option value="recall">Product Recall</option>
                    </select>
                </div>

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

                <div class="form-group">
                    <label for="wastUnit">Unit</label>
                    <input type="text" id="wastUnit" readonly style="background: #f0f0f0;">
                </div>

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

                <div class="form-group">
                    <label for="wastReason">Reason for Wastage *</label>
                    <textarea id="wastReason" required placeholder="Explain why this was wasted..."></textarea>
                </div>

                <div class="form-group">
                    <label for="wastDisposal">Disposal Method</label>
                    <select id="wastDisposal">
                        <option value="">Select disposal method...</option>
                        <option value="disposed">Disposed</option>
                        <option value="donated">Donated</option>
                        <option value="composted">Composted</option>
                        <option value="other">Other</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="wastExpiryDate">Expiry Date (if applicable)</label>
                    <input type="date" id="wastExpiryDate">
                </div>

                <div class="form-group">
                    <label for="wastBatchNumber">Batch Number (if applicable)</label>
                    <input type="text" id="wastBatchNumber" placeholder="Batch/Lot number">
                </div>

                <div class="form-group">
                    <label for="wastCost">Estimated Cost Impact (₹)</label>
                    <input type="number" id="wastCost" step="0.01" min="0" placeholder="Auto-calculated from quantity x unit cost" readonly style="background: #f8fafc;">
                </div>

                <div class="form-group">
                    <label for="wastNotes">Additional Notes</label>
                    <textarea id="wastNotes" placeholder="Any other relevant information..."></textarea>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeWastageModal()">Cancel</button>
            <button class="btn btn-primary" onclick="submitWastageForm()">
                <i class="fas fa-check"></i> Log Wastage
            </button>
        </div>
    </div>
</div>
</div>
</div>

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

<script>
    let expiryTrackingMap = {};

    document.addEventListener('DOMContentLoaded', () => {
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('wastDate').value = today;
        
        loadExpiryTracking();
        loadWastageRecords();
        loadMetrics();
        loadIngredientsList();
    });

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

    function onWastageIngredientSelect() {
        const select = document.getElementById('wastIngredient');
        const option = select.options[select.selectedIndex];
        document.getElementById('wastUnit').value = option.dataset.unit || '';
        calculateEstimatedCostImpact();
    }

    function calculateEstimatedCostImpact() {
        const select = document.getElementById('wastIngredient');
        const option = select.options[select.selectedIndex];
        const quantity = parseFloat(document.getElementById('wastQuantity').value || 0);
        const unitCost = parseFloat((option && option.dataset && option.dataset.unitCost) ? option.dataset.unitCost : 0);

        if (!option || !option.value || !quantity || quantity <= 0) {
            document.getElementById('wastCost').value = '';
            return;
        }

        const estimatedCost = quantity * unitCost;
        document.getElementById('wastCost').value = estimatedCost.toFixed(2);
    }

    async function loadMetrics() {
        try {
            const response = await fetch('../backend/store_keeper_api.php?action=get_wastage_metrics', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                console.error('Metrics API error - HTTP', response.status);
                return;
            }
            
            const data = await response.json();
            console.log('📊 Metrics API Response:', data);
            
            if (data.success && data.data) {
                document.getElementById('expiredCount').textContent = data.data.expired_count || 0;
                document.getElementById('expiringThisWeekCount').textContent = data.data.expiring_this_week || 0;
                document.getElementById('wastedToday').textContent = data.data.wasted_today || 0;
                const costDisplay = parseFloat(data.data.cost_impact || 0).toFixed(2);
                document.getElementById('costImpact').textContent = '₹' + costDisplay;
                
                console.log('✅ Metrics loaded:');
                console.log('   - Expired Count:', data.data.expired_count);
                console.log('   - Expiring This Week:', data.data.expiring_this_week);
                console.log('   - Wasted Today:', data.data.wasted_today);
                console.log('   - Cost Impact (This Month):', costDisplay);
            } else {
                console.warn('❌ Metrics API error:', data.message);
            }
        } catch (error) {
            console.error('❌ Error loading metrics:', error);
        }
    }

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

    function isMissingExpiryDate(expiryDate) {
        if (!expiryDate) return true;
        const normalized = String(expiryDate).trim().toLowerCase();
        return normalized === 'null' || normalized === '0000-00-00';
    }

    function getTodayDateISO() {
        const now = new Date();
        const local = new Date(now.getTime() - (now.getTimezoneOffset() * 60000));
        return local.toISOString().split('T')[0];
    }

    function renderExpiryDateCell(item) {
        if (!isMissingExpiryDate(item.expiry_date)) {
            return escapeHtml(item.expiry_date);
        }

        const inputId = `expiryInput_${item.id}`;
        const btnId = `expirySaveBtn_${item.id}`;
        return `
            <div class="expiry-editor">
                <div class="expiry-input-wrap">
                    <i class="fas fa-calendar-alt expiry-input-icon"></i>
                    <input
                        type="date"
                        id="${inputId}"
                        class="form-control"
                        min="${getTodayDateISO()}"
                        onchange="toggleExpirySaveBtn(${item.id})"
                        oninput="toggleExpirySaveBtn(${item.id})"
                        onkeydown="handleExpiryInputKeydown(event, ${item.id})"
                    >
                </div>
                <button id="${btnId}" class="btn btn-sm btn-primary" onclick="saveExpiryDate(${item.id})" disabled>
                    <i class="fas fa-save"></i> Save
                </button>
                <span class="missing-expiry">Set Expiry</span>
            </div>
        `;
    }

    function toggleExpirySaveBtn(ingredientId) {
        const input = document.getElementById(`expiryInput_${ingredientId}`);
        const button = document.getElementById(`expirySaveBtn_${ingredientId}`);
        if (!input || !button) return;
        button.disabled = !input.value;
    }

    function handleExpiryInputKeydown(event, ingredientId) {
        if (event.key === 'Enter') {
            event.preventDefault();
            const button = document.getElementById(`expirySaveBtn_${ingredientId}`);
            if (button && !button.disabled) {
                saveExpiryDate(ingredientId);
            }
        }
    }

    async function loadExpiryTracking() {
        try {
            const response = await fetch('../backend/store_keeper_api.php?action=get_expiry_tracking', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                console.error('Expiry tracking API error - HTTP', response.status);
                document.getElementById('expiryList').innerHTML = '<tr><td colspan="7" class="alert alert-danger">Error loading records</td></tr>';
                return;
            }
            
            const data = await response.json();
            
            const tbody = document.getElementById('expiryList');
            expiryTrackingMap = {};
            
            if (data.success && data.data && data.data.length > 0) {
                data.data.forEach(item => {
                    expiryTrackingMap[item.id] = item;
                });

                tbody.innerHTML = data.data.map(item => {
                    const stockQty = parseFloat(item.current_stock || 0);
                    const isOutOfStock = stockQty <= 0;
                    const isNoExpiry = isMissingExpiryDate(item.expiry_date) || Number(item.days_to_expiry) >= 99999;
                    const daysLeft = Number(item.days_to_expiry);
                    const statusClass = isNoExpiry ? 'info' : daysLeft < 0 ? 'danger' : daysLeft < 7 ? 'warning' : 'success';
                    const statusLabel = isNoExpiry ? 'NO DATE' : daysLeft < 0 ? 'EXPIRED' : daysLeft < 7 ? 'EXPIRING SOON' : 'OK';
                    const daysDisplay = isOutOfStock
                        ? '-'
                        : isNoExpiry
                        ? 'N/A'
                        : (daysLeft < 0 ? `${Math.abs(daysLeft)}d overdue` : `${daysLeft}d`);
                    
                    return `
                        <tr>
                            <td><strong>${escapeHtml(item.ingredient_name)}</strong></td>
                            <td>${escapeHtml(item.batch_number || '-')}</td>
                            <td>${parseFloat(item.current_stock).toFixed(2)} ${item.unit}</td>
                            <td>${isOutOfStock ? '-' : renderExpiryDateCell(item)}</td>
                            <td>${daysDisplay}</td>
                            <td>${isOutOfStock ? '-' : `<span class="badge ${statusClass}">${statusLabel}</span>`}</td>
                            <td>
                                ${isOutOfStock ? '-' : `
                                    <button class="btn btn-sm btn-danger" onclick="markAsWasted(${item.id})">
                                        <i class="fas fa-trash"></i> Waste
                                    </button>
                                `}
                            </td>
                        </tr>
                    `;
                }).join('');
            } else {
                tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; padding: 30px; color: var(--text-secondary);">No expiry tracking records found</td></tr>';
            }
        } catch (error) {
            console.error('Error loading expiry tracking:', error);
            document.getElementById('expiryList').innerHTML = '<tr><td colspan="7" class="alert alert-danger">Error loading records</td></tr>';
        }
    }

    async function submitAutoExpiredWastage(item) {
        const payload = {
            ingredient_id: Number(item.id),
            type: 'expiry',
            quantity: parseFloat(item.current_stock || 0),
            wastage_date: getTodayDateISO(),
            reason: 'Auto-logged from expiry tracking (status: EXPIRED)',
            disposal_method: 'disposed',
            expiry_date: item.expiry_date || null,
            batch_number: item.batch_number || '',
            notes: 'System auto-entry for expired ingredient'
        };

        if (!payload.quantity || payload.quantity <= 0) {
            Swal.fire('Info', 'Current stock is already 0 for this ingredient.', 'info');
            return;
        }

        const response = await fetch('../backend/store_keeper_api.php?action=log_wastage', {
            method: 'POST',
            credentials: 'include',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });
        
        if (!response.ok) {
            throw new Error('HTTP ' + response.status + ': Failed to log wastage');
        }
        
        const data = await response.json();

        if (!data.success) {
            throw new Error(data.message || 'Failed to auto-log expired wastage');
        }
    }

    async function saveExpiryDate(ingredientId) {
        const input = document.getElementById(`expiryInput_${ingredientId}`);
        const saveBtn = document.getElementById(`expirySaveBtn_${ingredientId}`);
        const expiryDate = input ? input.value : '';

        if (!expiryDate) {
            Swal.fire('Error', 'Please select an expiry date', 'error');
            return;
        }

        try {
            if (saveBtn) {
                saveBtn.disabled = true;
                saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';
            }

            const response = await fetch('../backend/store_keeper_api.php?action=set_ingredient_expiry_date', {
                method: 'POST',
                credentials: 'include',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    ingredient_id: ingredientId,
                    expiry_date: expiryDate
                })
            });
            
            if (!response.ok) {
                throw new Error('HTTP ' + response.status + ': Failed to update expiry date');
            }
            
            const data = await response.json();

            if (!data.success) {
                throw new Error(data.message || 'Failed to update expiry date');
            }

            await Swal.fire('Saved', 'Expiry date updated successfully', 'success');
            loadExpiryTracking();
            loadMetrics();
        } catch (error) {
            console.error('Error saving expiry date:', error);
            Swal.fire('Error', error.message || 'Failed to update expiry date', 'error');
        } finally {
            if (saveBtn) {
                saveBtn.innerHTML = '<i class="fas fa-save"></i> Save';
                saveBtn.disabled = !expiryDate;
            }
        }
    }

    async function loadWastageRecords() {
        try {
            const response = await fetch('../backend/store_keeper_api.php?action=get_wastage_records', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                console.error('Wastage records API error - HTTP', response.status);
                document.getElementById('wastageList').innerHTML = '<tr><td colspan="7" class="alert alert-danger">Error loading records</td></tr>';
                return;
            }
            
            const data = await response.json();
            
            const tbody = document.getElementById('wastageList');
            
            if (data.success && data.data && data.data.length > 0) {
                tbody.innerHTML = data.data.map(record => {
                    const statusClass = record.status === 'verified' ? 'success' : record.status === 'disposed' ? 'info' : 'warning';
                    
                    return `
                        <tr>
                            <td>${new Date(record.created_at).toLocaleDateString()}</td>
                            <td><strong>${record.ingredient_name}</strong></td>
                            <td><span class="badge info">${record.type.toUpperCase()}</span></td>
                            <td>${parseFloat(record.quantity).toFixed(2)} ${record.unit}</td>
                            <td>${record.reason}</td>
                            <td>₹${parseFloat(record.cost_impact || 0).toFixed(2)}</td>
                            <td><span class="badge ${statusClass}">${record.status.toUpperCase()}</span></td>
                        </tr>
                    `;
                }).join('');
            } else {
                tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; padding: 30px; color: var(--text-secondary);">No wastage records found</td></tr>';
            }
        } catch (error) {
            console.error('Error loading wastage records:', error);
            document.getElementById('wastageList').innerHTML = '<tr><td colspan="7" class="alert alert-danger">Error loading records</td></tr>';
        }
    }

    function switchTab(tab) {
        // Toggle tab visibility
        document.getElementById('expiryTab').style.display = tab === 'expiry' ? 'block' : 'none';
        document.getElementById('wastageTab').style.display = tab === 'wastage' ? 'block' : 'none';
        
        // Update button styling
        const expiryBtn = document.getElementById('expiryTabBtn');
        const wastageBtn = document.getElementById('wastageTabBtn');
        
        if (tab === 'expiry') {
            // Activate Expiry button
            expiryBtn.style.borderBottom = '3px solid var(--primary-color)';
            expiryBtn.style.color = 'var(--text-primary)';
            // Deactivate Wastage button
            wastageBtn.style.borderBottom = 'none';
            wastageBtn.style.color = 'var(--text-secondary)';
        } else if (tab === 'wastage') {
            // Activate Wastage button
            wastageBtn.style.borderBottom = '3px solid var(--primary-color)';
            wastageBtn.style.color = 'var(--text-primary)';
            // Deactivate Expiry button
            expiryBtn.style.borderBottom = 'none';
            expiryBtn.style.color = 'var(--text-secondary)';
        }
    }

    function openWastageModal() {
        document.getElementById('wastageForm').reset();
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('wastDate').value = today;
        document.getElementById('wastageModal').classList.add('active');
    }

    function closeWastageModal() {
        document.getElementById('wastageModal').classList.remove('active');
    }

    function markAsWasted(ingredientId) {
        const item = expiryTrackingMap[ingredientId];
        const daysLeft = item ? Number(item.days_to_expiry) : null;
        const isExpired = item && !isMissingExpiryDate(item.expiry_date) && Number.isFinite(daysLeft) && daysLeft < 0;

        Swal.fire({
            title: 'Mark as Wasted',
            text: isExpired
                ? 'This ingredient is EXPIRED. Full current stock will be auto-marked as expired wastage. Continue?'
                : 'Do you want to log this as wastage?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: isExpired ? 'Yes, auto log' : 'Yes, log it'
        }).then(async (result) => {
            if (result.isConfirmed) {
                if (isExpired && item) {
                    try {
                        await submitAutoExpiredWastage(item);
                        Swal.fire('Success', 'Expired stock was auto-marked as wastage.', 'success');
                        loadExpiryTracking();
                        loadWastageRecords();
                        loadMetrics();
                    } catch (error) {
                        console.error('Error auto-logging expired wastage:', error);
                        Swal.fire('Error', error.message || 'Failed to auto-log expired wastage', 'error');
                    }
                    return;
                }

                openWastageModal();
                document.getElementById('wastIngredient').value = ingredientId;
                onWastageIngredientSelect();
            }
        });
    }

    async function submitWastageForm() {
        const ingredientId = document.getElementById('wastIngredient').value;
        const wastType = document.getElementById('wastType').value;
        const quantity = document.getElementById('wastQuantity').value;
        const reason = document.getElementById('wastReason').value;
        const costValue = document.getElementById('wastCost').value;

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

        try {
            const payload = {
                ingredient_id: ingredientId,
                type: wastType,
                quantity: parseFloat(quantity),
                wastage_date: document.getElementById('wastDate').value,
                reason: reason,
                disposal_method: document.getElementById('wastDisposal').value,
                expiry_date: document.getElementById('wastExpiryDate').value || null,
                batch_number: document.getElementById('wastBatchNumber').value,
                cost_impact: costValue ? parseFloat(costValue) : 0,
                notes: document.getElementById('wastNotes').value
            };
            
            console.log('Sending wastage payload:', payload);

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

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

            const data = await response.json();
            console.log('Wastage response:', data);
            
            if (data.success) {
                Swal.fire('Success', 'Wastage logged successfully!', 'success');
                closeWastageModal();
                loadWastageRecords();
                loadMetrics();
            } else {
                Swal.fire('Error', data.message || 'Failed to log wastage', 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            Swal.fire('Error', 'An error occurred', '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));
            }
        });
    }

    async function fixOldRecords() {
        const result = await Swal.fire({
            title: 'Debug & Fix Records',
            html: `<p style="text-align: left;">This will:<br/>
            1. Check what's in the database<br/>
            2. Fix invalid dates (0000-00-00)<br/>
            3. Recalculate costs for missing values</p>`,
            icon: 'info',
            showCancelButton: true,
            confirmButtonText: 'Proceed',
            cancelButtonText: 'Cancel'
        });

        if (!result.isConfirmed) return;

        try {
            // Step 1: Check what's in the database
            console.log('=== STEP 1: CHECKING DATABASE ===');
            const checkResponse = await fetch('../backend/store_keeper_api.php?action=check_wastage_records', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (!checkResponse.ok) {
                throw new Error('HTTP ' + checkResponse.status + ': Failed to check records');
            }
            
            const checkData = await checkResponse.json();
            console.log('📋 ALL WASTAGE RECORDS:');
            console.table(checkData.data);
            
            // Show detailed info
            if (checkData.data && checkData.data.length > 0) {
                checkData.data.forEach((record, idx) => {
                    console.log(`Record ${idx + 1}:`);
                    console.log(`  - ID: ${record.id}`);
                    console.log(`  - Ingredient: ${record.ingredient_name}`);
                    console.log(`  - Quantity: ${record.quantity} ${record.unit}`);
                    console.log(`  - Current Cost Impact: ${record.cost_impact}`);
                    console.log(`  - Unit Cost: ${record.unit_cost}`);
                    console.log(`  - Calculated: ${record.quantity} × ${record.unit_cost} = ${record.calculated_cost}`);
                    console.log(`  - Wastage Date: ${record.wastage_date} ${record.wastage_date === '0000-00-00' ? '❌ INVALID' : '✅'}`);
                });
            }

            // Step 2: Fix invalid dates first
            console.log('=== STEP 2: FIXING INVALID DATES ===');
            const dateResponse = await fetch('../backend/store_keeper_api.php?action=fix_invalid_dates', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (!dateResponse.ok) {
                throw new Error('HTTP ' + dateResponse.status + ': Failed to fix dates');
            }
            
            const dateData = await dateResponse.json();
            console.log('Fix Dates Response:', dateData);
            
            if (dateData.success) {
                console.log(`✅ Fixed ${dateData.data.records_updated} records with invalid dates`);
            }

            // Step 3: Fix missing cost impacts
            console.log('=== STEP 3: FIXING MISSING COSTS ===');
            const response = await fetch('../backend/store_keeper_api.php?action=fix_old_wastage_records', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                throw new Error('HTTP ' + response.status + ': Failed to fix costs');
            }
            
            const data = await response.json();
            console.log('Fix Costs Response:', data);

            if (data.success || dateData.success) {
                const datesFixed = dateData.data?.records_updated || 0;
                const costsFixed = data.data?.records_updated || 0;
                await Swal.fire({
                    title: 'All Fixed! ✅',
                    html: `<p style="text-align: left;"><strong>Records Fixed:</strong><br/>
                    - Invalid Dates: ${datesFixed}<br/>
                    - Missing Costs: ${costsFixed}</p>
                    <p style="font-size: 0.9em; color: #666;">Financial impact will now show correctly!</p>`,
                    icon: 'success'
                });
                
                // Reload data
                setTimeout(() => {
                    loadMetrics();
                    loadWastageRecords();
                }, 500);
            } else {
                Swal.fire('Info', 'No records needed fixing.', 'info');
                loadMetrics();
            }
        } catch (error) {
            console.error('❌ Error:', error);
            Swal.fire('Error', 'An error occurred. Check browser console (F12) for details.', 'error');
        }
    }
</script>

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