<?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="Supplier Database - 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>Supplier Database</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>Supplier Master</h1>
            <p>Manage vendor contacts, ratings, lead times, and performance metrics</p>
        </div>
        <button class="btn-primary" onclick="openSupplierModal()"><i class="fas fa-plus"></i> Add Supplier</button>
    </div>

    <!-- FILTERS & SEARCH -->
    <div class="toolbar">
        <div class="search-box">
            <i class="fas fa-search"></i>
            <input type="text" id="searchInput" placeholder="Search suppliers by name or contact...">
        </div>
        <select id="statusFilter" class="filter-btn" style="border: 1px solid var(--border-color); padding: 10px 14px; border-radius: 8px; background: white;">
            <option value="">All Status</option>
            <option value="active">Active</option>
            <option value="inactive">Inactive</option>
        </select>
        <select id="ratingFilter" class="filter-btn" style="border: 1px solid var(--border-color); padding: 10px 14px; border-radius: 8px; background: white;">
            <option value="">All Ratings</option>
            <option value="4">★★★★+ (4+)</option>
            <option value="3">★★★+ (3+)</option>
            <option value="all">All Suppliers</option>
        </select>
        <button class="filter-btn" onclick="linkExistingIngredients()" title="Auto-link existing ingredients to suppliers"><i class="fas fa-link"></i> Link Ingredients</button>
        <button class="filter-btn" onclick="exportSuppliers()"><i class="fas fa-download"></i> Export</button>
        <button class="btn-secondary" onclick="loadSuppliers()"><i class="fas fa-rotate"></i> Refresh</button>
    </div>

    <!-- STATS ROW -->
    <div class="metric-strip">
        <div class="metric-card">
            <div class="label">Total Suppliers</div>
            <div class="value" id="totalCount">0</div>
        </div>
        <div class="metric-card">
            <div class="label">Active</div>
            <div class="value" id="activeCount">0</div>
        </div>
        <div class="metric-card">
            <div class="label">Avg Rating</div>
            <div class="value" id="avgRating">0</div>
        </div>
        <div class="metric-card">
            <div class="label">Avg Lead Time</div>
            <div class="value" id="avgLeadTime">0</div>
        </div>
    </div>

    <!-- TABLE -->
    <div class="table-wrapper">
        <table>
            <thead>
                <tr>
                    <th width="20%">Supplier Name</th>
                    <th width="15%">Contact</th>
                    <th width="15%">Phone</th>
                    <th width="15%">Email</th>
                    <th width="10%">Rating</th>
                    <th width="10%">Lead Time</th>
                    <th width="10%">Status</th>
                    <th width="15%">Actions</th>
                </tr>
            </thead>
            <tbody id="supplierBody">
                <tr><td colspan="8" class="empty-state"><i class="fas fa-spinner"></i> Loading suppliers...</td></tr>
            </tbody>
        </table>
    </div>
</div>

<!-- ADD/EDIT MODAL -->
<div class="modal" id="supplierModal">
    <div class="modal-content">
        <div class="modal-header">
            <span id="modalTitle">Add New Supplier</span>
            <button class="close" type="button" onclick="closeSupplierModal()">&times;</button>
        </div>
        <form id="supplierForm" onsubmit="saveSupplier(event)">
            <input type="hidden" id="supplierId">
            <div class="form-grid">
                <div class="form-group">
                    <label><i class="fas fa-building"></i> Supplier Name *</label>
                    <input id="supplierName" required placeholder="Enter supplier name">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-user"></i> Contact Person *</label>
                    <input id="contactPerson" required placeholder="Primary contact name">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-envelope"></i> Email *</label>
                    <input id="supplierEmail" type="email" required placeholder="contact@supplier.com">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-phone"></i> Phone *</label>
                    <input id="supplierPhone" required placeholder="+1 (555) 000-0000">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-star"></i> Rating (1-5)</label>
                    <input id="supplierRating" type="number" min="1" max="5" step="0.1" placeholder="e.g. 4.5">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-calendar-days"></i> Lead Time (days)</label>
                    <input id="leadTimeDays" type="number" min="0" step="1" value="0" placeholder="Delivery lead time">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-handshake"></i> Payment Terms</label>
                    <input id="paymentTerms" placeholder="e.g. Net 30, COD, Prepaid">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-toggle-on"></i> Status</label>
                    <select id="supplierStatus">
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label><i class="fas fa-map-marker"></i> Address</label>
                <textarea id="supplierAddress" rows="3" placeholder="Full supplier address"></textarea>
            </div>
            <div style="display: flex; gap: 12px; justify-content: flex-end;">
                <button type="button" class="btn-secondary" onclick="closeSupplierModal()" style="width: auto;">Cancel</button>
                <button type="submit" class="btn-primary"><i class="fas fa-check"></i> Save Supplier</button>
            </div>
        </form>
    </div>
</div>

<!-- DETAIL MODAL -->
<div class="modal" id="detailModal">
    <div class="modal-content">
        <div class="modal-header">
            <span id="detailTitle">Supplier Details</span>
            <button class="close" type="button" onclick="closeDetailModal()">&times;</button>
        </div>
        <div style="padding: 24px;">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div>
                    <div style="margin-bottom: 20px;">
                        <div style="color: var(--text-light); font-size: 12px; font-weight: 600; text-transform: uppercase; margin-bottom: 4px;">Company Name</div>
                        <div id="detailName" style="font-size: 16px; font-weight: 700; color: var(--text-primary);"></div>
                    </div>
                    <div style="margin-bottom: 20px;">
                        <div style="color: var(--text-light); font-size: 12px; font-weight: 600; text-transform: uppercase; margin-bottom: 4px;">Contact Person</div>
                        <div id="detailContact" style="font-size: 14px; color: var(--text-primary);"></div>
                    </div>
                    <div style="margin-bottom: 20px;">
                        <div style="color: var(--text-light); font-size: 12px; font-weight: 600; text-transform: uppercase; margin-bottom: 4px;">Phone</div>
                        <div id="detailPhone" style="font-size: 14px; color: var(--text-primary);"></div>
                    </div>
                </div>
                <div>
                    <div style="margin-bottom: 20px;">
                        <div style="color: var(--text-light); font-size: 12px; font-weight: 600; text-transform: uppercase; margin-bottom: 4px;">Email</div>
                        <div id="detailEmail" style="font-size: 14px; color: var(--text-primary);"></div>
                    </div>
                    <div style="margin-bottom: 20px;">
                        <div style="color: var(--text-light); font-size: 12px; font-weight: 600; text-transform: uppercase; margin-bottom: 4px;">Rating</div>
                        <div id="detailRating" style="font-size: 14px; color: var(--text-primary);"></div>
                    </div>
                    <div style="margin-bottom: 20px;">
                        <div style="color: var(--text-light); font-size: 12px; font-weight: 600; text-transform: uppercase; margin-bottom: 4px;">Lead Time</div>
                        <div id="detailLeadTime" style="font-size: 14px; color: var(--text-primary);"></div>
                    </div>
                </div>
            </div>
            <div style="margin-bottom: 20px;">
                <div style="color: var(--text-light); font-size: 12px; font-weight: 600; text-transform: uppercase; margin-bottom: 4px;">Address</div>
                <div id="detailAddress" style="font-size: 14px; color: var(--text-primary); line-height: 1.6;"></div>
            </div>
            <div style="display: flex; gap: 8px; justify-content: flex-end;">
                <button class="btn-secondary" onclick="closeDetailModal()" style="width: auto;">Close</button>
                <button class="btn-primary" onclick="openProductsModal()" style="width: auto;"><i class="fas fa-boxes"></i> Products</button>
                <button class="btn-primary" onclick="editSupplierFromDetail()" style="width: auto;"><i class="fas fa-edit"></i> Edit</button>
            </div>
        </div>
    </div>
</div>

<!-- SUPPLIER PRODUCTS MODAL -->
<div class="modal" id="productsModal">
    <div class="modal-content" style="max-width: 900px;">
        <div class="modal-header">
            <span id="productsTitle">Supplier Products</span>
            <button class="close" type="button" onclick="closeProductsModal()">&times;</button>
        </div>
        <div style="padding: 24px;">
            <!-- Add Product Button -->
            <div style="margin-bottom: 20px;">
                <button class="btn-primary" onclick="openAddProductModal()" style="width: auto;"><i class="fas fa-plus"></i> Add Product</button>
            </div>
            
            <!-- Products Table -->
            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>
                            <th width="20%">Ingredient</th>
                            <th width="12%">Unit</th>
                            <th width="12%">Price</th>
                            <th width="12%">Min Order</th>
                            <th width="12%">Lead Time</th>
                            <th width="12%">Status</th>
                            <th width="12%">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="productsBody">
                        <tr><td colspan="7" class="empty-state"><i class="fas fa-spinner"></i> Loading...</td></tr>
                    </tbody>
                </table>
            </div>
            
            <div style="display: flex; gap: 12px; justify-content: flex-end; margin-top: 20px;">
                <button class="btn-secondary" onclick="closeProductsModal()" style="width: auto;">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- ADD/EDIT PRODUCT MODAL -->
<div class="modal" id="productFormModal">
    <div class="modal-content">
        <div class="modal-header">
            <span id="productFormTitle">Add Product to Supplier</span>
            <button class="close" type="button" onclick="closeProductFormModal()">&times;</button>
        </div>
        <form id="productForm" onsubmit="saveProduct(event)">
            <input type="hidden" id="productId">
            <input type="hidden" id="productSupplierId">
            <div class="form-grid">
                <div class="form-group">
                    <label><i class="fas fa-leaf"></i> Ingredient / Custom Product *</label>
                    <select id="productIngredient" required onchange="onIngredientSelect()">
                        <option value="">Select ingredient...</option>
                    </select>
                </div>
                <div class="form-group">
                    <label><i class="fas fa-barcode"></i> Supplier SKU</label>
                    <input id="productSku" placeholder="e.g. SKU-12345">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-tag"></i> Supplier Product Name</label>
                    <input id="productName" placeholder="How supplier names this product">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-balance-scale"></i> Unit</label>
                    <input id="productUnit" list="productUnitOptions" disabled placeholder="Auto-filled from ingredient">
                    <datalist id="productUnitOptions"></datalist>
                </div>
                <div class="form-group">
                    <label><i class="fas fa-money-bill"></i> Unit Price *</label>
                    <input id="productPrice" type="number" step="0.01" min="0" required placeholder="0.00">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-cube"></i> Minimum Order Qty *</label>
                    <input id="productMinQty" type="number" step="0.01" min="0.01" value="1" required placeholder="1">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-calendar-days"></i> Lead Time (days) *</label>
                    <input id="productLeadTime" type="number" min="0" value="0" required placeholder="0">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-check-circle"></i> Availability</label>
                    <select id="productAvailability">
                        <option value="available">Available</option>
                        <option value="discontinued">Discontinued</option>
                        <option value="seasonal">Seasonal</option>
                    </select>
                </div>
                <div class="form-group">
                    <label><i class="fas fa-star"></i> Preferred Supplier</label>
                    <select id="productPreferred">
                        <option value="0">No</option>
                        <option value="1">Yes</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label><i class="fas fa-note-sticky"></i> Notes</label>
                <textarea id="productNotes" rows="2" placeholder="Additional information about this product..."></textarea>
            </div>
            <div style="display: flex; gap: 12px; justify-content: flex-end;">
                <button type="button" class="btn-secondary" onclick="closeProductFormModal()" style="width: auto;">Cancel</button>
                <button type="submit" class="btn-primary"><i class="fas fa-check"></i> Save Product</button>
            </div>
        </form>
    </div>
</div>

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

    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;
        
        loadSuppliers();
    }

    async function loadSuppliers() {
        try {
            const response = await fetch('../backend/suppliers_api.php?action=get_all');
            const data = await response.json();

            if (!data.success || !data.suppliers?.length) {
                allSuppliers = [];
                updateDisplay();
                return;
            }

            allSuppliers = data.suppliers;
            updateDisplay();
            updateStats();
        } catch (error) {
            console.error('Error loading suppliers:', error);
            Swal.fire('Error', 'Failed to load suppliers', 'error');
        }
    }

    function updateDisplay() {
        const searchTerm = document.getElementById('searchInput').value.toLowerCase();
        const statusFilter = document.getElementById('statusFilter').value;
        const ratingFilter = document.getElementById('ratingFilter').value;

        let filtered = allSuppliers.filter(s => {
            const matchSearch = !searchTerm || s.name.toLowerCase().includes(searchTerm) || 
                              (s.contact_person || '').toLowerCase().includes(searchTerm) ||
                              (s.email || '').toLowerCase().includes(searchTerm);
            const matchStatus = !statusFilter || s.status === statusFilter;
            const matchRating = !ratingFilter || (s.rating && parseFloat(s.rating) >= parseFloat(ratingFilter));
            return matchSearch && matchStatus && matchRating;
        });

        const tbody = document.getElementById('supplierBody');
        if (filtered.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8" class="empty-state">No suppliers found</td></tr>';
            return;
        }

        tbody.innerHTML = filtered.map(s => `
            <tr>
                <td><strong>${escapeHtml(s.name)}</strong></td>
                <td>${escapeHtml(s.contact_person || '-')}</td>
                <td>${escapeHtml(s.phone || '-')}</td>
                <td>${escapeHtml(s.email || '-')}</td>
                <td>${s.rating ? '★ ' + Number(s.rating).toFixed(1) : '-'}</td>
                <td>${s.lead_time_days || '-'} day(s)</td>
                <td><span class="status-badge status-${s.status.toLowerCase()}">${s.status}</span></td>
                <td>
                    <div class="action-buttons">
                        <button class="action-btn view" onclick="viewSupplier(${s.id})"><i class="fas fa-eye"></i></button>
                        <button class="action-btn edit" onclick="editSupplier(${s.id})"><i class="fas fa-edit"></i></button>
                        <button class="action-btn delete" onclick="deleteSupplier(${s.id})"><i class="fas fa-trash"></i></button>
                    </div>
                </td>
            </tr>
        `).join('');
    }

    function updateStats() {
        const total = allSuppliers.length;
        const active = allSuppliers.filter(s => s.status === 'active').length;
        const avgRating = allSuppliers.filter(s => s.rating).length > 0
            ? (allSuppliers.reduce((sum, s) => sum + (parseFloat(s.rating) || 0), 0) / allSuppliers.filter(s => s.rating).length).toFixed(1)
            : '0';
        const avgLeadTime = total > 0 
            ? Math.round(allSuppliers.reduce((sum, s) => sum + (parseInt(s.lead_time_days) || 0), 0) / total)
            : 0;

        document.getElementById('totalCount').textContent = total;
        document.getElementById('activeCount').textContent = active;
        document.getElementById('avgRating').textContent = avgRating;
        document.getElementById('avgLeadTime').textContent = avgLeadTime;
    }

    function openSupplierModal() {
        document.getElementById('supplierId').value = '';
        document.getElementById('supplierForm').reset();
        document.getElementById('modalTitle').textContent = 'Add New Supplier';
        document.getElementById('supplierModal').classList.add('show');
    }

    function closeSupplierModal() {
        document.getElementById('supplierModal').classList.remove('show');
    }

    function viewSupplier(id) {
        const supplier = allSuppliers.find(s => s.id === id);
        if (!supplier) return;

        document.getElementById('detailName').textContent = supplier.name;
        document.getElementById('detailContact').textContent = supplier.contact_person || '-';
        document.getElementById('detailPhone').textContent = supplier.phone || '-';
        document.getElementById('detailEmail').textContent = supplier.email || '-';
        document.getElementById('detailRating').textContent = supplier.rating ? '★ ' + Number(supplier.rating).toFixed(1) : '-';
        document.getElementById('detailLeadTime').textContent = (supplier.lead_time_days || '-') + ' day(s)';
        document.getElementById('detailAddress').textContent = supplier.address || '-';
        document.getElementById('detailTitle').textContent = supplier.name;
        document.getElementById('detailModal').classList.add('show');
        document.getElementById('detailModal').dataset.supplierId = id;
    }

    function closeDetailModal() {
        document.getElementById('detailModal').classList.remove('show');
    }

    function editSupplierFromDetail() {
        const id = parseInt(document.getElementById('detailModal').dataset.supplierId);
        closeDetailModal();
        editSupplier(id);
    }

    function editSupplier(id) {
        const supplier = allSuppliers.find(s => s.id === id);
        if (!supplier) return;

        document.getElementById('supplierId').value = id;
        document.getElementById('supplierName').value = supplier.name;
        document.getElementById('contactPerson').value = supplier.contact_person || '';
        document.getElementById('supplierEmail').value = supplier.email || '';
        document.getElementById('supplierPhone').value = supplier.phone || '';
        document.getElementById('supplierRating').value = supplier.rating || '';
        document.getElementById('leadTimeDays').value = supplier.lead_time_days || '0';
        document.getElementById('paymentTerms').value = supplier.payment_terms || '';
        document.getElementById('supplierStatus').value = supplier.status || 'active';
        document.getElementById('supplierAddress').value = supplier.address || '';
        document.getElementById('modalTitle').textContent = 'Edit Supplier';
        document.getElementById('supplierModal').classList.add('show');
    }

    async function deleteSupplier(id) {
        const result = await Swal.fire({
            title: 'Delete Supplier?',
            text: 'This action cannot be undone',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Delete',
            confirmButtonColor: '#dc2626'
        });

        if (!result.isConfirmed) return;

        try {
            const response = await fetch('../backend/suppliers_api.php?action=delete', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id })
            });

            const data = await response.json();
            if (data.success) {
                Swal.fire('Deleted!', 'Supplier removed successfully', 'success');
                loadSuppliers();
            } else {
                Swal.fire('Error', data.message || 'Failed to delete supplier', 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            Swal.fire('Error', 'Request failed', 'error');
        }
    }

    async function saveSupplier(event) {
        event.preventDefault();

        const supplier = {
            id: document.getElementById('supplierId').value || undefined,
            name: document.getElementById('supplierName').value,
            contact_person: document.getElementById('contactPerson').value,
            email: document.getElementById('supplierEmail').value,
            phone: document.getElementById('supplierPhone').value,
            rating: document.getElementById('supplierRating').value || null,
            lead_time_days: document.getElementById('leadTimeDays').value,
            payment_terms: document.getElementById('paymentTerms').value,
            status: document.getElementById('supplierStatus').value,
            address: document.getElementById('supplierAddress').value
        };

        try {
            const response = await fetch(`../backend/suppliers_api.php?action=${supplier.id ? 'update' : 'create'}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(supplier)
            });

            const data = await response.json();
            if (data.success) {
                Swal.fire('Success!', supplier.id ? 'Supplier updated' : 'Supplier added', 'success');
                closeSupplierModal();
                loadSuppliers();
            } else {
                Swal.fire('Error', data.message || 'Failed to save supplier', 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            Swal.fire('Error', 'Request failed', 'error');
        }
    }

    function exportSuppliers() {
        const headers = ['Name', 'Contact', 'Phone', 'Email', 'Rating', 'Lead Time (days)', 'Payment Terms', 'Status', 'Address'];
        const rows = allSuppliers.map(s => [
            s.name,
            s.contact_person || '',
            s.phone || '',
            s.email || '',
            s.rating || '',
            s.lead_time_days || '',
            s.payment_terms || '',
            s.status,
            s.address || ''
        ]);

        const csv = [headers, ...rows].map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(',')).join('\n');
        const blob = new Blob([csv], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'suppliers.csv';
        a.click();
        window.URL.revokeObjectURL(url);
    }

    async function linkExistingIngredients() {
        const result = await Swal.fire({
            title: 'Link Existing Ingredients to Suppliers?',
            html: 'This will automatically link all ingredients that have supplier names to their corresponding supplier records.<br><br><em>For example: If an ingredient has "Fresh Farm" as supplier, it will be linked to the Fresh Farm supplier record.</em>',
            icon: 'info',
            showCancelButton: true,
            confirmButtonText: 'Yes, Link Now',
            confirmButtonColor: '#3b82f6',
            cancelButtonText: 'Cancel'
        });

        if (!result.isConfirmed) return;

        Swal.fire({
            title: 'Processing...',
            html: 'Linking ingredients to suppliers. Please wait...',
            icon: 'info',
            allowOutsideClick: false,
            allowEscapeKey: false,
            showConfirmButton: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        try {
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 60000);
            const response = await fetch('../backend/link_ingredients_to_suppliers.php', {
                method: 'GET',
                signal: controller.signal
            });
            clearTimeout(timeoutId);

            const data = await response.json();
            Swal.close();

            if (data.success) {
                let resultHtml = `<div style="text-align: left; max-height: 300px; overflow-y: auto;">`;
                resultHtml += `<p><strong style="color: #10b981;">${data.linked_count} ingredients linked successfully</strong></p>`;
                if (typeof data.elapsed_ms === 'number') {
                    resultHtml += `<p style="color:#6b7280; font-size:12px; margin: 4px 0 10px 0;">Completed in ${(data.elapsed_ms / 1000).toFixed(2)}s</p>`;
                }

                if (data.results && data.results.length > 0) {
                    resultHtml += `<div style="background: #f0fdf4; padding: 10px; border-radius: 6px; margin-bottom: 10px; font-size: 13px;">`;
                    data.results.forEach(r => {
                        resultHtml += `<div>${r}</div>`;
                    });
                    resultHtml += `</div>`;
                }

                if (data.skipped_count > 0) {
                    resultHtml += `<p style="color: #f59e0b;"><strong>${data.skipped_count} skipped:</strong></p>`;
                    resultHtml += `<div style="background: #fffceb; padding: 10px; border-radius: 6px; font-size: 13px;">`;
                    (data.skipped || []).forEach(s => {
                        resultHtml += `<div>- ${s}</div>`;
                    });
                    resultHtml += `</div>`;
                }

                resultHtml += `</div>`;

                Swal.fire({
                    title: 'Linking Complete!',
                    html: resultHtml,
                    icon: 'success',
                    confirmButtonText: 'OK'
                });

                setTimeout(() => {
                    loadSuppliers();
                }, 1000);
            } else {
                Swal.fire('Error', data.message || 'Failed to link ingredients', 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            Swal.close();
            if (error.name === 'AbortError') {
                Swal.fire('Timeout', 'Linking is taking too long. Please try again.', 'warning');
            } else {
                Swal.fire('Error', 'Request failed: ' + error.message, 'error');
            }
        }
    }

    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?',
            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');
        }
    }

    // ===== SUPPLIER PRODUCTS MANAGEMENT =====
    
    let currentSupplierId = null;
    let allSupplierProducts = [];
    let availableIngredientsForProduct = [];

    async function openProductsModal() {
        const supplierId = parseInt(document.getElementById('detailModal').dataset.supplierId);
        if (!supplierId) return;
        
        currentSupplierId = supplierId;
        const supplier = allSuppliers.find(s => s.id === supplierId);
        document.getElementById('productsTitle').textContent = `Products - ${supplier.name}`;
        document.getElementById('productsModal').classList.add('show');
        
        await loadSupplierProducts(supplierId);
    }

    function closeProductsModal() {
        document.getElementById('productsModal').classList.remove('show');
    }

    async function loadSupplierProducts(supplierId) {
        try {
            const response = await fetch(`../backend/supplier_products_api.php?action=get_supplier_products&supplier_id=${supplierId}`);
            const data = await response.json();
            
            if (!data.success) {
                allSupplierProducts = [];
                displayProducts([]);
                Swal.fire('Error', data.message || 'Failed to load products', 'error');
                return;
            }

            if (!data.products?.length) {
                allSupplierProducts = [];
                displayProducts([]);
                return;
            }
            
            allSupplierProducts = data.products;
            displayProducts(data.products);
        } catch (error) {
            console.error('Error loading products:', error);
            Swal.fire('Error', 'Failed to load products', 'error');
        }
    }

    function displayProducts(products) {
        const tbody = document.getElementById('productsBody');
        
        if (!products || products.length === 0) {
            tbody.innerHTML = '<tr><td colspan="7" class="empty-state">No products added. Click "Add Product" to get started.</td></tr>';
            return;
        }
        
        tbody.innerHTML = products.map(p => {
            const readOnly = p.is_read_only === 1 || p.is_read_only === '1' || p.is_read_only === true;
            const availability = String(p.availability || 'available');
            const availabilityClass = availability.toLowerCase();
            const actionsHtml = readOnly
                ? '<span style="font-size: 12px; color: var(--text-light);">Linked from Ingredients</span>'
                : `<div class="action-buttons">
                        <button class="action-btn edit" onclick="editProduct(${p.id})"><i class="fas fa-edit"></i></button>
                        <button class="action-btn delete" onclick="deleteProduct(${p.id})"><i class="fas fa-trash"></i></button>
                   </div>`;

            return `
                <tr>
                    <td><strong>${escapeHtml(p.ingredient_name || p.supplier_product_name || p.product_name || 'N/A')}</strong></td>
                    <td>${escapeHtml(p.unit || '')}</td>
                    <td>$${Number(p.unit_price || 0).toFixed(2)}</td>
                    <td>${Number(p.minimum_order_qty || 1).toFixed(2)}</td>
                    <td>${p.lead_time_days || 0} days</td>
                    <td><span class="status-badge status-${availabilityClass}">${escapeHtml(availability)}</span></td>
                    <td>${actionsHtml}</td>
                </tr>
            `;
        }).join('');
    }

    async function openAddProductModal() {
        document.getElementById('productId').value = '';
        document.getElementById('productSupplierId').value = currentSupplierId;
        document.getElementById('productForm').reset();
        document.getElementById('productFormTitle').textContent = 'Add Product to Supplier';
        document.getElementById('productIngredient').disabled = false;
        
        // Load available ingredients
        await loadAvailableIngredients(currentSupplierId);
        
        document.getElementById('productFormModal').classList.add('show');
    }

    function closeProductFormModal() {
        document.getElementById('productFormModal').classList.remove('show');
    }

    async function loadAvailableIngredients(supplierId) {
        try {
            const response = await fetch(`../backend/supplier_products_api.php?action=get_available_ingredients&supplier_id=${supplierId}`);
            const data = await response.json();
            
            availableIngredientsForProduct = data.ingredients || [];
            const knownUnits = Array.from(new Set(
                availableIngredientsForProduct
                    .map(ing => (ing.unit || '').trim())
                    .filter(Boolean)
            )).sort((a, b) => a.localeCompare(b));
            
            const select = document.getElementById('productIngredient');
            select.innerHTML = '<option value="">Select ingredient...</option><option value="__custom__">Custom product (not in ingredients)</option>' + 
                availableIngredientsForProduct.map(ing => 
                    `<option value="${ing.id}" data-unit="${ing.unit}">${escapeHtml(ing.name)} (${escapeHtml(ing.unit)})</option>`
                ).join('');

            const unitsList = document.getElementById('productUnitOptions');
            unitsList.innerHTML = knownUnits.map(unit => `<option value="${escapeHtml(unit)}"></option>`).join('');
        } catch (error) {
            console.error('Error loading ingredients:', error);
        }
    }

    function onIngredientSelect() {
        const select = document.getElementById('productIngredient');
        const option = select.options[select.selectedIndex];
        const unitInput = document.getElementById('productUnit');
        if (select.value === '__custom__') {
            unitInput.disabled = false;
            unitInput.placeholder = 'Select or type unit (e.g., kg, liter, packet)';
            unitInput.value = '';
            return;
        }
        const unit = option.dataset.unit || '';
        unitInput.disabled = true;
        unitInput.placeholder = 'Auto-filled from ingredient';
        unitInput.value = unit;
    }

    async function editProduct(productId) {
        const product = allSupplierProducts.find(p => p.id === productId);
        if (!product || product.is_read_only === 1 || product.is_read_only === '1' || product.is_read_only === true) return;
        
        document.getElementById('productId').value = product.id;
        document.getElementById('productSupplierId').value = product.supplier_id;
        const ingredientSelect = document.getElementById('productIngredient');
        if (product.ingredient_id) {
            ingredientSelect.innerHTML = `<option value="${product.ingredient_id}">${escapeHtml(product.ingredient_name || product.supplier_product_name || 'Selected ingredient')}</option>`;
            ingredientSelect.value = String(product.ingredient_id);
        } else {
            ingredientSelect.innerHTML = '<option value="__custom__">Custom product (not in ingredients)</option>';
            ingredientSelect.value = '__custom__';
        }
        document.getElementById('productSku').value = product.supplier_sku || '';
        document.getElementById('productName').value = product.supplier_product_name || '';
        const unitInput = document.getElementById('productUnit');
        unitInput.value = product.unit;
        unitInput.disabled = !!product.ingredient_id;
        unitInput.placeholder = product.ingredient_id
            ? 'Auto-filled from ingredient'
            : 'Select or type unit (e.g., kg, liter, packet)';
        document.getElementById('productPrice').value = product.unit_price;
        document.getElementById('productMinQty').value = product.minimum_order_qty;
        document.getElementById('productLeadTime').value = product.lead_time_days || 0;
        document.getElementById('productAvailability').value = product.availability;
        document.getElementById('productPreferred').value = product.is_preferred ? '1' : '0';
        document.getElementById('productNotes').value = product.notes || '';
        document.getElementById('productIngredient').disabled = true;
        
        document.getElementById('productFormTitle').textContent = 'Edit Product';
        document.getElementById('productFormModal').classList.add('show');
    }

    async function saveProduct(event) {
        event.preventDefault();
        
        const productId = document.getElementById('productId').value;
        const supplierId = parseInt(document.getElementById('productSupplierId').value);
        const ingredientRaw = document.getElementById('productIngredient').value;
        const ingredientId = ingredientRaw === '__custom__' ? null : parseInt(ingredientRaw);
        const unitPrice = parseFloat(document.getElementById('productPrice').value);
        const productName = document.getElementById('productName').value.trim();

        if (!unitPrice || (!ingredientId && !productName)) {
            Swal.fire('Error', 'Select an ingredient or enter a custom product name, and set unit price', 'error');
            return;
        }

        const product = {
            id: productId || undefined,
            supplier_id: supplierId,
            ingredient_id: ingredientId || undefined,
            supplier_sku: document.getElementById('productSku').value,
            supplier_product_name: productName,
            unit: document.getElementById('productUnit').value,
            unit_price: unitPrice,
            minimum_order_qty: parseFloat(document.getElementById('productMinQty').value),
            lead_time_days: parseInt(document.getElementById('productLeadTime').value),
            availability: document.getElementById('productAvailability').value,
            is_preferred: document.getElementById('productPreferred').value === '1',
            notes: document.getElementById('productNotes').value
        };

        try {
            const action = productId ? 'update_product' : 'add_product';
            const response = await fetch(`../backend/supplier_products_api.php?action=${action}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(product)
            });

            const data = await response.json();
            if (data.success) {
                Swal.fire('Success!', productId ? 'Product updated' : 'Product added', 'success');
                closeProductFormModal();
                await loadSupplierProducts(currentSupplierId);
            } else {
                Swal.fire('Error', data.message || 'Failed to save product', 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            Swal.fire('Error', 'Request failed', 'error');
        }
    }

    async function deleteProduct(productId) {
        const product = allSupplierProducts.find(p => p.id === productId);
        if (!product || product.is_read_only === 1 || product.is_read_only === '1' || product.is_read_only === true) return;

        const result = await Swal.fire({
            title: 'Remove Product?',
            text: 'This product will be removed from the supplier',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Remove',
            confirmButtonColor: '#dc2626'
        });

        if (!result.isConfirmed) return;

        try {
            const response = await fetch('../backend/supplier_products_api.php?action=delete_product', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id: productId })
            });

            const data = await response.json();
            if (data.success) {
                Swal.fire('Removed!', 'Product removed successfully', 'success');
                await loadSupplierProducts(currentSupplierId);
            } else {
                Swal.fire('Error', data.message || 'Failed to remove product', 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            Swal.fire('Error', 'Request failed', 'error');
        }
    }


    // Event listeners
    document.getElementById('searchInput')?.addEventListener('input', updateDisplay);
    document.getElementById('statusFilter')?.addEventListener('change', updateDisplay);
    document.getElementById('ratingFilter')?.addEventListener('change', updateDisplay);
    document.getElementById('supplierModal')?.addEventListener('click', e => {
        if (e.target === e.currentTarget) closeSupplierModal();
    });
    document.getElementById('detailModal')?.addEventListener('click', e => {
        if (e.target === e.currentTarget) closeDetailModal();
    });
    document.getElementById('productsModal')?.addEventListener('click', e => {
        if (e.target === e.currentTarget) closeProductsModal();
    });
    document.getElementById('productFormModal')?.addEventListener('click', e => {
        if (e.target === e.currentTarget) closeProductFormModal();
    });

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

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