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

// 1. Fetch Summary Statistics for the Top Cards
$stats_query = "SELECT 
    COUNT(id) as total_services,
    SUM(CASE WHEN service_type = 'Consultation' THEN 1 ELSE 0 END) as total_consults,
    SUM(CASE WHEN service_type IN ('Procedure', 'Investigation') THEN 1 ELSE 0 END) as total_procedures
    FROM service_catalog";
$stats_result = $conn->query($stats_query);
$stats = $stats_result ? $stats_result->fetch_assoc() : ['total_services' => 0, 'total_consults' => 0, 'total_procedures' => 0];

// 2. Fetch Departments for the filter
$departments = [];
$dept_res = $conn->query("SELECT id, department_name FROM departments WHERE is_active = 1 ORDER BY department_name ASC");
if($dept_res) { while($row = $dept_res->fetch_assoc()) { $departments[] = $row; } }

// 3. Fetch Insurances for the Matrix View
$insurances = [];
$ins_res = $conn->query("SELECT id, insurance_name FROM insurance_type WHERE is_active = 1 ORDER BY insurance_name ASC");
if($ins_res) { while($row = $ins_res->fetch_assoc()) { $insurances[] = $row; } }
?>

<style>
/* Embedded CSS to guarantee SPA rendering */
.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; }

/* Top Stat Cards */
.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.orange { border-left-color: #f97316; }
.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 Filter Bar */
.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; }

/* Accordion Departments */
.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); }
.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; }
.accordion-header:hover { background: #f1f5f9; }
.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;}
.meta-pill.blue { background: #dbeafe; color: #1e40af; border-color: #bfdbfe; }
.chevron-icon { color: #94a3b8; transition: transform 0.3s ease; font-size: 18px; }

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

.service-name { font-weight: 700; color: #0f172a; margin-bottom: 4px; display: block; }
.service-type { font-size: 12px; color: #94a3b8; }
.cash-rate { font-weight: 800; color: #334155; }
.tariff-info { font-size: 12px; color: #64748b; line-height: 1.5; }
.tariff-val { font-weight: 700; color: #16a34a; }
.copay-badge { background: #fee2e2; color: #991b1b; padding: 4px 8px; border-radius: 6px; font-size: 11px; font-weight: 700; border: 1px solid #fecaca;}
.copay-none { color: #94a3b8; font-size: 12px;}

/* Action Buttons */
.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.view:hover { color: #3b82f6; border-color: #bfdbfe; background: #eff6ff; }
.btn-action.edit:hover { color: #f59e0b; border-color: #fde68a; background: #fffbeb; }
.btn-action.delete:hover { color: #ef4444; border-color: #fecaca; background: #fef2f2; }
.btn-action.toggle.active { color: #10b981; }
.btn-action.toggle.inactive { color: #94a3b8; opacity: 0.6; }
.btn-action.toggle.active:hover { background: #dcfce7; border-color: #bbf7d0; }

/* Pagination Area */
.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>

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" onload="
    if (typeof window.initCatalogUI === 'function') {
        window.initCatalogUI();
    } else {
        const s = document.createElement('script');
        s.src = '../../../assets/js/nhis-tariffs.js?v=' + new Date().getTime();
        s.onload = () => window.initCatalogUI();
        document.head.appendChild(s);
    }
    this.remove();
" style="display:none;">

<div class="catalog-container">
    <div class="header-flex">
        <h2><i class="fa-solid fa-layer-group"></i> Master Service Catalog</h2>
        <button onclick="if(typeof loadContent === 'function') { loadContent('Add New Procedure', 'gdrg/addNewGdrg.php', 'Procedures / Services', 'system_setup', null, true); } else { window.location.href='?cat=system_setup&page=gdrg/addNewGdrg.php'; }" class="btn-apply" style="background:#1e3a8a;">
            <i class="fa-solid fa-plus"></i> Add New Service
        </button>
    </div>

    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-info">
                <h4>Total Services</h4>
                <h3><?php echo number_format($stats['total_services']); ?></h3>
            </div>
            <div class="stat-icon"><i class="fa-solid fa-list-ul"></i></div>
        </div>
        <div class="stat-card purple">
            <div class="stat-info">
                <h4>Consultations</h4>
                <h3><?php echo number_format($stats['total_consults']); ?></h3>
            </div>
            <div class="stat-icon"><i class="fa-solid fa-user-doctor"></i></div>
        </div>
        <div class="stat-card orange">
            <div class="stat-info">
                <h4>Procedures / Labs</h4>
                <h3><?php echo number_format($stats['total_procedures']); ?></h3>
            </div>
            <div class="stat-icon"><i class="fa-solid fa-syringe"></i></div>
        </div>
    </div>

    <div class="advanced-filters">
        <div class="filter-group" style="flex: 2;">
            <label>Search Catalog</label>
            <div class="search-wrapper">
                <i class="fa-solid fa-magnifying-glass"></i>
                <input type="text" id="catSearch" class="filter-input search-input" placeholder="Search service name, GDRG code..." onkeyup="if(typeof window.debounceFetchCatalog === 'function') window.debounceFetchCatalog();">
            </div>
        </div>
        
        <div class="filter-group">
            <label>Department</label>
            <select id="catDept" class="filter-input" onchange="if(typeof window.fetchEnterpriseCatalog === 'function') window.fetchEnterpriseCatalog(1);">
                <option value="ALL">All Departments</option>
                <?php foreach($departments as $dept): ?>
                    <option value="<?php echo $dept['id']; ?>"><?php echo htmlspecialchars($dept['department_name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="filter-group">
            <label>Service Modality</label>
            <select id="catModality" class="filter-input" onchange="if(typeof window.fetchEnterpriseCatalog === 'function') window.fetchEnterpriseCatalog(1);">
                <option value="ALL">All Modalities</option>
                <option value="Consultation">Consultation</option>
                <option value="Procedure">Procedure</option>
                <option value="Investigation">Investigation / Lab</option>
            </select>
        </div>

        <div class="filter-group">
            <label>Insurance Partner</label>
            <select id="catInsurance" class="filter-input" style="color:#0f172a; font-weight:600; background:#f8fafc; border-color:#cbd5e1;" onchange="if(typeof window.fetchEnterpriseCatalog === 'function') window.fetchEnterpriseCatalog(1);">
                <option value="ALL">Default (NHIA View)</option>
                <?php foreach($insurances as $ins): ?>
                    <option value="<?php echo $ins['id']; ?>"><?php echo htmlspecialchars($ins['insurance_name']); ?> Matrix</option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="filter-group" style="min-width: 80px;">
            <label>Records</label>
            <select id="catLimit" class="filter-input" onchange="if(typeof window.fetchEnterpriseCatalog === 'function') window.fetchEnterpriseCatalog(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.fetchEnterpriseCatalog === 'function') window.fetchEnterpriseCatalog(1);"><i class="fa-solid fa-filter"></i> Apply Filters</button>
    </div>

    <div id="catalogAccordionContainer">
        <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 Enterprise Catalog...
        </div>
    </div>

    <div class="pagination-container">
        <div id="catPageInfo" 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="catPrev" class="page-btn" onclick="if(typeof window.changeCatPage === 'function') window.changeCatPage(-1);" disabled>Previous</button>
            <button id="catNext" class="page-btn" onclick="if(typeof window.changeCatPage === 'function') window.changeCatPage(1);" disabled>Next</button>
        </div>
    </div>

</div>