<?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="Cost Analysis - Purchase Manager">
    <link href="../assets/images/favicon/favicon.png" rel="icon">
    <link href="https://fonts.googleapis.com/css?family=Raleway:400,500,600,700,800" rel="stylesheet">
    <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>Cost Analysis</title>
    <style>
        .comparison-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(270px, 1fr));
            gap: 14px;
        }
        .comparison-card {
            background: rgba(255, 255, 255, 0.95);
            border: 1px solid #e5ecf7;
            border-radius: 14px;
            box-shadow: 0 8px 24px rgba(19, 38, 72, 0.06);
            padding: 14px;
        }
        .comparison-title { margin: 0 0 10px; font-size: 17px; color: #1b2d4e; }
        .supplier-row {
            display: flex;
            justify-content: space-between;
            gap: 8px;
            font-size: 13px;
            padding: 8px 0;
            border-bottom: 1px dashed #e7edf8;
        }
        .supplier-row:last-child { border-bottom: 0; }
        .supplier-name { font-weight: 700; color: #30425f; }
        .supplier-price { font-weight: 800; color: #204ea9; }
        .summary-strip {
            display: flex;
            justify-content: space-between;
            gap: 8px;
            margin-top: 10px;
            font-size: 12px;
            font-weight: 700;
        }
        .best-price { color: #1d7a42; }
        .worst-price { color: #b24141; }
    </style>
</head>
<body>
<?php include 'pm-sidebar.php'; ?>
<div class="pm-main-container">
    <div class="container">
    <div class="page-header">
        <h1>Supplier Quote Comparison</h1>
        <p>Capture and compare item quotes to pick the best supplier.</p>
    </div>

    <div class="toolbar">
        <button class="btn-secondary" onclick="loadComparisons()"><i class="fas fa-rotate"></i> Refresh</button>
    </div>

    <h3 style="margin: 8px 0 12px; color:#1b2d4e;">All Suppliers and Product Prices</h3>
    <div id="supplierContainer" class="comparison-grid">
        <div class="empty-state">Loading supplier products...</div>
    </div>

    <h3 style="margin: 22px 0 12px; color:#1b2d4e;">Common Product Price Comparison</h3>
    <div id="comparisonContainer" class="comparison-grid">
        <div class="empty-state">Loading common product comparisons...</div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script>
    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 || 'Purchase Manager';
        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;
    }

    async function loadComparisons() {
        const response = await fetch('../backend/cost_comparison_api.php?action=get_supplier_products_pricing');
        const data = await response.json();
        const container = document.getElementById('comparisonContainer');
        const supplierContainer = document.getElementById('supplierContainer');
        container.innerHTML = '';
        supplierContainer.innerHTML = '';

        if (!data.success || !data.suppliers?.length) {
            supplierContainer.innerHTML = '<div class="empty-state">No supplier product pricing available.</div>';
            container.innerHTML = '<div class="empty-state">No common products found.</div>';
            return;
        }

        for (const supplier of data.suppliers) {
            const products = Array.isArray(supplier.products) ? supplier.products : [];
            const rows = products.length
                ? products.map(p => `
                    <div class="supplier-row">
                        <span class="supplier-name">${escapeHtml(p.name || 'Unknown Product')}</span>
                        <span class="supplier-price">Rs.${Number(p.price || 0).toFixed(2)} / ${escapeHtml(p.unit || 'unit')}</span>
                    </div>
                `).join('')
                : '<div class="empty-state" style="padding:8px 0;">No products added.</div>';

            supplierContainer.innerHTML += `
                <div class="comparison-card">
                    <h3 class="comparison-title">${escapeHtml(supplier.supplier_name || 'Unknown Supplier')}</h3>
                    ${rows}
                </div>
            `;
        }

        const productMap = new Map();
        (data.suppliers || []).forEach(supplier => {
            (supplier.products || []).forEach(product => {
                const pname = String(product.name || '').trim();
                if (!pname) return;
                const key = pname.toLowerCase();
                if (!productMap.has(key)) {
                    productMap.set(key, {
                        product_name: pname,
                        unit: product.unit || 'unit',
                        rows: []
                    });
                }
                productMap.get(key).rows.push({
                    supplier_name: supplier.supplier_name || 'Unknown Supplier',
                    price: Number(product.price || 0),
                    unit: product.unit || 'unit'
                });
            });
        });

        if (productMap.size === 0) {
            container.innerHTML = '<div class="empty-state">No common products found.</div>';
            return;
        }

        const productGroups = Array.from(productMap.values())
            .filter(g => g.rows.length > 1)
            .sort((a, b) => a.product_name.localeCompare(b.product_name));

        if (!productGroups.length) {
            container.innerHTML = '<div class="empty-state">No common products between suppliers yet.</div>';
            return;
        }

        for (const group of productGroups) {
            const sortedRows = group.rows.sort((a, b) => a.price - b.price);
            const prices = sortedRows.map(r => r.price).filter(v => Number.isFinite(v) && v > 0);
            const bestPrice = prices.length ? Math.min(...prices) : 0;
            const worstPrice = prices.length ? Math.max(...prices) : 0;

            const rowsHtml = sortedRows.map(r => `
                <div class="supplier-row">
                    <span class="supplier-name">${escapeHtml(r.supplier_name)}</span>
                    <span class="supplier-price">Rs.${Number(r.price || 0).toFixed(2)} / ${escapeHtml(r.unit || group.unit)}</span>
                </div>
            `).join('');

            container.innerHTML += `
                <div class="comparison-card">
                    <h3 class="comparison-title">${escapeHtml(group.product_name)}</h3>
                    ${rowsHtml}
                    <div class="summary-strip">
                        <span class="best-price">Best: Rs.${Number(bestPrice).toFixed(2)}</span>
                        <span class="worst-price">Worst: Rs.${Number(worstPrice).toFixed(2)}</span>
                    </div>
                </div>
            `;
        }
    }

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

    function handleLogout() {
        Swal.fire({
            title: 'Logout',
            text: 'Are you sure you want to logout?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, logout'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = '../backend/purchase_manager_logout.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');
        }
    }

    document.addEventListener('DOMContentLoaded', async () => {
        await checkSession();
        await loadComparisons();
        await updateNewIngredientsBadge();
        setInterval(updateNewIngredientsBadge, 30000);
    });
</script>

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

