<?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, maximum-scale=1, user-scalable=no">
    <meta name="description" content="Reports - 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>Reports</title>
    <style>
        /* RESPONSIVE UTILITIES */
        * {
            box-sizing: border-box;
        }

        body {
            font-size: clamp(14px, 2vw, 16px);
        }

        h1 {
            font-size: clamp(24px, 6vw, 36px);
        }

        h2 {
            font-size: clamp(18px, 5vw, 28px);
        }

        h3 {
            font-size: clamp(14px, 4vw, 20px);
        }

        h4 {
            font-size: clamp(13px, 3vw, 16px);
        }

        /* RESPONSIVE CONTAINERS */
        .container {
            padding: 10px;
        }

        @media (min-width: 768px) {
            .container {
                padding: 20px;
            }
        }

        @media (min-width: 1024px) {
            .container {
                padding: 30px;
            }
        }

        /* RESPONSIVE PAGE ACTIONS */
        .page-actions {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }

        .page-header-content {
            padding: 15px 0;
        }

        @media (min-width: 768px) {
            .page-header-content {
                padding: 20px 0;
            }
        }

        /* RESPONSIVE GRIDS */
        .responsive-grid {
            display: grid;
            gap: 10px;
            grid-template-columns: 1fr;
        }

        @media (min-width: 480px) {
            .responsive-grid {
                grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
                gap: 12px;
            }
        }

        @media (min-width: 768px) {
            .responsive-grid {
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                gap: 15px;
            }
        }

        @media (min-width: 1024px) {
            .responsive-grid {
                grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
                gap: 20px;
            }
        }

        .report-cards-grid {
            display: grid;
            gap: 10px;
            grid-template-columns: 1fr;
            margin-bottom: 20px;
        }

        @media (min-width: 480px) {
            .report-cards-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 12px;
            }
        }

        @media (min-width: 768px) {
            .report-cards-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 15px;
                margin-bottom: 25px;
            }
        }

        @media (min-width: 1024px) {
            .report-cards-grid {
                grid-template-columns: repeat(4, 1fr);
                gap: 20px;
                margin-bottom: 30px;
            }
        }

        /* RESPONSIVE CARDS */
        .report-card {
            padding: 15px;
            text-align: center;
            cursor: pointer;
            transition: transform 0.3s, box-shadow 0.3s;
        }

        .report-card:hover,
        .report-card:active {
            transform: translateY(-2px);
        }

        @media (min-width: 768px) {
            .report-card {
                padding: 20px;
            }
        }

        @media (min-width: 1024px) {
            .report-card {
                padding: 30px;
            }
        }

        .report-card-icon {
            font-size: clamp(30px, 8vw, 50px);
            margin-bottom: 10px;
        }

        .report-card p {
            font-size: clamp(12px, 2vw, 14px);
            margin-bottom: 0;
        }

        /* RESPONSIVE CHARTS */
        .chart-container {
            position: relative;
            height: 250px;
            width: 100%;
            margin-bottom: 15px;
        }

        @media (min-width: 768px) {
            .chart-container {
                height: 300px;
                margin-bottom: 20px;
            }
        }

        @media (min-width: 1024px) {
            .chart-container {
                height: 350px;
            }
        }

        .charts-grid {
            display: grid;
            gap: 12px;
            grid-template-columns: 1fr;
            margin-bottom: 20px;
        }

        @media (min-width: 768px) {
            .charts-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 15px;
                margin-bottom: 25px;
            }
        }

        @media (min-width: 1024px) {
            .charts-grid {
                grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
                gap: 20px;
                margin-bottom: 30px;
            }
        }

        /* RESPONSIVE TABLES */
        .table-responsive {
            overflow-x: auto;
            margin: 0;
            -webkit-overflow-scrolling: touch;
        }

        .table {
            font-size: clamp(12px, 1.5vw, 14px);
            min-width: 100%;
        }

        .table thead th {
            padding: 8px 6px;
            font-size: clamp(11px, 1.5vw, 13px);
        }

        @media (min-width: 768px) {
            .table thead th {
                padding: 12px 8px;
                font-size: clamp(12px, 1.5vw, 14px);
            }

            .table tbody td {
                padding: 10px 8px;
            }
        }

        .table tbody td {
            padding: 8px 6px;
        }

        /* RESPONSIVE BADGES */
        .badge {
            padding: 4px 8px;
            font-size: clamp(10px, 1.5vw, 12px);
            display: inline-block;
            white-space: nowrap;
        }

        @media (min-width: 768px) {
            .badge {
                padding: 4px 10px;
            }
        }

        /* RESPONSIVE BUTTONS */
        .btn {
            padding: clamp(8px, 2vw, 12px) clamp(12px, 3vw, 16px);
            font-size: clamp(12px, 2vw, 14px);
            border-radius: 4px;
            white-space: nowrap;
            min-height: 36px;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        @media (max-width: 480px) {
            .btn {
                min-height: 40px;
            }

            .btn i {
                font-size: 14px;
            }
        }

        /* RESPONSIVE METRICS */
        .metrics-grid {
            display: grid;
            gap: 10px;
            grid-template-columns: repeat(2, 1fr);
            margin-bottom: 15px;
        }

        @media (min-width: 576px) {
            .metrics-grid {
                grid-template-columns: repeat(3, 1fr);
                gap: 12px;
            }
        }

        @media (min-width: 768px) {
            .metrics-grid {
                grid-template-columns: repeat(4, 1fr);
                gap: 15px;
                margin-bottom: 20px;
            }
        }

        .metric-card {
            padding: 12px;
            border-radius: 6px;
        }

        @media (min-width: 768px) {
            .metric-card {
                padding: 15px;
            }
        }

        @media (min-width: 1024px) {
            .metric-card {
                padding: 20px;
            }
        }

        .metric-label {
            font-size: clamp(11px, 1.5vw, 13px);
            margin-bottom: 8px;
        }

        .metric-value {
            font-size: clamp(18px, 5vw, 28px);
            font-weight: 700;
        }

        /* RESPONSIVE FILTERS */
        .filter-container {
            display: grid;
            gap: 10px;
            grid-template-columns: 1fr;
            margin-bottom: 15px;
            padding: 12px;
        }

        @media (min-width: 480px) {
            .filter-container {
                grid-template-columns: repeat(2, 1fr);
                gap: 12px;
            }
        }

        @media (min-width: 768px) {
            .filter-container {
                grid-template-columns: repeat(4, 1fr);
                gap: 15px;
                margin-bottom: 20px;
                padding: 15px;
            }
        }

        .form-control {
            width: 100%;
            padding: clamp(8px, 2vw, 12px);
            font-size: clamp(12px, 2vw, 14px);
        }

        /* RESPONSIVE HEADER */
        .report-header {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            align-items: flex-start;
            gap: 12px;
            margin-bottom: 20px;
        }

        @media (min-width: 768px) {
            .report-header {
                flex-direction: row;
                align-items: center;
                gap: 20px;
                margin-bottom: 25px;
            }
        }

        .report-header h2 {
            margin: 0;
            flex: 1;
        }

        .report-header button {
            width: 100%;
        }

        @media (min-width: 768px) {
            .report-header button {
                width: auto;
            }
        }

        /* MOBILE OPTIMIZATIONS */
        @media (max-width: 480px) {
            .navbar-menu {
                display: none;
            }

            .page-header {
                flex-direction: column;
                align-items: flex-start;
            }

            .page-actions {
                width: 100%;
            }

            .page-actions button {
                width: 100%;
            }

            table {
                border-collapse: collapse;
                border-spacing: 0;
            }

            th, td {
                border: 1px solid var(--border-color);
            }
        }

        /* PRINT STYLES */
        @media print {
            .navbar, .page-actions, .page-header-content {
                display: none;
            }

            .report-cards-grid {
                display: none;
            }

            body {
                font-size: 11pt;
            }

            .chart-container {
                page-break-inside: avoid;
            }

            table {
                font-size: 10pt;
            }
        }
    </style>
</head>
<body>
<?php include 'sidebar.php'; ?>

<div class="dashboard-container">
    <div class="main-content">
        <div class="page-header">
            <div class="page-header-content">
                <h1>Reports</h1>
                <p>Analyze inventory and wastage data</p>
            </div>
            <div class="page-actions">
                <button class="btn btn-primary" onclick="window.print()">
                    <i class="fas fa-print"></i> Print Report
                </button>
            </div>
        </div>

    <!-- REPORT SELECTION -->
    <div class="report-cards-grid">
        <div class="card report-card" onclick="showReport('stock_receiving')">
            <div class="report-card-icon" style="color: var(--primary-color);">
                <i class="fas fa-box-open"></i>
            </div>
            <h3 style="margin: 10px 0;">Stock Receiving</h3>
            <p style="color: var(--text-secondary);">Track all received inventory</p>
        </div>

        <div class="card report-card" onclick="showReport('inventory')">
            <div class="report-card-icon" style="color: var(--warning-color);">
                <i class="fas fa-boxes"></i>
            </div>
            <h3 style="margin: 10px 0;">Inventory Status</h3>
            <p style="color: var(--text-secondary);">Current stock levels and value</p>
        </div>

        <div class="card report-card" onclick="showReport('wastage')">
            <div class="report-card-icon" style="color: var(--danger-color);">
                <i class="fas fa-trash"></i>
            </div>
            <h3 style="margin: 10px 0;">Wastage Report</h3>
            <p style="color: var(--text-secondary);">Wastage and spoilage analysis</p>
        </div>

        <div class="card report-card" onclick="showReport('expiry')">
            <div class="report-card-icon" style="color: var(--info-color);">
                <i class="fas fa-calendar-times"></i>
            </div>
            <h3 style="margin: 10px 0;">Expiry Management</h3>
            <p style="color: var(--text-secondary);">Items expiring soon or expired</p>
        </div>
    </div>

    <!-- PLACEHOLDER FOR REPORTS -->
    <div class="card">
        <div class="card-body" id="reportContainer" style="text-align: center; padding: clamp(30px, 10vw, 60px) clamp(15px, 5vw, 20px);">
            <i class="fas fa-chart-bar" style="font-size: clamp(40px, 15vw, 60px); color: var(--text-secondary); margin-bottom: 20px;"></i>
            <h2 style="color: var(--text-secondary); margin: 20px 0;">Select a Report</h2>
            <p style="color: var(--text-secondary);">Click on any report card above to generate and view the detailed analysis.</p>
        </div>
    </div>
</div>
</div>
</div>

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

<script>
    let reportCharts = [];
    let stockReceivingRows = [];
    let reportFromDate = '';
    let reportToDate = '';

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

    function getResponsiveTableWrapper(html) {
        return `<div class="table-responsive">\n${html}\n</div>`;
    }

    function destroyReportCharts() {
        reportCharts.forEach(chart => {
            try { chart.destroy(); } catch (e) {}
        });
        reportCharts = [];
    }

    function applyResponsiveStyles(selector) {
        // Make tables work on mobile
        const tables = document.querySelectorAll(selector ? `${selector} table` : 'table');
        tables.forEach(table => {
            if (!table.parentElement.classList.contains('table-responsive')) {
                const wrapper = document.createElement('div');
                wrapper.className = 'table-responsive';
                table.parentElement.insertBefore(wrapper, table);
                wrapper.appendChild(table);
            }
        });
    }

    async function showReport(type) {
        if (type === 'stock_receiving') {
            await loadStockReceivingReport();
            return;
        }

        if (type === 'inventory') {
            await loadInventoryReport();
            return;
        }

        if (type === 'wastage') {
            await loadWastageReport();
            return;
        }

        if (type === 'expiry') {
            await loadExpiryReport();
            return;
        }

        Swal.fire({
            title: 'Report Coming Soon',
            text: 'This report will be available in the next version.',
            icon: 'info',
            confirmButtonText: 'OK'
        });
    }

    async function loadStockReceivingReport() {
        const container = document.getElementById('reportContainer');
        container.style.textAlign = 'left';
        container.style.padding = '20px';
        container.innerHTML = `
            <div style="text-align:center; padding: 30px; color: var(--text-secondary);">
                <i class="fas fa-spinner fa-spin"></i> Loading stock receiving report...
            </div>
        `;

        try {
            const response = await fetch('../backend/store_keeper_api.php?action=get_stock_receiving', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            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}`);
            }

            stockReceivingRows = Array.isArray(data.data) ? data.data : [];
            renderStockReceivingReport();
        } catch (error) {
            destroyReportCharts();
            container.innerHTML = `
                <div style="text-align:center; padding: 30px; color: #ef4444;">
                    <i class="fas fa-exclamation-triangle"></i> ${escapeHtml(error.message || 'Failed to load stock receiving report')}
                </div>
            `;
        }
    }

    function getFilteredStockReceivingRows() {
        return stockReceivingRows.filter(row => {
            const rowDate = String(row.created_at || '').slice(0, 10);
            if (!rowDate) return false;
            if (reportFromDate && rowDate < reportFromDate) return false;
            if (reportToDate && rowDate > reportToDate) return false;
            return true;
        });
    }

    function applyStockReceivingDateFilter() {
        const fromInput = document.getElementById('reportFromDate');
        const toInput = document.getElementById('reportToDate');
        reportFromDate = fromInput ? fromInput.value : '';
        reportToDate = toInput ? toInput.value : '';

        if (reportFromDate && reportToDate && reportFromDate > reportToDate) {
            Swal.fire('Invalid Date Range', 'From date cannot be after To date.', 'warning');
            return;
        }

        renderStockReceivingReport();
    }

    function clearStockReceivingDateFilter() {
        reportFromDate = '';
        reportToDate = '';
        renderStockReceivingReport();
    }

    function renderStockReceivingReport() {
        const container = document.getElementById('reportContainer');
        const rows = getFilteredStockReceivingRows();
            const totalEntries = rows.length;
            const totalQuantity = rows.reduce((sum, r) => sum + parseFloat(r.quantity_received || 0), 0);
            const uniqueIngredients = new Set(rows.map(r => String(r.ingredient_name || '').trim()).filter(Boolean)).size;
            const suppliers = new Set(rows.map(r => String(r.supplier_name || '').trim()).filter(Boolean)).size;

            container.innerHTML = `
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:16px;">
                    <h2 style="margin:0;"><i class="fas fa-box-open"></i> Stock Receiving Report</h2>
                    <div style="display:flex; gap:8px; align-items:center;">
                        <button class="btn btn-secondary" onclick="loadStockReceivingReport()">
                            <i class="fas fa-rotate"></i> Refresh
                        </button>
                    </div>
                </div>

                <div class="card" style="padding:12px; margin-bottom:16px;">
                    <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap:10px; align-items:end;">
                        <div>
                            <label for="reportFromDate" style="display:block; margin-bottom:6px; font-size:12px; color:var(--text-secondary);">From Date</label>
                            <input type="date" id="reportFromDate" value="${reportFromDate}" class="form-control" style="width:100%; padding:8px;">
                        </div>
                        <div>
                            <label for="reportToDate" style="display:block; margin-bottom:6px; font-size:12px; color:var(--text-secondary);">To Date</label>
                            <input type="date" id="reportToDate" value="${reportToDate}" class="form-control" style="width:100%; padding:8px;">
                        </div>
                        <div style="display:flex; gap:8px;">
                            <button class="btn btn-primary" onclick="applyStockReceivingDateFilter()"><i class="fas fa-filter"></i> Apply</button>
                            <button class="btn btn-secondary" onclick="clearStockReceivingDateFilter()"><i class="fas fa-eraser"></i> Clear</button>
                        </div>
                    </div>
                </div>

                <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap:12px; margin-bottom:16px;">
                    <div class="card" style="padding:12px;">
                        <div style="font-size:12px; color:var(--text-secondary);">Total Entries</div>
                        <div style="font-size:22px; font-weight:700;">${totalEntries}</div>
                    </div>
                    <div class="card" style="padding:12px;">
                        <div style="font-size:12px; color:var(--text-secondary);">Total Quantity</div>
                        <div style="font-size:22px; font-weight:700;">${totalQuantity.toFixed(2)}</div>
                    </div>
                    <div class="card" style="padding:12px;">
                        <div style="font-size:12px; color:var(--text-secondary);">Ingredients</div>
                        <div style="font-size:22px; font-weight:700;">${uniqueIngredients}</div>
                    </div>
                    <div class="card" style="padding:12px;">
                        <div style="font-size:12px; color:var(--text-secondary);">Suppliers</div>
                        <div style="font-size:22px; font-weight:700;">${suppliers}</div>
                    </div>
                </div>

                <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap:12px; margin-bottom:16px;">
                    <div class="card" style="padding:12px; height:300px; display:flex; flex-direction:column;">
                        <h4 style="margin: 0 0 10px 0;">Daily Receiving Trend</h4>
                        <div style="position:relative; flex:1; min-height:0;">
                            <canvas id="receivingTrendChart" style="height:100% !important; width:100%;"></canvas>
                        </div>
                    </div>
                    <div class="card" style="padding:12px; height:300px; display:flex; flex-direction:column;">
                        <h4 style="margin: 0 0 10px 0;">Top Ingredients (Qty)</h4>
                        <div style="position:relative; flex:1; min-height:0;">
                            <canvas id="ingredientQtyChart" style="height:100% !important; width:100%;"></canvas>
                        </div>
                    </div>
                    <div class="card" style="padding:12px; height:300px; display:flex; flex-direction:column;">
                        <h4 style="margin: 0 0 10px 0;">Supplier Share</h4>
                        <div style="position:relative; flex:1; min-height:0;">
                            <canvas id="supplierShareChart" style="height:100% !important; width:100%;"></canvas>
                        </div>
                    </div>
                </div>

                <div style="overflow:auto;">
                    <table class="table" style="width:100%;">
                        <thead>
                            <tr>
                                <th>Date & Time</th>
                                <th>Ingredient</th>
                                <th>Quantity</th>
                                <th>Supplier</th>
                                <th>Invoice</th>
                                <th>PO</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${rows.length ? rows.map(row => `
                                <tr>
                                    <td>${new Date(row.created_at).toLocaleString()}</td>
                                    <td>${escapeHtml(row.ingredient_name || '-')}</td>
                                    <td>${parseFloat(row.quantity_received || 0).toFixed(2)} ${escapeHtml(row.unit || '')}</td>
                                    <td>${escapeHtml(row.supplier_name || '-')}</td>
                                    <td>${escapeHtml(row.invoice_number || '-')}</td>
                                    <td>${escapeHtml(row.po_number || '-')}</td>
                                </tr>
                            `).join('') : `
                                <tr><td colspan="6" style="text-align:center; padding: 20px; color: var(--text-secondary);">No stock receiving records found</td></tr>
                            `}
                        </tbody>
                    </table>
                </div>
            `;

        destroyReportCharts();
        renderStockReceivingCharts(rows);
        setTimeout(() => applyResponsiveStyles('#reportContainer'), 100);
    }

    function renderStockReceivingCharts(rows) {
        const trendMap = new Map();
        const ingredientMap = new Map();
        const supplierMap = new Map();

        rows.forEach(row => {
            const qty = parseFloat(row.quantity_received || 0);
            const dateKey = new Date(row.created_at).toLocaleDateString();
            const ingredient = String(row.ingredient_name || 'Unknown');
            const supplier = String(row.supplier_name || 'Unknown');

            trendMap.set(dateKey, (trendMap.get(dateKey) || 0) + qty);
            ingredientMap.set(ingredient, (ingredientMap.get(ingredient) || 0) + qty);
            supplierMap.set(supplier, (supplierMap.get(supplier) || 0) + qty);
        });

        const trendLabels = Array.from(trendMap.keys()).reverse();
        const trendData = Array.from(trendMap.values()).reverse().map(v => Number(v.toFixed(2)));

        const topIngredients = Array.from(ingredientMap.entries())
            .sort((a, b) => b[1] - a[1])
            .slice(0, 6);
        const ingredientLabels = topIngredients.map(([name]) => name);
        const ingredientData = topIngredients.map(([, qty]) => Number(qty.toFixed(2)));

        const supplierEntries = Array.from(supplierMap.entries())
            .sort((a, b) => b[1] - a[1])
            .slice(0, 6);
        const supplierLabels = supplierEntries.map(([name]) => name);
        const supplierData = supplierEntries.map(([, qty]) => Number(qty.toFixed(2)));

        const trendCtx = document.getElementById('receivingTrendChart');
        if (trendCtx) {
            reportCharts.push(new Chart(trendCtx, {
                type: 'line',
                data: {
                    labels: trendLabels.length ? trendLabels : ['No Data'],
                    datasets: [{
                        label: 'Quantity Received',
                        data: trendData.length ? trendData : [0],
                        borderColor: '#2563eb',
                        backgroundColor: 'rgba(37, 99, 235, 0.15)',
                        fill: true,
                        tension: 0.35
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            }));
        }

        const ingredientCtx = document.getElementById('ingredientQtyChart');
        if (ingredientCtx) {
            const ingredientPalette = ['#2563eb', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#14b8a6', '#f97316', '#84cc16'];
            const ingredientColors = (ingredientLabels.length ? ingredientLabels : ['No Data']).map((_, idx) => ingredientPalette[idx % ingredientPalette.length]);
            reportCharts.push(new Chart(ingredientCtx, {
                type: 'bar',
                data: {
                    labels: ingredientLabels.length ? ingredientLabels : ['No Data'],
                    datasets: [{
                        label: 'Quantity',
                        data: ingredientData.length ? ingredientData : [0],
                        backgroundColor: ingredientColors,
                        borderColor: ingredientColors,
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            }));
        }

        const supplierCtx = document.getElementById('supplierShareChart');
        if (supplierCtx) {
            reportCharts.push(new Chart(supplierCtx, {
                type: 'doughnut',
                data: {
                    labels: supplierLabels.length ? supplierLabels : ['No Data'],
                    datasets: [{
                        data: supplierData.length ? supplierData : [1],
                        backgroundColor: ['#0ea5e9', '#6366f1', '#14b8a6', '#f59e0b', '#ef4444', '#84cc16']
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '60%',
                    layout: {
                        padding: {
                            top: 4,
                            bottom: 4
                        }
                    },
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                boxWidth: 12,
                                boxHeight: 12,
                                padding: 10
                            }
                        }
                    }
                }
            }));
        }
    }

    async function loadInventoryReport() {
        destroyReportCharts();
        const container = document.getElementById('reportContainer');
        container.style.textAlign = 'left';
        container.style.padding = '20px';
        container.innerHTML = `
            <div style="text-align:center; padding: 30px; color: var(--text-secondary);">
                <i class="fas fa-spinner fa-spin"></i> Loading inventory report...
            </div>
        `;

        try {
            const response = await fetch('../backend/store_keeper_api.php?action=get_inventory', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            const rawText = await response.text();
            let data;
            try {
                data = JSON.parse(rawText);
            } catch (parseError) {
                throw new Error(`Invalid JSON response`);
            }

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

            const inventoryData = Array.isArray(data.data) ? data.data : [];
            renderInventoryReport(inventoryData);
        } catch (error) {
            destroyReportCharts();
            container.innerHTML = `
                <div style="text-align:center; padding: 30px; color: #ef4444;">
                    <i class="fas fa-exclamation-triangle"></i> ${escapeHtml(error.message || 'Failed to load inventory report')}
                </div>
            `;
        }
    }

    function renderInventoryReport(inventoryData) {
        const container = document.getElementById('reportContainer');

        // Calculate metrics
        const totalItems = inventoryData.length;
        const totalValue = inventoryData.reduce((sum, item) => sum + (parseFloat(item.current_stock || 0) * parseFloat(item.unit_cost || 0)), 0);
        const lowStockCount = inventoryData.filter(item => parseFloat(item.current_stock || 0) <= parseFloat(item.minimum_stock || 0)).length;
        const adequateStockCount = inventoryData.filter(item => parseFloat(item.current_stock || 0) > parseFloat(item.minimum_stock || 0)).length;

        // Group by status
        const statusCounts = {
            'Low': lowStockCount,
            'Normal': adequateStockCount
        };

        // Top 5 by value
        const topByValue = [...inventoryData]
            .map(item => ({
                name: item.name,
                value: parseFloat(item.current_stock || 0) * parseFloat(item.unit_cost || 0)
            }))
            .sort((a, b) => b.value - a.value)
            .slice(0, 5);

        // Stock distribution
        const stockDistribution = {
            'Critical': inventoryData.filter(i => parseFloat(i.current_stock || 0) < parseFloat(i.minimum_stock || 0) * 0.5).length,
            'Low': inventoryData.filter(i => {
                const stock = parseFloat(i.current_stock || 0);
                const min = parseFloat(i.minimum_stock || 0);
                return stock >= min * 0.5 && stock <= min;
            }).length,
            'Adequate': inventoryData.filter(i => {
                const stock = parseFloat(i.current_stock || 0);
                const min = parseFloat(i.minimum_stock || 0);
                return stock > min && stock <= min * 2;
            }).length,
            'Optimal': inventoryData.filter(i => {
                const stock = parseFloat(i.current_stock || 0);
                const min = parseFloat(i.minimum_stock || 0);
                return stock > min * 2;
            }).length
        };

        container.innerHTML = `
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
                <h2 style="margin:0;"><i class="fas fa-boxes"></i> Inventory Status Report</h2>
                <button class="btn btn-secondary" onclick="loadInventoryReport()">
                    <i class="fas fa-rotate"></i> Refresh
                </button>
            </div>

            <!-- KEY METRICS -->
            <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap:15px; margin-bottom:20px;">
                <div class="card" style="padding:20px;">
                    <div style="font-size:13px; color:var(--text-secondary); margin-bottom:8px;">Total Items</div>
                    <div style="font-size:28px; font-weight:700; color:var(--primary-color);">${totalItems}</div>
                </div>
                <div class="card" style="padding:20px;">
                    <div style="font-size:13px; color:var(--text-secondary); margin-bottom:8px;">Total Inventory Value</div>
                    <div style="font-size:28px; font-weight:700; color:var(--success-color);">₹${totalValue.toFixed(0)}</div>
                </div>
                <div class="card" style="padding:20px;">
                    <div style="font-size:13px; color:var(--text-secondary); margin-bottom:8px;">Low Stock Items</div>
                    <div style="font-size:28px; font-weight:700; color:var(--warning-color);">${lowStockCount}</div>
                </div>
                <div class="card" style="padding:20px;">
                    <div style="font-size:13px; color:var(--text-secondary); margin-bottom:8px;">Adequate Stock</div>
                    <div style="font-size:28px; font-weight:700; color:var(--info-color);">${adequateStockCount}</div>
                </div>
            </div>

            <!-- CHARTS -->
            <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap:15px; margin-bottom:20px;">
                <div class="card" style="padding:15px; height:350px;">
                    <h4 style="margin:0 0 15px 0;"><i class="fas fa-chart-doughnut"></i> Stock Status Distribution</h4>
                    <div style="position:relative; height:300px;">
                        <canvas id="statusChart"></canvas>
                    </div>
                </div>
                <div class="card" style="padding:15px; height:350px;">
                    <h4 style="margin:0 0 15px 0;"><i class="fas fa-chart-pie"></i> Stock Level Categories</h4>
                    <div style="position:relative; height:300px;">
                        <canvas id="distributionChart"></canvas>
                    </div>
                </div>
                <div class="card" style="padding:15px; height:350px;">
                    <h4 style="margin:0 0 15px 0;"><i class="fas fa-chart-bar"></i> Top 5 by Inventory Value</h4>
                    <div style="position:relative; height:300px;">
                        <canvas id="valueChart"></canvas>
                    </div>
                </div>
            </div>

            <!-- TABLE -->
            <div class="card">
                <div style="padding:15px; border-bottom:1px solid var(--border-color);">
                    <h4 style="margin:0;"><i class="fas fa-table"></i> Complete Inventory</h4>
                </div>
                <div style="overflow:auto;">
                    <table class="table" style="margin-bottom:0;">
                        <thead>
                            <tr>
                                <th>Ingredient</th>
                                <th>Current Stock</th>
                                <th>Minimum Stock</th>
                                <th>Unit</th>
                                <th>Unit Cost</th>
                                <th>Total Value</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${inventoryData.map(item => {
                                const stock = parseFloat(item.current_stock || 0);
                                const min = parseFloat(item.minimum_stock || 0);
                                let statusBadge = '';
                                if (stock <= min * 0.5) {
                                    statusBadge = '<span class="badge danger">Critical</span>';
                                } else if (stock <= min) {
                                    statusBadge = '<span class="badge warning">Low</span>';
                                } else if (stock <= min * 2) {
                                    statusBadge = '<span class="badge info">Adequate</span>';
                                } else {
                                    statusBadge = '<span class="badge success">Optimal</span>';
                                }
                                const value = stock * parseFloat(item.unit_cost || 0);
                                return `<tr>
                                    <td><strong>${escapeHtml(item.name)}</strong></td>
                                    <td>${stock.toFixed(2)}</td>
                                    <td>${min.toFixed(2)}</td>
                                    <td>${escapeHtml(item.unit)}</td>
                                    <td>₹${parseFloat(item.unit_cost || 0).toFixed(2)}</td>
                                    <td><strong>₹${value.toFixed(2)}</strong></td>
                                    <td>${statusBadge}</td>
                                </tr>`;
                            }).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
        `;

        // Render charts
        setTimeout(() => {
            renderInventoryCharts(inventoryData, statusCounts, topByValue, stockDistribution);
            applyResponsiveStyles('#reportContainer');
        }, 100);
    }

    function renderInventoryCharts(inventoryData, statusCounts, topByValue, stockDistribution) {
        // Status Chart (Pie)
        const statusCtx = document.getElementById('statusChart');
        if (statusCtx) {
            const chart = new Chart(statusCtx, {
                type: 'doughnut',
                data: {
                    labels: Object.keys(statusCounts),
                    datasets: [{
                        data: Object.values(statusCounts),
                        backgroundColor: ['#10b981', '#f59e0b'],
                        borderColor: '#fff',
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { position: 'bottom' },
                        tooltip: {
                            callbacks: {
                                label: ctx => `${ctx.label}: ${ctx.parsed} items`
                            }
                        }
                    }
                }
            });
            reportCharts.push(chart);
        }

        // Distribution Chart (Pie)
        const distCtx = document.getElementById('distributionChart');
        if (distCtx) {
            const chart = new Chart(distCtx, {
                type: 'pie',
                data: {
                    labels: Object.keys(stockDistribution),
                    datasets: [{
                        data: Object.values(stockDistribution),
                        backgroundColor: ['#ef4444', '#f59e0b', '#3b82f6', '#10b981'],
                        borderColor: '#fff',
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { position: 'bottom' },
                        tooltip: {
                            callbacks: {
                                label: ctx => `${ctx.label}: ${ctx.parsed} items`
                            }
                        }
                    }
                }
            });
            reportCharts.push(chart);
        }

        // Value Chart (Bar)
        const valueCtx = document.getElementById('valueChart');
        if (valueCtx) {
            const chart = new Chart(valueCtx, {
                type: 'bar',
                data: {
                    labels: topByValue.map(item => item.name.substring(0, 15)),
                    datasets: [{
                        label: 'Inventory Value (₹)',
                        data: topByValue.map(item => item.value),
                        backgroundColor: '#2ec4b6',
                        borderColor: '#1a9b8e',
                        borderWidth: 1
                    }]
                },
                options: {
                    indexAxis: 'y',
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false }
                    },
                    scales: {
                        x: { beginAtZero: true }
                    }
                }
            });
            reportCharts.push(chart);
        }
    }

    async function loadWastageReport() {
        const container = document.getElementById('reportContainer');
        container.style.textAlign = 'left';
        container.style.padding = '20px';
        container.innerHTML = `
            <div style="text-align:center; padding: 30px; color: var(--text-secondary);">
                <i class="fas fa-spinner fa-spin"></i> Loading wastage report...
            </div>
        `;

        try {
            const response = await fetch('../backend/store_keeper_api.php?action=get_wastage_records', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            const rawText = await response.text();
            let data;
            try {
                data = JSON.parse(rawText);
            } catch (parseError) {
                throw new Error(`Invalid JSON response`);
            }

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

            const wastageData = Array.isArray(data.data) ? data.data : [];
            renderWastageReport(wastageData);
        } catch (error) {
            destroyReportCharts();
            container.innerHTML = `
                <div style="text-align:center; padding: 30px; color: #ef4444;">
                    <i class="fas fa-exclamation-triangle"></i> ${escapeHtml(error.message || 'Failed to load wastage report')}
                </div>
            `;
        }
    }

    function renderWastageReport(wastageData) {
        const container = document.getElementById('reportContainer');

        // Calculate metrics
        const totalWastage = wastageData.reduce((sum, item) => sum + parseFloat(item.quantity || 0), 0);
        const totalCost = wastageData.reduce((sum, item) => sum + parseFloat(item.cost_impact || 0), 0);
        const wasteByType = {};
        const costByType = {};

        wastageData.forEach(item => {
            const type = item.type || 'Unknown';
            wasteByType[type] = (wasteByType[type] || 0) + parseFloat(item.quantity || 0);
            costByType[type] = (costByType[type] || 0) + parseFloat(item.cost_impact || 0);
        });

        // Top wasted ingredients
        const topWasted = [...wastageData]
            .map(item => ({
                name: item.ingredient_name,
                quantity: parseFloat(item.quantity || 0),
                cost: parseFloat(item.cost_impact || 0)
            }))
            .sort((a, b) => b.cost - a.cost)
            .slice(0, 5);

        container.innerHTML = `
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
                <h2 style="margin:0;"><i class="fas fa-trash"></i> Wastage Report</h2>
                <button class="btn btn-secondary" onclick="loadWastageReport()">
                    <i class="fas fa-rotate"></i> Refresh
                </button>
            </div>

            <!-- KEY METRICS -->
            <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap:15px; margin-bottom:20px;">
                <div class="card" style="padding:20px;">
                    <div style="font-size:13px; color:var(--text-secondary); margin-bottom:8px;">Total Wasted (Qty)</div>
                    <div style="font-size:28px; font-weight:700; color:var(--danger-color);">${totalWastage.toFixed(2)} kg</div>
                </div>
                <div class="card" style="padding:20px;">
                    <div style="font-size:13px; color:var(--text-secondary); margin-bottom:8px;">Total Cost Impact</div>
                    <div style="font-size:28px; font-weight:700; color:var(--danger-color);">₹${totalCost.toFixed(2)}</div>
                </div>
                <div class="card" style="padding:20px;">
                    <div style="font-size:13px; color:var(--text-secondary); margin-bottom:8px;">Records Count</div>
                    <div style="font-size:28px; font-weight:700; color:var(--text-primary);">${wastageData.length}</div>
                </div>
                <div class="card" style="padding:20px;">
                    <div style="font-size:13px; color:var(--text-secondary); margin-bottom:8px;">Avg Cost Per Record</div>
                    <div style="font-size:28px; font-weight:700; color:var(--info-color);">₹${(totalCost / (wastageData.length || 1)).toFixed(2)}</div>
                </div>
            </div>

            <!-- CHARTS -->
            <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap:15px; margin-bottom:20px;">
                <div class="card" style="padding:15px; height:350px;">
                    <h4 style="margin:0 0 15px 0;"><i class="fas fa-chart-pie"></i> Wastage by Type</h4>
                    <div style="position:relative; height:300px;">
                        <canvas id="wastageTypeChart"></canvas>
                    </div>
                </div>
                <div class="card" style="padding:15px; height:350px;">
                    <h4 style="margin:0 0 15px 0;"><i class="fas fa-chart-bar"></i> Top 5 by Cost</h4>
                    <div style="position:relative; height:300px;">
                        <canvas id="topWastedChart"></canvas>
                    </div>
                </div>
                <div class="card" style="padding:15px; height:350px;">
                    <h4 style="margin:0 0 15px 0;"><i class="fas fa-chart-doughnut"></i> Cost by Type</h4>
                    <div style="position:relative; height:300px;">
                        <canvas id="costByTypeChart"></canvas>
                    </div>
                </div>
            </div>

            <!-- TABLE -->
            <div class="card">
                <div style="padding:15px; border-bottom:1px solid var(--border-color);">
                    <h4 style="margin:0;"><i class="fas fa-table"></i> All Wastage Records</h4>
                </div>
                <div style="overflow:auto;">
                    <table class="table" style="margin-bottom:0;">
                        <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>
                            ${wastageData.map(item => {
                                const typeBadge = item.type === 'expiry' ? '<span class="badge danger">EXPIRED</span>' :
                                               item.type === 'spoilage' ? '<span class="badge warning">SPOILAGE</span>' :
                                               item.type === 'wastage' ? '<span class="badge info">WASTAGE</span>' :
                                               '<span class="badge secondary">RECALL</span>';
                                const normalizedStatus = String(item.status || '').toLowerCase().trim();
                                const statusBadge = normalizedStatus === 'verified' ? '<span class="badge success">VERIFIED</span>' :
                                                 normalizedStatus === 'disposed' ? '<span class="badge info">DISPOSED</span>' :
                                                 normalizedStatus === 'documented' ? '<span class="badge secondary">DOCUMENTED</span>' :
                                                 '<span class="badge warning">PENDING</span>';
                                return `<tr>
                                    <td>${new Date(item.created_at).toLocaleDateString()}</td>
                                    <td><strong>${escapeHtml(item.ingredient_name)}</strong></td>
                                    <td>${typeBadge}</td>
                                    <td>${parseFloat(item.quantity).toFixed(2)} ${item.unit}</td>
                                    <td>${escapeHtml(item.reason)}</td>
                                    <td><strong>₹${parseFloat(item.cost_impact || 0).toFixed(2)}</strong></td>
                                    <td>${statusBadge}</td>
                                </tr>`;
                            }).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
        `;

        // Render charts
        setTimeout(() => {
            renderWastageCharts(wasteByType, costByType, topWasted);
            applyResponsiveStyles('#reportContainer');
        }, 100);
    }

    function renderWastageCharts(wasteByType, costByType, topWasted) {
        // Wastage Type Chart (Pie)
        const typeCtx = document.getElementById('wastageTypeChart');
        if (typeCtx) {
            const chart = new Chart(typeCtx, {
                type: 'pie',
                data: {
                    labels: Object.keys(wasteByType),
                    datasets: [{
                        data: Object.values(wasteByType),
                        backgroundColor: ['#ef4444', '#f59e0b', '#3b82f6', '#8b5cf6'],
                        borderColor: '#fff',
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { position: 'bottom' },
                        tooltip: { callbacks: { label: ctx => `${ctx.label}: ${ctx.parsed} units` } }
                    }
                }
            });
            reportCharts.push(chart);
        }

        // Top Wasted Chart (Bar)
        const topCtx = document.getElementById('topWastedChart');
        if (topCtx) {
            const chart = new Chart(topCtx, {
                type: 'bar',
                data: {
                    labels: topWasted.map(item => item.name.substring(0, 15)),
                    datasets: [{
                        label: 'Cost Impact (₹)',
                        data: topWasted.map(item => item.cost),
                        backgroundColor: '#ef4444',
                        borderColor: '#dc2626',
                        borderWidth: 1
                    }]
                },
                options: {
                    indexAxis: 'y',
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: { legend: { display: false } },
                    scales: { x: { beginAtZero: true } }
                }
            });
            reportCharts.push(chart);
        }

        // Cost by Type Chart (Doughnut)
        const costCtx = document.getElementById('costByTypeChart');
        if (costCtx) {
            const chart = new Chart(costCtx, {
                type: 'doughnut',
                data: {
                    labels: Object.keys(costByType),
                    datasets: [{
                        data: Object.values(costByType),
                        backgroundColor: ['#dc2626', '#d97706', '#1d4ed8', '#7c3aed'],
                        borderColor: '#fff',
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { position: 'bottom' },
                        tooltip: { callbacks: { label: ctx => `₹${ctx.parsed}` } }
                    }
                }
            });
            reportCharts.push(chart);
        }
    }

    async function loadExpiryReport() {
        const container = document.getElementById('reportContainer');
        container.style.textAlign = 'left';
        container.style.padding = '20px';
        container.innerHTML = `
            <div style="text-align:center; padding: 30px; color: var(--text-secondary);">
                <i class="fas fa-spinner fa-spin"></i> Loading expiry report...
            </div>
        `;

        try {
            const response = await fetch('../backend/store_keeper_api.php?action=get_expiry_tracking', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            const rawText = await response.text();
            let data;
            try {
                data = JSON.parse(rawText);
            } catch (parseError) {
                throw new Error(`Invalid JSON response`);
            }

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

            const expiryData = Array.isArray(data.data) ? data.data : [];
            renderExpiryReport(expiryData);
        } catch (error) {
            destroyReportCharts();
            container.innerHTML = `
                <div style="text-align:center; padding: 30px; color: #ef4444;">
                    <i class="fas fa-exclamation-triangle"></i> ${escapeHtml(error.message || 'Failed to load expiry report')}
                </div>
            `;
        }
    }

    function renderExpiryReport(expiryData) {
        const container = document.getElementById('reportContainer');

        // Categorize items
        const expired = expiryData.filter(item => item.days_to_expiry < 0);
        const expiringSoon = expiryData.filter(item => item.days_to_expiry >= 0 && item.days_to_expiry <= 7);
        const expiringLater = expiryData.filter(item => item.days_to_expiry > 7 && item.days_to_expiry <= 30);
        const safeTillMonthEnd = expiryData.filter(item => item.days_to_expiry > 30 && item.days_to_expiry < 99999);
        const noExpiryDate = expiryData.filter(item => item.days_to_expiry >= 99999);

        // Expiry distribution (only items with expiry dates)
        const expiryTrend = {};
        expiryData.forEach(item => {
            if (item.expiry_date && item.expiry_date !== '0000-00-00') {
                const expiryDate = new Date(item.expiry_date);
                const monthYear = expiryDate.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
                expiryTrend[monthYear] = (expiryTrend[monthYear] || 0) + 1;
            }
        });

        container.innerHTML = `
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
                <h2 style="margin:0;"><i class="fas fa-calendar-times"></i> Expiry Management Report</h2>
                <button class="btn btn-secondary" onclick="loadExpiryReport()">
                    <i class="fas fa-rotate"></i> Refresh
                </button>
            </div>

            <!-- KEY METRICS -->
            <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap:15px; margin-bottom:20px;">
                <div class="card" style="padding:20px; border-left:4px solid #ef4444;">
                    <div style="font-size:13px; color:var(--text-secondary); margin-bottom:8px;">🔴 Expired Items</div>
                    <div style="font-size:28px; font-weight:700; color:#ef4444;">${expired.length}</div>
                </div>
                <div class="card" style="padding:20px; border-left:4px solid #f59e0b;">
                    <div style="font-size:13px; color:var(--text-secondary); margin-bottom:8px;">🟡 Expiring This Week</div>
                    <div style="font-size:28px; font-weight:700; color:#f59e0b;">${expiringSoon.length}</div>
                </div>
                <div class="card" style="padding:20px; border-left:4px solid #3b82f6;">
                    <div style="font-size:13px; color:var(--text-secondary); margin-bottom:8px;">🔵 Expiring This Month</div>
                    <div style="font-size:28px; font-weight:700; color:#3b82f6;">${expiringLater.length}</div>
                </div>
                <div class="card" style="padding:20px; border-left:4px solid #10b981;">
                    <div style="font-size:13px; color:var(--text-secondary); margin-bottom:8px;">✅ Safe Stock</div>
                    <div style="font-size:28px; font-weight:700; color:#10b981;">${safeTillMonthEnd.length + noExpiryDate.length}</div>
                </div>
            </div>

            <!-- CHARTS -->
            <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap:15px; margin-bottom:20px;">
                <div class="card" style="padding:15px; height:350px;">
                    <h4 style="margin:0 0 15px 0;"><i class="fas fa-chart-doughnut"></i> Expiry Status Breakdown</h4>
                    <div style="position:relative; height:300px;">
                        <canvas id="expiryStatusChart"></canvas>
                    </div>
                </div>
                <div class="card" style="padding:15px; height:350px;">
                    <h4 style="margin:0 0 15px 0;"><i class="fas fa-chart-line"></i> Items by Expiry Month</h4>
                    <div style="position:relative; height:300px;">
                        <canvas id="expiryTrendChart"></canvas>
                    </div>
                </div>
            </div>

            <!-- CRITICAL ITEMS TABLE -->
            ${expired.length > 0 ? `
            <div class="card" style="margin-bottom:20px; border-top:4px solid #ef4444;">
                <div style="padding:15px; background:#fef2f2; border-bottom:1px solid #fca5a5;">
                    <h4 style="margin:0; color:#dc2626;"><i class="fas fa-skull-crossbones"></i> EXPIRED ITEMS (${expired.length})</h4>
                </div>
                <div style="overflow:auto;">
                    <table class="table" style="margin-bottom:0;">
                        <thead>
                            <tr>
                                <th>Ingredient</th>
                                <th>Batch</th>
                                <th>Quantity</th>
                                <th>Expiry Date</th>
                                <th>Days Overdue</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${expired.map(item => `<tr style="background:#fef2f2;">
                                <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>${item.expiry_date}</td>
                                <td><span class="badge danger">${Math.abs(item.days_to_expiry)} days</span></td>
                            </tr>`).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
            ` : ''}

            <!-- SAFE INGREDIENTS TABLE (WITH EXPIRY DATES) -->
            ${safeTillMonthEnd.length > 0 ? `
            <div class="card" style="margin-bottom:20px; border-top:4px solid #10b981;">
                <div style="padding:15px; background:#f0fdf4; border-bottom:1px solid #86efac;">
                    <h4 style="margin:0; color:#16a34a;"><i class="fas fa-shield-alt"></i> SAFE INGREDIENTS (${safeTillMonthEnd.length})</h4>
                </div>
                <div style="overflow:auto;">
                    <table class="table" style="margin-bottom:0;">
                        <thead>
                            <tr>
                                <th>Ingredient</th>
                                <th>Batch #</th>
                                <th>Current Stock</th>
                                <th>Expiry Date</th>
                                <th>Days Left</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${safeTillMonthEnd.map(item => `<tr style="background:#f0fdf4;">
                                <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>${item.expiry_date}</td>
                                <td><span class="badge success">${item.days_to_expiry} days</span></td>
                                <td><span class="badge success">SAFE</span></td>
                            </tr>`).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
            ` : ''}

            <!-- NON-PERISHABLE ITEMS TABLE -->
            ${noExpiryDate.length > 0 ? `
            <div class="card" style="margin-bottom:20px; border-top:4px solid #8b5cf6;">
                <div style="padding:15px; background:#faf5ff; border-bottom:1px solid #ddd6fe;">
                    <h4 style="margin:0; color:#6d28d9;"><i class="fas fa-infinity"></i> NON-PERISHABLE ITEMS (${noExpiryDate.length})</h4>
                </div>
                <div style="overflow:auto;">
                    <table class="table" style="margin-bottom:0;">
                        <thead>
                            <tr>
                                <th>Ingredient</th>
                                <th>Batch #</th>
                                <th>Current Stock</th>
                                <th>Type</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${noExpiryDate.map(item => `<tr style="background:#faf5ff;">
                                <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>${item.is_perishable === 1 || item.is_perishable === '1' ? '🔴 Perishable (No Date Set)' : '✅ Non-Perishable'}</td>
                                <td><span class="badge success">SAFE</span></td>
                            </tr>`).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
            ` : ''}

            <!-- ALL ITEMS TABLE -->
            <div class="card">
                <div style="padding:15px; border-bottom:1px solid var(--border-color);">
                    <h4 style="margin:0;"><i class="fas fa-table"></i> Complete Expiry Tracking</h4>
                </div>
                <div style="overflow:auto;">
                    <table class="table" style="margin-bottom:0;">
                        <thead>
                            <tr>
                                <th>Ingredient</th>
                                <th>Batch #</th>
                                <th>Quantity</th>
                                <th>Expiry Date</th>
                                <th>Days Left</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${expiryData.map(item => {
                                const daysLeft = item.days_to_expiry;
                                const isNoExpiry = daysLeft >= 99999;
                                const statusClass = daysLeft < 0 ? 'danger' : daysLeft < 7 ? 'warning' : daysLeft < 30 ? 'info' : 'success';
                                const statusLabel = daysLeft < 0 ? 'EXPIRED' : daysLeft < 7 ? 'EXPIRING SOON' : daysLeft < 30 ? 'THIS MONTH' : isNoExpiry ? 'NO EXPIRY' : 'SAFE';
                                const expiryDisplay = isNoExpiry ? '∞ (No Expiry)' : item.expiry_date;
                                const daysDisplay = isNoExpiry ? '∞' : (daysLeft < 0 ? '-' + Math.abs(daysLeft) : daysLeft) + ' days';
                                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>${expiryDisplay}</td>
                                    <td>${daysDisplay}</td>
                                    <td><span class="badge ${statusClass}">${statusLabel}</span></td>
                                </tr>`;
                            }).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
        `;

        // Render charts
        setTimeout(() => {
            renderExpiryCharts(expired, expiringSoon, expiringLater, safeTillMonthEnd, noExpiryDate, expiryTrend);
            applyResponsiveStyles('#reportContainer');
        }, 100);
    }

    function renderExpiryCharts(expired, expiringSoon, expiringLater, safeTillMonthEnd, noExpiryDate, expiryTrend) {
        // Status Breakdown (Pie)
        const statusCtx = document.getElementById('expiryStatusChart');
        if (statusCtx) {
            const chart = new Chart(statusCtx, {
                type: 'doughnut',
                data: {
                    labels: ['Expired', 'Expiring This Week', 'Expiring This Month', 'Safe (With Expiry)', 'Non-Perishable'],
                    datasets: [{
                        data: [expired.length, expiringSoon.length, expiringLater.length, safeTillMonthEnd.length, noExpiryDate.length],
                        backgroundColor: ['#ef4444', '#f59e0b', '#3b82f6', '#10b981', '#8b5cf6'],
                        borderColor: '#fff',
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { position: 'bottom' },
                        tooltip: { callbacks: { label: ctx => `${ctx.label}: ${ctx.parsed} items` } }
                    }
                }
            });
            reportCharts.push(chart);
        }

        // Expiry Trend (Line)
        const trendCtx = document.getElementById('expiryTrendChart');
        if (trendCtx) {
            const trendLabels = Object.keys(expiryTrend).length > 0 ? Object.keys(expiryTrend) : ['No Data'];
            const trendData = Object.keys(expiryTrend).length > 0 ? Object.values(expiryTrend) : [0];
            const chart = new Chart(trendCtx, {
                type: 'line',
                data: {
                    labels: trendLabels,
                    datasets: [{
                        label: 'Items Expiring',
                        data: trendData,
                        borderColor: '#f59e0b',
                        backgroundColor: 'rgba(245, 158, 11, 0.1)',
                        tension: 0.4,
                        fill: true,
                        pointBackgroundColor: '#f59e0b',
                        pointBorderColor: '#fff',
                        pointRadius: 5
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: { legend: { position: 'bottom' } },
                    scales: { y: { beginAtZero: true } }
                }
            });
            reportCharts.push(chart);
        }
    }

    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'
                }).then(() => {
                    window.location.href = 'index.php';
                });
            }
        });
    }

    // RESPONSIVE BEHAVIOR
    window.addEventListener('resize', () => {
        applyResponsiveStyles('#reportContainer');
    });

    // Initial responsive setup
    document.addEventListener('DOMContentLoaded', () => {
        applyResponsiveStyles('#reportContainer');
    });
</script>

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