window.currentCatPage = 1;
window.catalogSearchTimeout = null;

// Initialize when the View is loaded
window.initCatalogUI = function() {
    window.fetchEnterpriseCatalog(1);
};

// Debounce Search Input
window.debounceFetchCatalog = function() {
    clearTimeout(window.catalogSearchTimeout);
    window.catalogSearchTimeout = setTimeout(() => {
        window.fetchEnterpriseCatalog(1);
    }, 400); 
};

// Accordion Event Delegation (Fixes dynamic click issues in SPA)
document.addEventListener('click', function(e) {
    const header = e.target.closest('.accordion-header');
    if (header) {
        const body = header.nextElementSibling;
        const icon = header.querySelector('.chevron-icon');
        
        if (body.style.display === 'none' || body.style.display === '') {
            body.style.display = 'block';
            icon.style.transform = 'rotate(180deg)';
        } else {
            body.style.display = 'none';
            icon.style.transform = 'rotate(0deg)';
        }
    }
});

// Fetch Data from Backend
window.fetchEnterpriseCatalog = function(page = 1) {
    window.currentCatPage = page;
    const container = document.getElementById('catalogAccordionContainer');
    if(!container) return;

    const search = document.getElementById('catSearch') ? document.getElementById('catSearch').value : '';
    const dept = document.getElementById('catDept') ? document.getElementById('catDept').value : 'ALL';
    const modality = document.getElementById('catModality') ? document.getElementById('catModality').value : 'ALL';
    const insurance = document.getElementById('catInsurance') ? document.getElementById('catInsurance').value : 'ALL';
    const limit = document.getElementById('catLimit') ? document.getElementById('catLimit').value : 50;

    container.innerHTML = `<div style="text-align:center; padding: 40px; color:#64748b;"><i class="fa-solid fa-spinner fa-spin" style="font-size: 24px; margin-bottom:10px;"></i><br>Fetching Catalog Data...</div>`;

    // EXACT PATH FIX: Relative to the SPA Dashboard
    fetch(`../../dripend/systemSetup/gdrg/fetch_catalog.php?page=${page}&limit=${limit}&search=${encodeURIComponent(search)}&dept=${encodeURIComponent(dept)}&modality=${encodeURIComponent(modality)}&insurance=${encodeURIComponent(insurance)}`)
        .then(async response => {
            const text = await response.text(); 
            try {
                const data = JSON.parse(text);
                
                if (data.error) {
                    container.innerHTML = `<div style="padding: 20px; color:#dc2626; background:#fef2f2; border:1px solid #fecaca; border-radius:12px;"><strong>Database Error:</strong><br>${data.error}</div>`;
                    return;
                }
                window.renderEnterpriseCatalog(data);
            } catch (e) {
                console.error("Parse Error:", e);
                container.innerHTML = `<div style="padding: 20px; color:#dc2626; background:#fef2f2; border:1px solid #fecaca; border-radius:12px;">
                    <strong>Server returned invalid JSON. Read the box below to see the exact PHP Error or 404 Not Found issue:</strong><br>
                    <textarea style="width:100%; height:200px; margin-top:10px; font-family:monospace; font-size:12px; border:1px solid #fca5a5; padding:10px;">${text}</textarea>
                </div>`;
            }
        })
        .catch(err => {
            console.error('Fetch Error:', err);
            container.innerHTML = `<div style="text-align:center; padding: 40px; color:#dc2626;"><i class="fa-solid fa-wifi" style="font-size: 24px; margin-bottom:10px;"></i><br>Network Error. Cannot reach the server.</div>`;
        });
};

// Render Grouped Data into Accordions
window.renderEnterpriseCatalog = function(data) {
    const container = document.getElementById('catalogAccordionContainer');
    
    if (!data.records || data.records.length === 0) {
        container.innerHTML = `<div style="text-align:center; padding: 40px; color:#64748b; background:#fff; border:1px solid #e2e8f0; border-radius:12px;">No procedures or services match your current filters.</div>`;
        window.updateCatPagination(0, 0, 0, 0);
        return;
    }

    const grouped = data.records.reduce((acc, curr) => {
        const deptName = curr.department_name || 'Uncategorized / Global';
        if (!acc[deptName]) { acc[deptName] = { items: [], consults: 0 }; }
        acc[deptName].items.push(curr);
        if (curr.service_type === 'Consultation') { acc[deptName].consults += 1; }
        return acc;
    }, {});

    container.innerHTML = ''; 

    let globalIndex = ((data.current_page - 1) * data.limit) + 1;

    Object.keys(grouped).forEach(deptName => {
        const dept = grouped[deptName];
        let tableRows = '';
        
        dept.items.forEach(item => {
            let tariffDisplay = '--';
            let copayDisplay = '--';

            // FORMAT DUAL CASH PRICING (Direct from the DB columns)
            const cashDisplay = `
                <div style="font-size: 12px; color: #475569; line-height:1.6;">
                    <span style="display:inline-block; width:35px;">Adlt:</span> <strong style="color:#0f172a;">GHS ${parseFloat(item.cash_price_adult || 0).toFixed(2)}</strong><br>
                    <span style="display:inline-block; width:35px;">Chld:</span> <strong style="color:#0f172a;">GHS ${parseFloat(item.cash_price_child || 0).toFixed(2)}</strong>
                </div>
            `;

            // INSURANCE FORMATTING LOGIC
            if (data.insurance_view === 'ALL' || data.insurance_view === 'NHIS') {
                if (item.nhis_covered == 1) {
                    tariffDisplay = `
                        <div class="tariff-info"><span style="color:#cbd5e1;">${item.gdrg_adult_code || 'N/A'}</span> : <span class="tariff-val">GHS ${parseFloat(item.tariff_adult).toFixed(2)}</span> (Adult)</div>
                        <div class="tariff-info"><span style="color:#cbd5e1;">${item.gdrg_child_code || 'N/A'}</span> : <span class="tariff-val">GHS ${parseFloat(item.tariff_child).toFixed(2)}</span> (Child)</div>
                    `;
                    if (item.is_copay_required == 1) {
                        copayDisplay = `
                            <div style="font-size: 12px; color: #b45309; line-height:1.6;">
                                <span style="display:inline-block; width:35px;">Adlt:</span> <strong>GHS ${parseFloat(item.nhis_copay_adult || 0).toFixed(2)}</strong><br>
                                <span style="display:inline-block; width:35px;">Chld:</span> <strong>GHS ${parseFloat(item.nhis_copay_child || 0).toFixed(2)}</strong>
                            </div>
                        `;
                    } else {
                        copayDisplay = `<span class="copay-none">No Co-Pay</span>`;
                    }
                } else {
                    tariffDisplay = `<span style="color:#94a3b8; font-size:12px;">--</span>`;
                }
            } else {
                if (item.corp_tariff !== null && item.corp_tariff !== undefined) {
                    tariffDisplay = `<div class="tariff-info"><span class="tariff-val" style="font-size:14px; color:#1d4ed8;">GHS ${parseFloat(item.corp_tariff).toFixed(2)}</span></div>`;
                    if (item.corp_copay_req == 1) {
                        copayDisplay = `
                            <div style="font-size: 12px; color: #b45309; line-height:1.6;">
                                <span style="display:inline-block; width:35px;">Adlt:</span> <strong>GHS ${parseFloat(item.corp_copay_adult || 0).toFixed(2)}</strong><br>
                                <span style="display:inline-block; width:35px;">Chld:</span> <strong>GHS ${parseFloat(item.corp_copay_child || 0).toFixed(2)}</strong>
                            </div>
                        `;
                    } else {
                         copayDisplay = `<span class="copay-none">No Co-Pay</span>`;
                    }
                } else {
                    tariffDisplay = `<span style="color:#94a3b8; font-size:12px;">Not Mapped</span>`;
                }
            }

            const activeClass = item.is_active == 1 ? 'active' : 'inactive';
            const actionButtons = `
                <div class="actions-flex">
                    <button class="btn-action view" title="View Details"><i class="fa-solid fa-eye"></i></button>
                    <button class="btn-action edit" title="Edit Pricing" onclick="if(typeof loadContent === 'function') { loadContent('Edit Procedure', 'gdrg/editGdrg.php?id=${item.service_id}', 'Catalog', 'facility', null, true); }"><i class="fa-solid fa-pen"></i></button>
                    <button class="btn-action toggle ${activeClass}" title="${item.is_active == 1 ? 'Deactivate' : 'Activate'}"><i class="fa-solid fa-power-off"></i></button>
                    <button class="btn-action delete" title="Delete Rule"><i class="fa-solid fa-trash"></i></button>
                </div>
            `;

            tableRows += `
                <tr style="opacity: ${item.is_active == 1 ? '1' : '0.6'};">
                    <td style="font-weight:600; color:#94a3b8;">${globalIndex}</td>
                    <td style="width: 30%;">
                        <span class="service-name">${item.service_name}</span>
                        <span class="service-type">${item.service_type} • ${item.applicable_gender} • ${item.target_age_group}</span>
                    </td>
                    <td>${cashDisplay}</td>
                    <td>${tariffDisplay}</td>
                    <td>${copayDisplay}</td>
                    <td>${actionButtons}</td>
                </tr>
            `;
            globalIndex++;
        });

        const consultPill = dept.consults > 0 ? `<span class="meta-pill blue"><i class="fa-solid fa-stethoscope"></i> ${dept.consults} Consults</span>` : '';
        const isCorpView = (data.insurance_view === 'CORP');
        const insHeader = isCorpView ? 'Agreed Corporate Tariff' : 'NHIA Insured Tariffs';

        const accordionHtml = `
            <div class="dept-accordion">
                <div class="accordion-header">
                    <div class="dept-title"><i class="fa-solid fa-folder-open"></i> ${deptName}</div>
                    <div class="dept-meta">
                        <span class="meta-pill">Total: ${dept.items.length}</span>
                        ${consultPill}
                        <i class="fa-solid fa-chevron-down chevron-icon"></i>
                    </div>
                </div>
                <div class="accordion-body">
                    <table class="inner-table">
                        <thead>
                            <tr>
                                <th style="width:40px;">#</th>
                                <th>Service Profile</th>
                                <th>Base Cash (Adult/Child)</th>
                                <th>${insHeader}</th>
                                <th>Patient Co-Pay</th>
                                <th style="text-align:right;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>${tableRows}</tbody>
                    </table>
                </div>
            </div>
        `;
        
        container.insertAdjacentHTML('beforeend', accordionHtml);
    });

    window.updateCatPagination(data.total_records, data.total_pages, window.currentCatPage, data.limit);
};

window.updateCatPagination = function(totalRecords, totalPages, current, limit) {
    const prevBtn = document.getElementById('catPrev');
    const nextBtn = document.getElementById('catNext');
    const pageInfo = document.getElementById('catPageInfo');

    if(prevBtn) prevBtn.disabled = current <= 1;
    if(nextBtn) nextBtn.disabled = current >= totalPages || totalPages === 0;

    if(pageInfo) {
        if (totalRecords === 0) {
            pageInfo.textContent = `Showing 0 entries`;
        } else {
            const start = ((current - 1) * limit) + 1;
            const end = Math.min(current * limit, totalRecords);
            pageInfo.textContent = `Showing ${start} to ${end} of ${totalRecords} entries (Page ${current} of ${totalPages})`;
        }
    }
};

window.changeCatPage = function(direction) {
    window.fetchEnterpriseCatalog(window.currentCatPage + direction);
};