<?php
// Connect to the database
require_once '../../../dripend/includes/db.php';

// Fetch Summary Statistics
$stats_query = "SELECT 
    COUNT(id) as total_mappings,
    COUNT(DISTINCT gdrg_code) as total_gdrgs_mapped,
    COUNT(DISTINCT icd10_code) as total_icds_mapped
    FROM gdrg_icd_mapping";
$stats_result = $conn->query($stats_query);
$stats = $stats_result ? $stats_result->fetch_assoc() : ['total_mappings' => 0, 'total_gdrgs_mapped' => 0, 'total_icds_mapped' => 0];
?>

<style>
/* Enterprise SPA Styles & Pure CSS Accordion */
.catalog-container { font-family: "Segoe UI", system-ui, sans-serif; animation: fadeIn 0.3s ease; }
.header-flex { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
.header-flex h2 { color: #1e3a8a; font-size: 24px; font-weight: 800; display: flex; align-items: center; gap: 10px; text-transform: uppercase; margin: 0; }

.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 24px; }
.stat-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 12px; padding: 20px; display: flex; justify-content: space-between; align-items: center; border-left: 4px solid #1e3a8a; box-shadow: 0 2px 4px rgba(0,0,0,0.02); }
.stat-card.purple { border-left-color: #8b5cf6; }
.stat-card.green { border-left-color: #10b981; }
.stat-info h4 { font-size: 11px; color: #64748b; text-transform: uppercase; font-weight: 700; margin: 0 0 8px 0; letter-spacing: 0.5px; }
.stat-info h3 { font-size: 28px; color: #0f172a; margin: 0; font-weight: 800; }
.stat-icon { font-size: 32px; color: #f1f5f9; }

.advanced-filters { background: #fff; border: 1px solid #e2e8f0; border-radius: 12px; padding: 20px; margin-bottom: 24px; display: flex; gap: 15px; align-items: flex-end; flex-wrap: wrap; box-shadow: 0 2px 4px rgba(0,0,0,0.02); }
.filter-group { display: flex; flex-direction: column; gap: 6px; flex: 1; min-width: 180px; }
.filter-group label { font-size: 11px; font-weight: 700; color: #64748b; text-transform: uppercase; }
.search-wrapper { position: relative; width: 100%; }
.search-wrapper i { position: absolute; left: 14px; top: 14px; color: #94a3b8; font-size: 14px; }
.filter-input { width: 100%; padding: 10px 14px; border: 1px solid #cbd5e1; border-radius: 8px; font-size: 14px; color: #334155; outline: none; box-sizing: border-box; background: #fff; }
.search-input { padding-left: 36px !important; }
.filter-input:focus { border-color: #1e3a8a; }

.btn-apply { background: #16a34a; color: #fff; border: none; padding: 10px 24px; border-radius: 8px; font-weight: 700; font-size: 14px; cursor: pointer; display: flex; align-items: center; gap: 8px; height: 42px; transition: 0.2s; white-space: nowrap; }
.btn-apply:hover { background: #15803d; }

/* CSS Accordions */
.dept-accordion { background: #fff; border: 1px solid #e2e8f0; border-radius: 12px; margin-bottom: 16px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.02); }
.acc-toggle { display: none; }
.accordion-header { padding: 16px 24px; background: #fafaf9; cursor: pointer; display: flex; justify-content: space-between; align-items: center; user-select: none; transition: background 0.2s; margin: 0; }
.accordion-header:hover { background: #f1f5f9; }
.accordion-body { display: none; border-top: 1px solid #e2e8f0; }
.acc-toggle:checked ~ .accordion-body { display: block; animation: slideDown 0.3s ease-out forwards; }
.acc-toggle:checked + .accordion-header .chevron-icon { transform: rotate(180deg); color: #1e3a8a; }
@keyframes slideDown { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }

.dept-title { font-size: 16px; font-weight: 800; color: #1e3a8a; display: flex; align-items: center; gap: 10px; }
.dept-meta { display: flex; align-items: center; gap: 12px; }
.meta-pill { background: #f1f5f9; color: #475569; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 700; border: 1px solid #e2e8f0;}
.chevron-icon { color: #94a3b8; transition: transform 0.3s ease; font-size: 18px; }

/* Inner Table */
.inner-table { width: 100%; border-collapse: collapse; text-align: left; }
.inner-table th { padding: 12px 24px; font-size: 11px; font-weight: 800; color: #64748b; text-transform: uppercase; border-bottom: 1px solid #e2e8f0; background: #fff; }
.inner-table td { padding: 12px 24px; font-size: 14px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; color: #334155; }
.inner-table tr:hover { background: #f8fafc; }

.code-badge { background: #e0e7ff; color: #1e40af; padding: 4px 10px; border-radius: 6px; font-weight: 700; font-size: 13px; border: 1px solid #bfdbfe; display: inline-block; }
.desc-text { font-weight: 600; color: #0f172a; }

.actions-flex { display: flex; gap: 6px; justify-content: flex-end; }
.btn-action { width: 32px; height: 32px; border-radius: 6px; border: 1px solid #e2e8f0; background: #fff; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: 0.2s; color: #64748b; }
.btn-action:hover { background: #f1f5f9; color: #0f172a; }
.btn-action.delete:hover { color: #ef4444; border-color: #fecaca; background: #fef2f2; }

.pagination-container { display: flex; justify-content: space-between; align-items: center; padding: 20px 0; }
.page-btn { padding: 8px 16px; border: 1px solid #cbd5e1; background: #fff; border-radius: 6px; font-weight: 600; color: #334155; cursor: pointer; }
.page-btn:disabled { opacity: 0.5; cursor: not-allowed; }
</style>

<textarea id="mapping-app-core" style="display:none;">
    window.currentMapPage = 1;
    window.mapSearchTimeout = null;

    window.debounceFetchMapping = function() {
        clearTimeout(window.mapSearchTimeout);
        window.mapSearchTimeout = setTimeout(() => { window.fetchMappingData(1); }, 400); 
    };

    window.fetchMappingData = function(page = 1) {
        window.currentMapPage = page;
        const container = document.getElementById('mappingAccordionContainer');
        if(!container) return;

        const search = document.getElementById('mapSearch') ? document.getElementById('mapSearch').value : '';
        const limit = document.getElementById('mapLimit') ? document.getElementById('mapLimit').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 Mappings...</div>';

        fetch('../../dripend/systemSetup/gdrg/fetch_gdrg_icd_mapping.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.renderMappingData(data);
                } catch (e) {
                    // FIXED: Split the closing tag so the browser doesn't freak out!
                    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 + '</text' + 'area></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.renderMappingData = function(data) {
        const container = document.getElementById('mappingAccordionContainer');
        
        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 mappings found matching your criteria.</div>';
            window.updateMapPagination(0, 0, 0, 0);
            return;
        }

        const grouped = data.records.reduce((acc, curr) => {
            const gdrgRaw = String(curr.gdrg_code).trim();
            const gdrgDesc = curr.gdrg_desc || 'Pending Update';
            const gdrgKey = gdrgRaw + ' - ' + gdrgDesc;
            
            if (!acc[gdrgKey]) { acc[gdrgKey] = { code: gdrgRaw, items: [] }; }
            acc[gdrgKey].items.push(curr);
            return acc;
        }, {});

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

        Object.keys(grouped).forEach(gdrgKey => {
            const groupData = grouped[gdrgKey];
            const mappedItems = groupData.items;
            const safeId = 'acc-' + groupData.code.replace(/[^a-zA-Z0-9]/g, '');
            
            let tableRows = '';
            mappedItems.forEach(item => {
                const actionButtons = `
                    <div class="actions-flex">
                        <button class="btn-action delete" title="Unlink ICD-10" onclick="if(confirm(\\'Are you sure you want to remove ICD ' + item.icd10_code + ' from GDRG ' + item.gdrg_code + '?\\')) { if(typeof loadContent === \\'function\\') { loadContent(\\'Delete Mapping\\', \\'gdrg/deleteMapping.php?id=' + item.id + '\\', \\'Mapping\\', \\'facility\\', null, true); } }"><i class="fa-solid fa-link-slash"></i></button>
                    </div>
                `;

                tableRows += `
                    <tr>
                        <td style="width: 40px; font-weight:600; color:#94a3b8;">${globalIndex}</td>
                        <td style="width: 150px;"><span class="code-badge">${String(item.icd10_code).trim()}</span></td>
                        <td><span class="desc-text">${item.icd10_desc}</span></td>
                        <td style="text-align:right;">${actionButtons}</td>
                    </tr>
                `;
                globalIndex++;
            });

            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-layer-group"></i> ${gdrgKey}</div>
                        <div class="dept-meta">
                            <span class="meta-pill">Mapped ICD Codes: ${mappedItems.length}</span>
                            <i class="fa-solid fa-chevron-down chevron-icon"></i>
                        </div>
                    </label>
                    <div class="accordion-body">
                        <table class="inner-table">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>ICD-10 Code</th>
                                    <th>ICD-10 Description</th>
                                    <th style="text-align:right;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>${tableRows}</tbody>
                        </table>
                    </div>
                </div>
            `;
        });
        
        container.innerHTML = finalHtml;
        window.updateMapPagination(data.total_records, data.total_pages, window.currentMapPage, data.limit);
    };

    window.updateMapPagination = function(totalRecords, totalPages, current, limit) {
        const prevBtn = document.getElementById('mapPrev');
        const nextBtn = document.getElementById('mapNext');
        const pageInfo = document.getElementById('mapPageInfo');

        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.changeMapPage = function(direction) {
        window.fetchMappingData(window.currentMapPage + direction);
    };
</textarea>

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" onload="
    // Use an absolute path for the JS source to prevent '404 not found' on the live server
    const script = document.createElement('script');
    script.src = '/rimax/application/assets/js/drg-icd-mapping.js?v=' + new Date().getTime();
    document.head.appendChild(script);
    
    // Slight delay to ensure the script is loaded before calling
    setTimeout(function() { 
        if(typeof window.fetchMappingData === 'function') { 
            window.fetchMappingData(1); 
        } 
    }, 100);
    this.remove();
" style="display:none;">

<div class="catalog-container">
    <div class="header-flex">
        <h2><i class="fa-solid fa-link"></i> GDRG to ICD-10 Mapping</h2>
        <button class="btn-apply" style="background:#1e3a8a;" onclick="if(typeof loadContent === 'function') { loadContent('Add New Mapping', 'gdrg/addMapping.php', 'Mapping', 'facility', null, true); }">
            <i class="fa-solid fa-plus"></i> Add New Mapping
        </button>
    </div>

    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-info">
                <h4>Total Active Mappings</h4>
                <h3><?php echo number_format($stats['total_mappings']); ?></h3>
            </div>
            <div class="stat-icon"><i class="fa-solid fa-link"></i></div>
        </div>
        <div class="stat-card purple">
            <div class="stat-info">
                <h4>Mapped GDRGs</h4>
                <h3><?php echo number_format($stats['total_gdrgs_mapped']); ?></h3>
            </div>
            <div class="stat-icon"><i class="fa-solid fa-layer-group"></i></div>
        </div>
        <div class="stat-card green">
            <div class="stat-info">
                <h4>Mapped ICD-10 Codes</h4>
                <h3><?php echo number_format($stats['total_icds_mapped']); ?></h3>
            </div>
            <div class="stat-icon"><i class="fa-solid fa-barcode"></i></div>
        </div>
    </div>

    <div class="advanced-filters">
        <div class="filter-group" style="flex: 3;">
            <label>Search Mappings</label>
            <div class="search-wrapper">
                <i class="fa-solid fa-magnifying-glass"></i>
                <input type="text" id="mapSearch" class="filter-input search-input" placeholder="Search GDRG code, ICD code, or description..." onkeyup="if(typeof window.debounceFetchMapping === 'function') window.debounceFetchMapping();">
            </div>
        </div>

        <div class="filter-group" style="flex: 1; min-width: 100px;">
            <label>Records</label>
            <select id="mapLimit" class="filter-input" onchange="if(typeof window.fetchMappingData === 'function') window.fetchMappingData(1);">
                <option value="25">25</option>
                <option value="50" selected>50</option>
                <option value="100">100</option>
                <option value="500">500</option>
            </select>
        </div>

        <button type="button" class="btn-apply" onclick="if(typeof window.fetchMappingData === 'function') window.fetchMappingData(1);"><i class="fa-solid fa-filter"></i> Search</button>
    </div>

    <div id="mappingAccordionContainer">
        <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>Loading Mapping Data...
        </div>
    </div>

    <div class="pagination-container">
        <div id="mapPageInfo" style="font-size:13px; font-weight:600; color:#64748b;">Showing 0 to 0 of 0 entries</div>
        <div style="display:flex; gap:8px;">
            <button id="mapPrev" class="page-btn" onclick="if(typeof window.changeMapPage === 'function') window.changeMapPage(-1);" disabled>Previous</button>
            <button id="mapNext" class="page-btn" onclick="if(typeof window.changeMapPage === 'function') window.changeMapPage(1);" disabled>Next</button>
        </div>
    </div>
</div>