window.currentCorpPage = 1;
window.corpSearchTimeout = null;

window.initCorporateInsurance = function() {
    window.fetchCorpData(1);
};

window.debounceFetchCorp = function() {
    clearTimeout(window.corpSearchTimeout);
    window.corpSearchTimeout = setTimeout(() => { window.fetchCorpData(1); }, 400); 
};

window.fetchCorpData = function(page = 1) {
    window.currentCorpPage = page;
    const container = document.getElementById('corpAccordionContainer');
    if(!container) return;

    const search = document.getElementById('corpSearch') ? document.getElementById('corpSearch').value : '';
    const limit = document.getElementById('corpLimit') ? document.getElementById('corpLimit').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 Insurance Matrix...</div>';

    // Resolve URL using absolute window anchor context instead of breaking with relative paths '../../../'
    const appBase = window.rimaxAppRoot || '/rimax/application';

    fetch(appBase + '/dripend/systemSetup/insurance/fetch_corporate_insurance.php?page=' + page + '&limit=' + limit + '&search=' + encodeURIComponent(search))
        .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.renderCorpData(data);
            } catch (e) {
                container.innerHTML = '<div style="padding: 20px; color:#dc2626; background:#fef2f2; border:1px solid #fecaca; border-radius:12px;"><strong>Server JSON Error:</strong><br><textarea style="width:100%; height:100px;">' + text + '</textarea></div>';
            }
        })
        .catch(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>';
        });
};

window.renderCorpData = function(data) {
    const container = document.getElementById('corpAccordionContainer');
    
    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 providers or mappings found.</div>';
        window.updateCorpPagination(0, 0, 0, 0);
        return;
    }

    const grouped = data.records.reduce((acc, curr) => {
        const provName = curr.provider_name || 'Unknown Provider';
        if (!acc[provName]) { 
            acc[provName] = { id: curr.provider_id, status: curr.provider_status, procedures: [] }; 
        }
        if (curr.map_id) { acc[provName].procedures.push(curr); }
        return acc;
    }, {});

    let finalHtml = ''; 

    Object.keys(grouped).forEach(provName => {
        const groupData = grouped[provName];
        const procedures = groupData.procedures;
        const safeId = 'acc-prov-' + groupData.id;
        
        const provStatusBadge = groupData.status == 1 
            ? '<span style="background:#dcfce7; color:#16a34a; padding:4px 8px; border-radius:6px; font-size:11px; font-weight:700;"><i class="fa-solid fa-circle-check"></i> Active</span>'
            : '<span style="background:#fee2e2; color:#dc2626; padding:4px 8px; border-radius:6px; font-size:11px; font-weight:700;"><i class="fa-solid fa-ban"></i> Suspended</span>';

        let tableRows = '';
        
        if (procedures.length === 0) {
            tableRows = '<tr><td colspan="6" style="text-align:center; color:#94a3b8; padding:30px;">No procedures mapped to this provider yet. Click "Map Procedure" to begin.</td></tr>';
        } else {
            procedures.forEach((item, index) => {
                
                const cAdult = parseFloat(item.cash_price_adult) || 0;
                const cChild = parseFloat(item.cash_price_child) || 0;
                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 ${cAdult.toFixed(2)}</strong><br>
                        <span style="display:inline-block; width:35px;">Chld:</span> <strong style="color:#0f172a;">GHS ${cChild.toFixed(2)}</strong>
                    </div>
                `;

                const copayBadge = item.is_copay_required == 1
                    ? `<div style="font-size: 12px; color: #b45309; line-height:1.6;">
                           <span style="display:inline-block; width:35px;">Adlt:</span> <strong>GHS ${parseFloat(item.copay_amount_adult || 0).toFixed(2)}</strong><br>
                           <span style="display:inline-block; width:35px;">Chld:</span> <strong>GHS ${parseFloat(item.copay_amount_child || 0).toFixed(2)}</strong>
                       </div>`
                    : '<span style="color:#94a3b8; font-size:12px;">No Co-Pay</span>';

                const actionButtons = `
                    <div class="actions-flex">
                        <button class="btn-action edit" title="Edit Tariff" onclick="if(typeof loadContent === 'function') { loadContent('Edit Tariff', 'insurance/editTariff.php?id=${item.map_id}', 'Insurance', 'system_setup', null, true); }"><i class="fa-solid fa-pen"></i></button>
                        <button class="btn-action delete" title="Unlink Procedure" onclick="if(confirm('Remove this procedure from ${provName}?')) { if(typeof loadContent === 'function') { loadContent('Delete Mapping', 'insurance/deleteTariff.php?id=${item.map_id}', 'Insurance', 'system_setup', null, true); } }"><i class="fa-solid fa-link-slash"></i></button>
                    </div>
                `;

                tableRows += `
                    <tr>
                        <td style="width: 40px; font-weight:600; color:#94a3b8;">${index + 1}</td>
                        <td>
                            <span class="desc-text" style="display:block; margin-bottom:4px;">${item.service_name}</span>
                            <span class="code-badge" style="font-size:11px;"><i class="fa-solid fa-barcode"></i> GDRG: ${item.gdrg_adult_code || 'N/A'}</span>
                        </td>
                        <td>${cashDisplay}</td>
                        <td class="money-text">GHS ${parseFloat(item.tariff_amount || 0).toFixed(2)}</td>
                        <td>${copayBadge}</td>
                        <td style="text-align:right;">${actionButtons}</td>
                    </tr>
                `;
            });
        }

        finalHtml += `
            <div class="dept-accordion">
                <input type="checkbox" id="${safeId}" class="acc-toggle">
                <label class="accordion-header" for="${safeId}">
                    <div class="dept-title"><i class="fa-solid fa-briefcase-medical"></i> ${provName} ${provStatusBadge}</div>
                    <div class="dept-meta">
                        <span class="meta-pill"><i class="fa-solid fa-list-check"></i> ${procedures.length} Mapped Procedures</span>
                        <i class="fa-solid fa-chevron-down chevron-icon"></i>
                    </div>
                </label>
                <div class="accordion-body">
                    <table class="inner-table">
                        <thead>
                            <tr>
                                <th style="width:40px;">#</th>
                                <th>Service / Procedure Name</th>
                                <th>Base Cash Rate (A/C)</th>
                                <th>Agreed Tariff Cap</th>
                                <th>Patient Co-Pay Rule</th>
                                <th style="text-align:right;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>${tableRows}</tbody>
                    </table>
                </div>
            </div>
        `;
    });
    
    container.innerHTML = finalHtml;
    window.updateCorpPagination(data.total_records, data.total_pages, window.currentCorpPage, data.limit);
};

window.updateCorpPagination = function(totalRecords, totalPages, current, limit) {
    const prevBtn = document.getElementById('corpPrev');
    const nextBtn = document.getElementById('corpNext');
    const pageInfo = document.getElementById('corpPageInfo');

    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.changeCorpPage = function(direction) {
    window.fetchCorpData(window.currentCorpPage + direction);
};