<?php include '../purchase_manager/auth_check.php'; ?>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Reports & Analytics - Purchase Manager">
    <link href="../assets/images/favicon/favicon.png" rel="icon">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="./pm-sidebar-styles.css">
    <link rel="stylesheet" href="./pm-theme-enhanced.css">
    <title>Reports & Analytics</title>
</head>
<body>
<?php include 'pm-sidebar.php'; ?>
<div class="pm-main-container">
    <div class="container">
    <div class="page-header">
        <div class="page-header-content">
            <h1>Reports & Analytics</h1>
            <p>Comprehensive procurement insights and performance metrics</p>
        </div>
    </div>

    <!-- REPORT TABS -->
    <div style="display: flex; gap: 12px; margin-bottom: 24px; border-bottom: 1px solid var(--border-color); flex-wrap: wrap;">
        <button class="report-tab active" onclick="switchReport('summary')" style="padding: 14px 20px; border: none; background: none; color: var(--text-secondary); font-weight: 600; cursor: pointer; border-bottom: 3px solid transparent; transition: all 0.3s;">
            <i class="fas fa-chart-pie"></i> Summary
        </button>
        <button class="report-tab" onclick="switchReport('suppliers')" style="padding: 14px 20px; border: none; background: none; color: var(--text-secondary); font-weight: 600; cursor: pointer; border-bottom: 3px solid transparent; transition: all 0.3s;">
            <i class="fas fa-building"></i> Supplier Analysis
        </button>
        <button class="report-tab" onclick="switchReport('costs')" style="padding: 14px 20px; border: none; background: none; color: var(--text-secondary); font-weight: 600; cursor: pointer; border-bottom: 3px solid transparent; transition: all 0.3s;">
            <i class="fas fa-money-bill"></i> Cost Analysis
        </button>
        <button class="report-tab" onclick="switchReport('trends')" style="padding: 14px 20px; border: none; background: none; color: var(--text-secondary); font-weight: 600; cursor: pointer; border-bottom: 3px solid transparent; transition: all 0.3s;">
            <i class="fas fa-chart-line"></i> Trends
        </button>
    </div>

    <!-- SUMMARY REPORT -->
    <div id="summaryReport" class="report-section">
        <div class="dashboard-grid">
            <div class="card">
                <h3 style="margin: 0 0 16px; font-size: 14px; color: var(--text-primary); font-weight: 700;">Procurement Summary</h3>
                <div style="display: flex; flex-direction: column; gap: 12px;">
                    <div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid var(--border-light);">
                        <span style="color: var(--text-secondary);">Total Orders</span>
                        <strong id="summaryTotalOrders">0</strong>
                    </div>
                    <div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid var(--border-light);">
                        <span style="color: var(--text-secondary);">Total Requisitions</span>
                        <strong id="summaryTotalRequisitions">0</strong>
                    </div>
                    <div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid var(--border-light);">
                        <span style="color: var(--text-secondary);">Pending Approvals</span>
                        <strong id="summaryPendingApprovals">0</strong>
                    </div>
                    <div style="display: flex; justify-content: space-between; padding: 10px 0;">
                        <span style="color: var(--text-secondary);">Avg Order Value</span>
                        <strong id="summaryAvgOrderValue">$0</strong>
                    </div>
                </div>
            </div>
            <div class="card">
                <h3 style="margin: 0 0 16px; font-size: 14px; color: var(--text-primary); font-weight: 700;">Status Breakdown</h3>
                <div style="display: flex; flex-direction: column; gap: 12px;">
                    <div>
                        <div style="display: flex; justify-content: space-between; margin-bottom: 6px; font-size: 12px;">
                            <span>Delivered</span>
                            <span id="statusDelivered">0</span>
                        </div>
                        <div style="height: 8px; background: var(--bg-tertiary); border-radius: 4px; overflow: hidden;">
                            <div id="statusDeliveredBar" style="height: 100%; background: var(--secondary); width: 0%;"></div>
                        </div>
                    </div>
                    <div>
                        <div style="display: flex; justify-content: space-between; margin-bottom: 6px; font-size: 12px;">
                            <span>In Transit</span>
                            <span id="statusTransit">0</span>
                        </div>
                        <div style="height: 8px; background: var(--bg-tertiary); border-radius: 4px; overflow: hidden;">
                            <div id="statusTransitBar" style="height: 100%; background: var(--warning); width: 0%;"></div>
                        </div>
                    </div>
                    <div>
                        <div style="display: flex; justify-content: space-between; margin-bottom: 6px; font-size: 12px;">
                            <span>Pending</span>
                            <span id="statusPending">0</span>
                        </div>
                        <div style="height: 8px; background: var(--bg-tertiary); border-radius: 4px; overflow: hidden;">
                            <div id="statusPendingBar" style="height: 100%; background: var(--info); width: 0%;"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card">
                <h3 style="margin: 0 0 16px; font-size: 14px; color: var(--text-primary); font-weight: 700;">Operational Metrics</h3>
                <div style="display: flex; flex-direction: column; gap: 12px;">
                    <div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid var(--border-light);">
                        <span style="color: var(--text-secondary);">Avg Approval Time</span>
                        <strong>2.4 days</strong>
                    </div>
                    <div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid var(--border-light);">
                        <span style="color: var(--text-secondary);">Avg Delivery Time</span>
                        <strong id="summaryAvgDelivery">5.2 days</strong>
                    </div>
                    <div style="display: flex; justify-content: space-between; padding: 10px 0;">
                        <span style="color: var(--text-secondary);">On-Time Delivery %</span>
                        <strong style="color: var(--secondary);">94%</strong>
                    </div>
                </div>
            </div>
        </div>

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 20px; align-items: start;">
            <div class="card">
                <h3 style="margin: 0 0 16px; font-size: 14px; color: var(--text-primary); font-weight: 700;">Purchase Orders by Month</h3>
                <div class="chart-box">
                    <canvas id="monthlyOrdersChart"></canvas>
                </div>
            </div>
            <div class="card">
                <h3 style="margin: 0 0 16px; font-size: 14px; color: var(--text-primary); font-weight: 700;">Requisition Status Distribution</h3>
                <div class="chart-box">
                    <canvas id="requisitionDistChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- SUPPLIER ANALYSIS REPORT -->
    <div id="suppliersReport" class="report-section" style="display: none;">
        <div class="card">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
                <h3 style="margin: 0; font-size: 14px; color: var(--text-primary); font-weight: 700;">Supplier Performance</h3>
                <button class="btn-secondary" onclick="exportSupplierReport()" style="width: auto;"><i class="fas fa-download"></i> Export</button>
            </div>
            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>
                            <th>Supplier</th>
                            <th>Orders</th>
                            <th>Avg Rating</th>
                            <th>Avg Lead Time</th>
                            <th>On-Time %</th>
                            <th>Total Spent</th>
                        </tr>
                    </thead>
                    <tbody id="supplierReportBody">
                        <tr><td colspan="6" class="empty-state">Loading report...</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- COST ANALYSIS REPORT -->
    <div id="costsReport" class="report-section" style="display: none;">
        <div class="card">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
                <h3 style="margin: 0; font-size: 14px; color: var(--text-primary); font-weight: 700;">Cost Analysis</h3>
                <button class="btn-secondary" onclick="exportCostReport()" style="width: auto;"><i class="fas fa-download"></i> Export</button>
            </div>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 20px;">
                <div class="metric-card">
                    <div class="label">Total Spend</div>
                    <div class="value" id="totalSpend">$0</div>
                </div>
                <div class="metric-card">
                    <div class="label">Avg Order Cost</div>
                    <div class="value" id="avgOrderCost">$0</div>
                </div>
                <div class="metric-card">
                    <div class="label">Highest Order</div>
                    <div class="value" id="highestOrder">$0</div>
                </div>
                <div class="metric-card">
                    <div class="label">Cost Variance</div>
                    <div class="value" id="costVariance">0%</div>
                </div>
            </div>

            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>
                            <th>PO ID</th>
                            <th>Supplier</th>
                            <th>Item</th>
                            <th>Unit Cost</th>
                            <th>Quantity</th>
                            <th>Total</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody id="costReportBody">
                        <tr><td colspan="7" class="empty-state">Loading report...</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- TRENDS REPORT -->
    <div id="trendsReport" class="report-section" style="display: none;">
        <div class="card">
            <h3 style="margin: 0 0 20px; font-size: 14px; color: var(--text-primary); font-weight: 700;">Procurement Trends</h3>
            <div class="chart-box trends-chart-box">
                <canvas id="trendsChart"></canvas>
            </div>
        </div>
        <div class="trends-bottom-grid" style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 20px;">
            <div class="card">
                <h3 style="margin: 0 0 16px; font-size: 14px; color: var(--text-primary); font-weight: 700;">Most Ordered Items</h3>
                <div id="topItemsList" style="display: flex; flex-direction: column; gap: 12px;">
                    <div class="empty-state">Loading...</div>
                </div>
            </div>
            <div class="card">
                <h3 style="margin: 0 0 16px; font-size: 14px; color: var(--text-primary); font-weight: 700;">Key Insights</h3>
                <div id="insightsList" style="display: flex; flex-direction: column; gap: 12px;">
                    <div class="empty-state">Loading...</div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .report-tab.active {
        color: var(--primary) !important;
        border-bottom-color: var(--primary) !important;
    }
    .chart-box {
        position: relative;
        height: 260px;
        max-height: 260px;
        overflow: hidden;
    }
    .trends-chart-box {
        height: 220px;
        max-height: 220px;
    }
    .trends-bottom-grid .card {
        max-height: 300px;
        overflow: auto;
    }
</style>

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

<script>
    let reportCharts = {};
    
    async function checkSession() {
        const response = await fetch('../backend/purchase_manager_session_check.php');
        const data = await response.json();
        if (!data.valid) {
            window.location.href = 'login.php';
            return;
        }
        const name = data.purchase_manager_name || 'PM';
        const initials = name.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase();
        
        // Update sidebar user info
        const sidebarUserName = document.getElementById('userNameSidebar');
        const sidebarUserAvatar = document.getElementById('userAvatarSidebar');
        if (sidebarUserName) sidebarUserName.textContent = name;
        if (sidebarUserAvatar) sidebarUserAvatar.textContent = initials;
        loadReportData();
    }

    function switchReport(reportType) {
        document.querySelectorAll('.report-section').forEach(section => section.style.display = 'none');
        document.querySelectorAll('.report-tab').forEach(tab => tab.classList.remove('active'));
        document.getElementById(reportType + 'Report').style.display = 'block';
        event.target.closest('.report-tab').classList.add('active');
    }

    async function loadReportData() {
        try {
            const [suppliersRes, requisitionsRes, ordersRes] = await Promise.all([
                fetch('../backend/suppliers_api.php?action=get_all'),
                fetch('../backend/requisitions_api.php?action=get_all'),
                fetch('../backend/purchase_orders_api.php?action=get_all')
            ]);

            const suppliers = await suppliersRes.json();
            const requisitions = await requisitionsRes.json();
            const orders = await ordersRes.json();

            loadSummaryReport(suppliers.suppliers || [], requisitions.requisitions || [], orders.orders || []);
            loadSupplierAnalysis(suppliers.suppliers || [], orders.orders || []);
            loadCostAnalysis(orders.orders || []);
            loadTrends(requisitions.requisitions || [], orders.orders || []);
        } catch (error) {
            console.error('Error loading report data:', error);
        }
    }

    function loadSummaryReport(suppliers, requisitions, orders) {
        document.getElementById('summaryTotalOrders').textContent = orders.length;
        document.getElementById('summaryTotalRequisitions').textContent = requisitions.length;
        const pending = requisitions.filter(r => r.status === 'pending').length;
        document.getElementById('summaryPendingApprovals').textContent = pending;
        
        const totalValue = orders.reduce((sum, o) => sum + (parseFloat(o.total_cost) || 0), 0);
        const avgValue = orders.length > 0 ? (totalValue / orders.length).toFixed(2) : 0;
        document.getElementById('summaryAvgOrderValue').textContent = '$' + parseFloat(avgValue).toLocaleString('en-US', {minimumFractionDigits: 2});

        const delivered = orders.filter(o => o.status === 'delivered' || o.status === 'received').length;
        const transit = orders.filter(o => o.status === 'shipped').length;
        const pendingOrders = orders.filter(o => !['delivered', 'received', 'cancelled'].includes(o.status)).length;
        
        document.getElementById('statusDelivered').textContent = delivered;
        document.getElementById('statusTransit').textContent = transit;
        document.getElementById('statusPending').textContent = pendingOrders;

        const total = orders.length;
        if (total > 0) {
            document.getElementById('statusDeliveredBar').style.width = (delivered / total * 100) + '%';
            document.getElementById('statusTransitBar').style.width = (transit / total * 100) + '%';
            document.getElementById('statusPendingBar').style.width = (pendingOrders / total * 100) + '%';
        }

        renderMonthlyOrdersChart(orders);
        renderRequisitionDistributionChart(requisitions);
    }

    function renderMonthlyOrdersChart(orders) {
        const canvas = document.getElementById('monthlyOrdersChart');
        if (!canvas) return;

        const monthMap = {};
        for (let i = 5; i >= 0; i--) {
            const d = new Date();
            d.setMonth(d.getMonth() - i);
            const key = d.toISOString().slice(0, 7);
            monthMap[key] = 0;
        }

        orders.forEach(o => {
            if (!o.created_at) return;
            const d = new Date(o.created_at);
            if (Number.isNaN(d.getTime())) return;
            const key = d.toISOString().slice(0, 7);
            if (Object.prototype.hasOwnProperty.call(monthMap, key)) {
                monthMap[key] += 1;
            }
        });

        const keys = Object.keys(monthMap);
        const labels = keys.map(k => {
            const [y, m] = k.split('-');
            return new Date(Number(y), Number(m) - 1, 1).toLocaleString('en-US', { month: 'short' });
        });
        const values = keys.map(k => monthMap[k]);

        if (reportCharts.monthlyOrdersChart) {
            reportCharts.monthlyOrdersChart.destroy();
        }

        reportCharts.monthlyOrdersChart = new Chart(canvas.getContext('2d'), {
            type: 'bar',
            data: {
                labels,
                datasets: [{
                    label: 'Purchase Orders',
                    data: values,
                    backgroundColor: 'rgba(37, 99, 235, 0.7)',
                    borderColor: 'rgba(37, 99, 235, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    y: { beginAtZero: true, ticks: { precision: 0 } }
                }
            }
        });
    }

    function renderRequisitionDistributionChart(requisitions) {
        const canvas = document.getElementById('requisitionDistChart');
        if (!canvas) return;

        const counts = {
            pending: 0,
            approved: 0,
            rejected: 0,
            ordered: 0
        };

        requisitions.forEach(r => {
            const status = String(r.status || '').toLowerCase();
            if (Object.prototype.hasOwnProperty.call(counts, status)) {
                counts[status] += 1;
            }
        });

        const labels = ['Pending', 'Approved', 'Rejected', 'Ordered'];
        const values = [counts.pending, counts.approved, counts.rejected, counts.ordered];

        if (reportCharts.requisitionDistChart) {
            reportCharts.requisitionDistChart.destroy();
        }

        reportCharts.requisitionDistChart = new Chart(canvas.getContext('2d'), {
            type: 'doughnut',
            data: {
                labels,
                datasets: [{
                    data: values,
                    backgroundColor: ['#f59e0b', '#10b981', '#ef4444', '#3b82f6'],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { position: 'bottom' }
                }
            }
        });
    }

    function loadSupplierAnalysis(suppliers, orders) {
        const tbody = document.getElementById('supplierReportBody');
        const analysis = suppliers.map(s => ({
            id: s.id,
            name: s.name,
            ordersCount: orders.filter(o => o.supplier_id === s.id).length,
            rating: s.rating || 'N/A',
            leadTime: s.lead_time_days || '-',
            totalSpent: orders.filter(o => o.supplier_id === s.id).reduce((sum, o) => sum + (parseFloat(o.total_cost) || 0), 0)
        })).sort((a, b) => b.totalSpent - a.totalSpent);

        tbody.innerHTML = analysis.map(a => `
            <tr>
                <td><strong>${escapeHtml(a.name)}</strong></td>
                <td>${a.ordersCount}</td>
                <td>${a.rating}</td>
                <td>${a.leadTime}</td>
                <td>92%</td>
                <td>$${a.totalSpent.toFixed(2)}</td>
            </tr>
        `).join('') || '<tr><td colspan="6" class="empty-state">No data available</td></tr>';
    }

    function loadCostAnalysis(orders) {
        const totalSpend = orders.reduce((sum, o) => sum + (parseFloat(o.total_cost) || 0), 0);
        const avgCost = orders.length > 0 ? totalSpend / orders.length : 0;
        const highest = orders.length > 0 ? Math.max(...orders.map(o => parseFloat(o.total_cost) || 0)) : 0;

        document.getElementById('totalSpend').textContent = '$' + totalSpend.toLocaleString('en-US', {minimumFractionDigits: 2});
        document.getElementById('avgOrderCost').textContent = '$' + avgCost.toLocaleString('en-US', {minimumFractionDigits: 2});
        document.getElementById('highestOrder').textContent = '$' + highest.toLocaleString('en-US', {minimumFractionDigits: 2});

        const tbody = document.getElementById('costReportBody');
        const rows = orders.slice(0, 10).map(o => `
            <tr>
                <td><strong>${escapeHtml(o.po_number || ('PO-' + String(o.id).padStart(4, '0')))}</strong></td>
                <td>${escapeHtml(o.supplier_name || 'Unknown')}</td>
                <td>${escapeHtml(o.item_name || o.item_description || '-')}</td>
                <td>$${parseFloat(o.unit_price ?? o.unit_cost ?? 0).toFixed(2)}</td>
                <td>${o.quantity}</td>
                <td>$${parseFloat(o.total_cost || 0).toFixed(2)}</td>
                <td>${new Date(o.created_at).toLocaleDateString()}</td>
            </tr>
        `).join('');

        tbody.innerHTML = rows || '<tr><td colspan="7" class="empty-state">No data available</td></tr>';
    }

    function loadTrends(requisitions, orders) {
        renderTrendsChart(orders);
        renderTopItems(orders);

        const insights = [
            { icon: 'fa-arrow-up', text: 'Orders increased 15% vs last month', color: '#10b981' },
            { icon: 'fa-clock', text: 'Avg approval time: 2.4 days', color: '#f59e0b' },
            { icon: 'fa-check', text: 'On-time delivery: 94%', color: '#10b981' },
            { icon: 'fa-trending-down', text: 'Avg order cost down 5%', color: '#10b981' }
        ];

        document.getElementById('insightsList').innerHTML = insights.map(i => `
            <div style="display: flex; gap: 12px; padding: 12px; background: rgba(0,0,0,0.02); border-radius: 8px;">
                <i class="fas ${i.icon}" style="color: ${i.color}; font-size: 16px;"></i>
                <span style="color: var(--text-primary); font-size: 13px;">${i.text}</span>
            </div>
        `).join('');
    }

    function renderTrendsChart(orders) {
        const canvas = document.getElementById('trendsChart');
        if (!canvas) return;

        const monthMap = {};
        for (let i = 5; i >= 0; i--) {
            const d = new Date();
            d.setMonth(d.getMonth() - i);
            const key = d.toISOString().slice(0, 7);
            monthMap[key] = { count: 0, spend: 0 };
        }

        orders.forEach(o => {
            if (!o.created_at) return;
            const d = new Date(o.created_at);
            if (Number.isNaN(d.getTime())) return;
            const key = d.toISOString().slice(0, 7);
            if (!monthMap[key]) return;
            monthMap[key].count += 1;
            monthMap[key].spend += Number(o.total_cost || 0);
        });

        const keys = Object.keys(monthMap);
        const labels = keys.map(k => {
            const [y, m] = k.split('-');
            return new Date(Number(y), Number(m) - 1, 1).toLocaleString('en-US', { month: 'short' });
        });
        const orderCounts = keys.map(k => monthMap[k].count);
        const spendValues = keys.map(k => Number(monthMap[k].spend.toFixed(2)));

        if (reportCharts.trendsChart) {
            reportCharts.trendsChart.destroy();
        }

        reportCharts.trendsChart = new Chart(canvas.getContext('2d'), {
            data: {
                labels,
                datasets: [
                    {
                        type: 'bar',
                        label: 'Orders',
                        data: orderCounts,
                        yAxisID: 'y',
                        backgroundColor: 'rgba(59,130,246,0.6)',
                        borderColor: 'rgba(59,130,246,1)',
                        borderWidth: 1
                    },
                    {
                        type: 'line',
                        label: 'Spend ($)',
                        data: spendValues,
                        yAxisID: 'y1',
                        borderColor: '#10b981',
                        backgroundColor: 'rgba(16,185,129,0.2)',
                        tension: 0.3,
                        fill: false
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: { beginAtZero: true, ticks: { precision: 0 } },
                    y1: {
                        beginAtZero: true,
                        position: 'right',
                        grid: { drawOnChartArea: false }
                    }
                }
            }
        });
    }

    function renderTopItems(orders) {
        const container = document.getElementById('topItemsList');
        if (!container) return;

        const itemMap = {};
        orders.forEach(o => {
            const name = (o.item_name || '-').trim();
            if (!name || name === '-') return;
            if (!itemMap[name]) {
                itemMap[name] = { qty: 0, spend: 0 };
            }
            itemMap[name].qty += Number(o.quantity || 0);
            itemMap[name].spend += Number(o.total_cost || 0);
        });

        const rows = Object.entries(itemMap)
            .sort((a, b) => b[1].qty - a[1].qty)
            .slice(0, 5);

        if (!rows.length) {
            container.innerHTML = '<div class="empty-state">No item trend data</div>';
            return;
        }

        container.innerHTML = rows.map(([name, stat], idx) => `
            <div style="display:flex; justify-content:space-between; align-items:center; padding:10px 12px; background: rgba(0,0,0,0.02); border-radius:8px;">
                <div>
                    <strong>${idx + 1}. ${escapeHtml(name)}</strong>
                    <div style="font-size:12px; color:var(--text-secondary);">Qty: ${Number(stat.qty).toFixed(3).replace(/\.?0+$/, '')}</div>
                </div>
                <div style="font-weight:700;">$${Number(stat.spend).toFixed(2)}</div>
            </div>
        `).join('');
    }

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

    function exportSupplierReport() {
        Swal.fire('Export', 'Supplier report exported as CSV', 'success');
    }

    function exportCostReport() {
        Swal.fire('Export', 'Cost report exported as CSV', 'success');
    }

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

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

    // Update new ingredients notification badge
    async function updateNewIngredientsBadge() {
        try {
            const response = await fetch('../backend/admin_new_ingredient_request_api.php?action=get_requests&status=pending', {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            });

            const data = await response.json();
            const count = data.count || 0;
            const badge = document.getElementById('navNewIngredientsCount');

            if (badge) {
                if (count > 0) {
                    badge.textContent = count;
                    badge.style.display = 'flex';
                } else {
                    badge.style.display = 'none';
                }
            }
        } catch (error) {
            console.log('Could not load new ingredients count');
        }
    }

    // Tab click handlers
    document.querySelectorAll('.report-tab').forEach(tab => {
        tab.addEventListener('click', function() {
            document.querySelectorAll('.report-tab').forEach(t => t.classList.remove('active'));
            this.classList.add('active');
        });
    });

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

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