<?php
// 1. Structural File System Path Resolution (Safe for any OS)
require_once __DIR__ . '/../../../dripend/includes/db.php';

// 2. Dynamic Web URL Root Sniffer (Auto-detects localhost subdirectories or production domain roots)
$requestRoot = '';
if (strpos($_SERVER['SCRIPT_NAME'], '/application/') !== false) {
    $requestRoot = explode('/application/', $_SERVER['SCRIPT_NAME'])[0] . '/application';
} else {
    $requestRoot = dirname(dirname(dirname($_SERVER['SCRIPT_NAME'])));
}
$requestRoot = rtrim($requestRoot, '/\\');

$stats = ['total_providers' => 0, 'active_providers' => 0, 'total_tariffs' => 0];

try {
    $prov_res = $conn->query("SELECT COUNT(id) as total, SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active FROM insurance_type");
    if ($prov_res && $row = $prov_res->fetch_assoc()) {
        $stats['total_providers'] = (int)$row['total'];
        $stats['active_providers'] = (int)$row['active'];
    }

    $tariff_res = $conn->query("SELECT COUNT(id) as total FROM service_corporate_tariffs");
    if ($tariff_res && $row = $tariff_res->fetch_assoc()) {
        $stats['total_tariffs'] = (int)$row['total'];
    }
} catch (Exception $e) {
    // Fails silently if an error occurs
}
?>

<style>
.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; flex-wrap: wrap; gap: 15px;}
.header-flex h2 { color: #1e3a8a; font-size: 24px; font-weight: 800; display: flex; align-items: center; gap: 10px; text-transform: uppercase; margin: 0; }
.header-actions { display: flex; gap: 10px; }

.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; }
.btn-primary-alt { background: #1e3a8a; }
.btn-primary-alt:hover { background: #1e40af; }
.btn-amber { background: #f59e0b; color: #fff; }
.btn-amber:hover { background: #d97706; }

.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 { 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; }
.money-text { font-family: monospace; font-weight: 800; color: #059669; font-size: 15px; }

.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.edit:hover { color: #f59e0b; border-color: #fde68a; background: #fffbeb; }
.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>

<script>
    window.rimaxAppRoot = '<?php echo $requestRoot; ?>';
</script>

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

<div class="catalog-container">
    
    <div class="header-flex">
        <h2><i class="fa-solid fa-handshake"></i> Corporate Insurance & HMOs</h2>
        
        <div class="header-actions">
            <button class="btn-apply btn-primary-alt" onclick="if(typeof loadContent === 'function') { loadContent('Add Provider', 'insurance/addCoporateInsuranceProvider.php', 'Insurance', 'system_setup', null, true); }">
                <i class="fa-solid fa-building-user"></i> Add New Provider
            </button>
            
            <button class="btn-apply btn-amber" onclick="if(typeof loadContent === 'function') { loadContent('Map Procedure', 'insurance/mapCorporateInsurance.php', 'Insurance', 'system_setup', null, true); }">
                <i class="fa-solid fa-link"></i> Map Procedure
            </button>
        </div>
    </div>

    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-info">
                <h4>Total Providers</h4>
                <h3><?php echo number_format($stats['total_providers']); ?></h3>
            </div>
            <div class="stat-icon"><i class="fa-solid fa-building"></i></div>
        </div>
        <div class="stat-card green">
            <div class="stat-info">
                <h4>Active Providers</h4>
                <h3><?php echo number_format($stats['active_providers']); ?></h3>
            </div>
            <div class="stat-icon"><i class="fa-solid fa-circle-check"></i></div>
        </div>
        <div class="stat-card purple">
            <div class="stat-info">
                <h4>Total Mapped Procedures</h4>
                <h3><?php echo number_format($stats['total_tariffs']); ?></h3>
            </div>
            <div class="stat-icon"><i class="fa-solid fa-list-check"></i></div>
        </div>
    </div>

    <div class="advanced-filters">
        <div class="filter-group" style="flex: 3;">
    <label>Search Directory</label>
    <div class="search-wrapper">
        <i class="fa-solid fa-magnifying-glass"></i>
        <input type="text" id="corpSearch" class="filter-input search-input" placeholder="Search Provider Name or Procedure..." onkeyup="if(typeof window.debounceFetchCorp === 'function') window.debounceFetchCorp();">
            </div>
        </div>

        <div class="filter-group" style="flex: 1; min-width: 100px;">
            <label>Records Per Page</label>
            <select id="corpLimit" class="filter-input" onchange="if(typeof window.fetchCorpData === 'function') window.fetchCorpData(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.fetchCorpData === 'function') window.fetchCorpData(1);"><i class="fa-solid fa-filter"></i> Filter</button>
    </div>

    <div id="corpAccordionContainer">
        <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 Insurance Matrix...
        </div>
    </div>

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

</div>