<?php include '../purchase_manager/auth_check.php'; ?>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Purchase Manager Dashboard - 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="./pm-sidebar-styles.css">
    <link rel="stylesheet" href="./pm-theme-enhanced.css">
    <title>Purchase Manager Dashboard</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>Procurement Dashboard</h1>
            <p>Real-time overview of your procurement operations</p>
        </div>
        <div class="page-actions">
            <button class="btn-primary" onclick="location.href='requisitions.php'"><i class="fas fa-circle-check"></i> Approve Requests</button>
        </div>
    </div>

    <!-- KEY METRICS -->
    <div class="metric-strip">
        <div class="metric-card">
            <div class="label">Active Suppliers</div>
            <div class="value" id="suppliersCount">0</div>
            <div class="trend" id="suppliersTrend">↑ 0% from last month</div>
        </div>
        <div class="metric-card">
            <div class="label">Pending Approval</div>
            <div class="value" id="requisitionsPendingCount">0</div>
            <div class="trend" id="pendingTrend">⏱ Needs attention</div>
        </div>
        <div class="metric-card">
            <div class="label">Awaiting Delivery</div>
            <div class="value" id="ordersTransitCount">0</div>
            <div class="trend" id="deliveryTrend">📦 In transit</div>
        </div>
        <div class="metric-card">
            <div class="label">Low Stock Items</div>
            <div class="value" id="lowStockCount">0</div>
            <div class="trend down" id="stockTrend">⚠ Alert</div>
        </div>
        <div class="metric-card">
            <div class="label">Total Suppliers</div>
            <div class="value" id="totalSuppliersCount">0</div>
            <div class="trend" id="totalSuppliersTrend">Active network</div>
        </div>
        <div class="metric-card">
            <div class="label">Open Orders</div>
            <div class="value" id="ordersOpenCount">0</div>
            <div class="trend" id="ordersTrend">In progress</div>
        </div>
    </div>

    <!-- CHARTS ROW -->
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 16px; margin-bottom: 20px; align-items: start;">
        <div class="card" style="padding: 16px;">
            <h3 style="margin: 0 0 16px; font-size: 16px; color: var(--text-primary);">Requisition Status</h3>
            <div style="position: relative; height: 150px; max-height: 150px;">
                <canvas id="requisitionChart"></canvas>
            </div>
        </div>
        <div class="card" style="padding: 16px;">
            <h3 style="margin: 0 0 16px; font-size: 16px; color: var(--text-primary);">Purchase Order Status</h3>
            <div style="position: relative; height: 150px; max-height: 150px;">
                <canvas id="poChart"></canvas>
            </div>
        </div>
    </div>

    <!-- QUICK ACTIONS -->
    <div class="dashboard-grid">
        <div class="card">
            <div class="card-icon"><i class="fas fa-file-circle-check"></i></div>
            <h3 class="card-title">Approve Requests</h3>
            <p class="card-description">Review and approve kitchen ingredient requests. Priority-based filtering available.</p>
            <a href="requisitions.php" class="card-btn"><i class="fas fa-arrow-right"></i> Go to Requisitions</a>
        </div>
        <div class="card">
            <div class="card-icon"><i class="fas fa-dolly"></i></div>
            <h3 class="card-title">Create Purchase Orders</h3>
            <p class="card-description">Create POs from approved requisitions or manually. Track delivery and receive stock.</p>
            <a href="purchase_orders.php" class="card-btn"><i class="fas fa-arrow-right"></i> Go to Orders</a>
        </div>
        <div class="card">
            <div class="card-icon"><i class="fas fa-chart-line"></i></div>
            <h3 class="card-title">Compare Prices</h3>
            <p class="card-description">Add supplier quotes and compare prices. Make data-driven supplier decisions.</p>
            <a href="cost_comparison.php" class="card-btn"><i class="fas fa-arrow-right"></i> Go to Comparison</a>
        </div>
        <div class="card">
            <div class="card-icon"><i class="fas fa-building"></i></div>
            <h3 class="card-title">Manage Suppliers</h3>
            <p class="card-description">Add vendors, track ratings, manage payment terms and lead times.</p>
            <a href="suppliers.php" class="card-btn"><i class="fas fa-arrow-right"></i> Go to Suppliers</a>
        </div>
    </div>

    <!-- RECENT ACTIVITIES & ALERTS -->
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 26px;">
        <!-- Recent Activities -->
        <div class="card">
            <h3 style="margin: 0 0 16px; font-size: 16px; color: var(--text-primary);">Recent Activities</h3>
            <div id="recentActivities" style="display: flex; flex-direction: column; gap: 12px;">
                <div style="color: var(--text-secondary); font-size: 13px; text-align: center; padding: 20px;">
                    <i class="fas fa-hourglass-end"></i> Loading activities...
                </div>
            </div>
        </div>

        <!-- Alerts & Warnings -->
        <div class="card">
            <h3 style="margin: 0 0 16px; font-size: 16px; color: var(--text-primary);">Alerts & Warnings</h3>
            <div id="alertsContainer" style="display: flex; flex-direction: column; gap: 12px;">
                <div style="color: var(--text-secondary); font-size: 13px; text-align: center; padding: 20px;">
                    <i class="fas fa-check-circle"></i> All systems operational
                </div>
            </div>
        </div>
    </div>

    <!-- TOP SUPPLIERS -->
    <div class="card">
        <h3 style="margin: 0 0 20px; font-size: 16px; color: var(--text-primary);">Top Performing Suppliers</h3>
        <div class="table-wrapper">
            <table>
                <thead>
                    <tr>
                        <th>Supplier</th>
                        <th>Rating</th>
                        <th>Orders</th>
                        <th>Avg Lead Time</th>
                        <th>Last Order</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody id="topSuppliersBody">
                    <tr><td colspan="6" class="empty-state"><i class="fas fa-spinner"></i> Loading...</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<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 requisitionChart, poChart;

    async function checkSession() {
        try {
            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;
            
            loadDashboardData();
        } catch (error) {
            console.error('Session check failed:', error);
            window.location.href = 'login.php';
        }
    }

    async function loadDashboardData() {
        try {
            // Load metrics
            const [suppliersRes, requisitionsRes, ordersRes, statsRes] = 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'),
                fetch('../backend/purchase_manager_api.php?action=get_dashboard_stats')
            ]);

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

            // Update metrics
            const suppliersList = suppliers.suppliers || [];
            const activeSuppliers = suppliersList.filter(s => s.status === 'active').length;
            document.getElementById('suppliersCount').textContent = activeSuppliers;
            document.getElementById('totalSuppliersCount').textContent = suppliersList.length;

            if (requisitions.requisitions) {
                const pending = requisitions.requisitions.filter(r => r.status === 'pending').length;
                document.getElementById('requisitionsPendingCount').textContent = pending;
            }

            if (orders.orders) {
                const transit = orders.orders.filter(o => o.status === 'shipped').length;
                const open = orders.orders.filter(o => !['delivered', 'cancelled'].includes(o.status)).length;
                document.getElementById('ordersTransitCount').textContent = transit;
                document.getElementById('ordersOpenCount').textContent = open;
            }

            if (stats && stats.success) {
                document.getElementById('lowStockCount').textContent = stats.low_stock_count || 0;
            }

            // Load charts
            loadCharts(requisitions.requisitions || [], orders.orders || []);

            // Load recent activities
            loadRecentActivities();

            // Load alerts
            loadAlerts(requisitions.requisitions || [], orders.orders || []);

            // Load top suppliers
            loadTopSuppliers(suppliersList, orders.orders || []);

        } catch (error) {
            console.error('Error loading dashboard data:', error);
        }
    }

    function loadCharts(requisitions, orders) {
        // Requisition Status Chart
        const reqStatuses = {
            'pending': 0,
            'approved': 0,
            'rejected': 0,
            'ordered': 0,
            'received': 0
        };

        requisitions.forEach(r => {
            const status = String(r.status || '').toLowerCase();
            if (reqStatuses.hasOwnProperty(status)) {
                reqStatuses[status]++;
            }
        });

        const reqCtx = document.getElementById('requisitionChart').getContext('2d');
        const reqData = [reqStatuses.pending, reqStatuses.approved, reqStatuses.rejected, reqStatuses.ordered, reqStatuses.received];
        const reqTotal = reqData.reduce((sum, n) => sum + n, 0);
        const reqLabels = reqTotal > 0 ? ['Pending', 'Approved', 'Rejected', 'Ordered', 'Received'] : ['No Requisitions'];
        const reqDataset = reqTotal > 0 ? reqData : [1];
        const reqColors = reqTotal > 0
            ? ['#f59e0b', '#10b981', '#dc2626', '#3b82f6', '#8b5cf6']
            : ['#d1d5db'];
        if (requisitionChart) requisitionChart.destroy();
        requisitionChart = new Chart(reqCtx, {
            type: 'doughnut',
            data: {
                labels: reqLabels,
                datasets: [{
                    data: reqDataset,
                    backgroundColor: reqColors,
                    borderColor: 'rgba(255, 255, 255, 0.2)',
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: { font: { size: 12 }, usePointStyle: true, padding: 15 }
                    }
                }
            }
        });

        // Purchase Order Status Chart
        const poStatuses = {
            'draft': 0,
            'confirmed': 0,
            'shipped': 0,
            'delivered': 0,
            'cancelled': 0,
            'received': 0
        };

        orders.forEach(o => {
            const status = String(o.status || '').toLowerCase();
            if (poStatuses.hasOwnProperty(status)) {
                poStatuses[status]++;
            }
        });

        const poCtx = document.getElementById('poChart').getContext('2d');
        if (poChart) poChart.destroy();
        poChart = new Chart(poCtx, {
            type: 'doughnut',
            data: {
                labels: ['Draft', 'Confirmed', 'Shipped', 'Delivered', 'Cancelled', 'Received'],
                datasets: [{
                    data: [poStatuses.draft, poStatuses.confirmed, poStatuses.shipped, poStatuses.delivered, poStatuses.cancelled, poStatuses.received],
                    backgroundColor: ['#6b7280', '#3b82f6', '#f59e0b', '#10b981', '#dc2626', '#8b5cf6'],
                    borderColor: 'rgba(255, 255, 255, 0.2)',
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: { font: { size: 12 }, usePointStyle: true, padding: 15 }
                    }
                }
            }
        });
    }

    function loadRecentActivities() {
        const activities = [
            { icon: 'fa-check-circle', text: 'New supplier added: Fresh Vegetables Co.', time: '2 hours ago', color: '#10b981' },
            { icon: 'fa-file-text', text: 'PO #2024-001 status updated to Shipped', time: '4 hours ago', color: '#3b82f6' },
            { icon: 'fa-thumbs-up', text: '5 requisitions approved and ready to order', time: '1 day ago', color: '#f59e0b' },
            { icon: 'fa-truck', text: 'Delivery received: Flour (25kg)', time: '2 days ago', color: '#10b981' },
            { icon: 'fa-star', text: 'Supplier rating updated: Quality Foods (4.8★)', time: '3 days ago', color: '#8b5cf6' }
        ];

        const container = document.getElementById('recentActivities');
        container.innerHTML = activities.map(a => `
            <div style="display: flex; gap: 12px; padding: 12px; border-radius: 8px; background: rgba(0,0,0,0.02);">
                <div style="color: ${a.color}; font-size: 18px; flex-shrink: 0;">
                    <i class="fas ${a.icon}"></i>
                </div>
                <div style="flex: 1;">
                    <div style="font-size: 13px; color: var(--text-primary); font-weight: 500;">${a.text}</div>
                    <div style="font-size: 11px; color: var(--text-light); margin-top: 4px;">${a.time}</div>
                </div>
            </div>
        `).join('');
    }

    function loadAlerts(requisitions, orders) {
        const alerts = [];

        // Pending requisitions alert
        const pending = requisitions.filter(r => r.status === 'pending').length;
        if (pending > 0) {
            alerts.push({
                type: 'warning',
                icon: 'fa-circle-exclamation',
                title: 'Pending Approvals',
                message: `${pending} requisition(s) awaiting your approval`,
                action: 'Review now'
            });
        }

        // Overdue orders alert
        const overdue = orders.filter(o => o.status === 'shipped' && o.expected_delivery_date).length;
        if (overdue > 0) {
            alerts.push({
                type: 'info',
                icon: 'fa-hourglass-end',
                title: 'In Transit',
                message: `${overdue} order(s) currently in transit`,
                action: 'Track shipments'
            });
        }

        const container = document.getElementById('alertsContainer');
        if (alerts.length === 0) {
            container.innerHTML = '<div style="color: var(--text-secondary); font-size: 13px; text-align: center; padding: 20px;"><i class="fas fa-check-circle"></i> All systems operational</div>';
        } else {
            container.innerHTML = alerts.map(a => {
                const colors = {
                    'warning': { bg: '#fef3c7', color: '#92400e', icon: '#f59e0b' },
                    'info': { bg: '#dbeafe', color: '#1e40af', icon: '#3b82f6' },
                    'danger': { bg: '#fee2e2', color: '#7f1d1d', icon: '#dc2626' }
                };
                const c = colors[a.type];
                return `
                    <div style="padding: 12px; border-radius: 8px; background: ${c.bg}; color: ${c.color};">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <i class="fas ${a.icon}" style="color: ${c.icon}; font-size: 16px;"></i>
                            <div style="flex: 1;">
                                <div style="font-weight: 600; font-size: 13px;">${a.title}</div>
                                <div style="font-size: 12px; margin-top: 2px;">${a.message}</div>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');
        }
    }
    function loadTopSuppliers(suppliers, orders) {
        const active = suppliers.filter(s => s.status === 'active')
            .sort((a, b) => (b.rating || 0) - (a.rating || 0))
            .slice(0, 5);

        const tbody = document.getElementById('topSuppliersBody');
        if (active.length === 0) {
            tbody.innerHTML = '<tr><td colspan="6" class="empty-state">No active suppliers yet</td></tr>';
            return;
        }

        const bySupplierId = new Map();
        const bySupplierName = new Map();
        (orders || []).forEach(o => {
            const sid = Number(o.supplier_id || 0);
            const sname = String(o.supplier_name || '').trim().toLowerCase();
            const createdAt = o.created_at ? new Date(o.created_at) : null;
            const validDate = createdAt instanceof Date && !Number.isNaN(createdAt.getTime());

            if (sid > 0) {
                if (!bySupplierId.has(sid)) bySupplierId.set(sid, { count: 0, lastOrder: null });
                const entry = bySupplierId.get(sid);
                entry.count += 1;
                if (validDate && (!entry.lastOrder || createdAt > entry.lastOrder)) entry.lastOrder = createdAt;
            }

            if (sname) {
                if (!bySupplierName.has(sname)) bySupplierName.set(sname, { count: 0, lastOrder: null });
                const entry = bySupplierName.get(sname);
                entry.count += 1;
                if (validDate && (!entry.lastOrder || createdAt > entry.lastOrder)) entry.lastOrder = createdAt;
            }
        });

        tbody.innerHTML = active.map(s => {
            const sid = Number(s.id || 0);
            const nameKey = String(s.name || '').trim().toLowerCase();
            const stats = (sid > 0 && bySupplierId.has(sid))
                ? bySupplierId.get(sid)
                : (bySupplierName.get(nameKey) || { count: 0, lastOrder: null });
            const lastOrderText = stats.lastOrder ? stats.lastOrder.toLocaleDateString('en-CA') : '-';

            return `
            <tr>
                <td><strong>${escapeHtml(s.name)}</strong></td>
                <td><span class="status-badge" style="background: #fed7aa; color: #92400e;">&#9733; ${s.rating || 'N/A'}</span></td>
                <td>${stats.count}</td>
                <td>${s.lead_time_days || '-'} day(s)</td>
                <td>${lastOrderText}</td>
                <td><span class="status-badge status-${s.status.toLowerCase()}">${s.status}</span></td>
            </tr>
            `;
        }).join('');
    }
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

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

        if (result.isConfirmed) {
            await fetch('../backend/purchase_manager_logout.php');
            window.location.href = 'index.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');
        }
    }

    // Update low stock notification badge
    async function updateLowStockBadge() {
        try {
            const response = await fetch('../backend/supplier_products_api.php?action=get_low_stock_ingredients', {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            });

            const data = await response.json();
            const count = data.ingredients?.length || 0;
            const badge = document.getElementById('navLowStockCount');

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

    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        checkSession();
        updateNewIngredientsBadge();
        updateLowStockBadge();
        // Update badges every 30 seconds
        setInterval(updateNewIngredientsBadge, 30000);
        setInterval(updateLowStockBadge, 30000);
    });
</script>

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