<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../../dripend/includes/db.php';

// ==============================================================================
// 1. FETCH FILTER DICTIONARIES
// ==============================================================================
$departments = $conn->query("SELECT id, department_name FROM departments ORDER BY department_name ASC")->fetch_all(MYSQLI_ASSOC);
$insurances = $conn->query("SELECT id, insurance_name FROM insurance_type WHERE LOWER(insurance_name) NOT IN ('nhis', 'cash') AND is_active = 1 ORDER BY insurance_name ASC")->fetch_all(MYSQLI_ASSOC);

// ==============================================================================
// 2. DYNAMIC SQL SEARCH & FILTER ENGINE
// ==============================================================================
$search_text = $_GET['search'] ?? '';
$filter_dept = $_GET['department_id'] ?? '';
$filter_type = $_GET['service_type'] ?? '';
$filter_ins_id = !empty($_GET['provider_id']) ? (int)$_GET['provider_id'] : null;

// Base SELECT clause
$query = "SELECT sc.*, d.department_name ";
if ($filter_ins_id) {
    $query .= ", sct.tariff_amount AS corp_tariff, sct.is_copay_required AS corp_req, sct.copay_amount AS corp_copay ";
}
$query .= "FROM service_catalog sc LEFT JOIN departments d ON sc.department_id = d.id ";

if ($filter_ins_id) {
    $query .= "LEFT JOIN service_corporate_tariffs sct ON sc.id = sct.service_id AND sct.insurance_type_id = ? ";
}

// Build strictly bound WHERE clauses
$conditions = ["sc.is_active = 1"];
$params = [];
$types = "";

if ($filter_ins_id) {
    $params[] = $filter_ins_id;
    $types .= "i";
}
if ($search_text !== '') {
    $conditions[] = "(sc.service_name LIKE ? OR sc.gdrg_adult_code LIKE ? OR sc.gdrg_child_code LIKE ?)";
    $search_param = "%{$search_text}%";
    array_push($params, $search_param, $search_param, $search_param);
    $types .= "sss";
}
if ($filter_dept !== '') {
    $conditions[] = "sc.department_id = ?";
    $params[] = (int)$filter_dept;
    $types .= "i";
}
if ($filter_type !== '') {
    $conditions[] = "sc.service_type = ?";
    $params[] = $filter_type;
    $types .= "s";
}

$query .= " WHERE " . implode(" AND ", $conditions) . " ORDER BY d.department_name ASC, sc.service_name ASC";

$stmt = $conn->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$services = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// ==============================================================================
// 3. ENTERPRISE GROUPING & KPI CALCULATION (RESPONSIVE TO FILTERS)
// ==============================================================================
$grouped_services = [];
$kpis = [
    'total_services' => 0,
    'consultations' => 0,
    'procedures' => 0,
    'investigations' => 0
];

foreach ($services as $s) {
    $dept = $s['department_name'] ?: 'Unassigned / General';
    
    if (!isset($grouped_services[$dept])) {
        $grouped_services[$dept] = [
            'services' => [],
            'stats' => ['total' => 0, 'consults' => 0, 'others' => 0]
        ];
    }
    
    $grouped_services[$dept]['services'][] = $s;
    $grouped_services[$dept]['stats']['total']++;
    $kpis['total_services']++;
    
    if ($s['is_consultation'] == 1) {
        $grouped_services[$dept]['stats']['consults']++;
        $kpis['consultations']++;
    } else {
        $grouped_services[$dept]['stats']['others']++;
        if (strtolower($s['service_type']) === 'procedure') $kpis['procedures']++;
        if (strtolower($s['service_type']) === 'investigation') $kpis['investigations']++;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Service & GDRG Catalog | Enterprise</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
    :root { --sidebar-width: 240px; --e-blue: #1e3a8a; --e-green: #16a34a; --bg: #f8fafc; --border: #e2e8f0; --text: #334155; }
    body { font-family: "Segoe UI", system-ui, sans-serif; background: var(--bg); margin: 0; padding: 0; color: var(--text); overflow-x: hidden; }
    
    .page-wrapper { position: absolute; top: 0; left: var(--sidebar-width); width: calc(100% - var(--sidebar-width)); min-height: 100vh; padding: 30px; display: block !important; box-sizing: border-box; }
    
    .header-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
    .header-bar h2 { color: var(--e-blue); margin: 0; font-size: 24px; font-weight: 800; text-transform: uppercase; }
    .btn-add { background: var(--e-blue); color: #fff; padding: 12px 20px; text-decoration: none; border-radius: 8px; font-weight: bold; box-shadow: 0 4px 6px rgba(30, 58, 138, 0.2); transition: 0.2s; display: inline-flex; align-items: center; gap: 8px; }
    .btn-add:hover { background: #172554; transform: translateY(-2px); }

    /* KPI DASHBOARD */
    .kpi-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; margin-bottom: 25px; }
    .kpi-card { background: #fff; padding: 20px; border-radius: 12px; border: 1px solid var(--border); border-left: 5px solid var(--e-blue); box-shadow: 0 4px 10px rgba(0,0,0,0.02); display: flex; justify-content: space-between; align-items: center; }
    .kpi-card.green { border-left-color: var(--e-green); }
    .kpi-card.purple { border-left-color: #8b5cf6; }
    .kpi-card.orange { border-left-color: #f97316; }
    .kpi-info h3 { margin: 0 0 5px 0; font-size: 13px; color: #64748b; text-transform: uppercase; font-weight: 700; }
    .kpi-info p { margin: 0; font-size: 26px; font-weight: 800; color: #0f172a; }
    .kpi-icon { font-size: 30px; color: #e2e8f0; }

    /* FILTERS */
    .filter-panel { background: #fff; padding: 20px; border-radius: 12px; margin-bottom: 25px; border: 1px solid var(--border); box-shadow: 0 4px 10px rgba(0,0,0,0.02); }
    .filter-grid { display: grid; grid-template-columns: 2fr 1.5fr 1.5fr 1.5fr auto; gap: 15px; align-items: end; }
    .filter-group { display: flex; flex-direction: column; gap: 6px; }
    .filter-group label { font-size: 12px; font-weight: 700; color: #64748b; text-transform: uppercase; }
    .filter-control { padding: 11px 12px; border-radius: 6px; border: 1px solid #cbd5e1; outline: none; font-size: 14px; background: #fff; }
    .filter-control:focus { border-color: var(--e-blue); box-shadow: 0 0 0 3px #eff6ff; }
    .btn-filter { background: var(--e-green); color: #fff; border: none; padding: 12px 25px; border-radius: 6px; font-weight: bold; cursor: pointer; transition: 0.2s; height: 42px; }
    .btn-filter:hover { background: #15803d; }
    .btn-reset { color: #64748b; text-decoration: none; font-size: 13px; font-weight: 700; display: inline-block; margin-top: 12px; }
    .btn-reset:hover { color: #dc2626; }

    /* ACCORDION UI */
    .accordion-item { margin-bottom: 15px; border: 1px solid var(--border); border-radius: 10px; background: #fff; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.02); }
    .accordion-header { padding: 18px 20px; background: #f8fafc; display: flex; justify-content: space-between; align-items: center; cursor: pointer; transition: background 0.2s; user-select: none; }
    .accordion-header:hover { background: #f1f5f9; }
    .accordion-title { font-weight: 800; color: var(--e-blue); font-size: 17px; display: flex; align-items: center; gap: 10px; }
    .accordion-stats { display: flex; gap: 8px; align-items: center; }
    .accordion-toggle-icon { font-size: 18px; color: #94a3b8; transition: transform 0.3s ease; }
    .accordion-item.active .accordion-toggle-icon { transform: rotate(180deg); color: var(--e-blue); }
    .accordion-item.active .accordion-header { border-bottom: 1px solid var(--border); background: #fff; }
    
    .accordion-body { display: none; padding: 0; background: #fff; }
    .accordion-item.active .accordion-body { display: block; }

    /* TABLE STYLES */
    table { width: 100%; border-collapse: collapse; }
    th { background: #fff; color: #64748b; padding: 14px 20px; font-size: 12px; text-transform: uppercase; border-bottom: 2px solid var(--border); text-align: left; }
    td { padding: 16px 20px; border-bottom: 1px solid var(--border); font-size: 14px; vertical-align: middle; }
    tr:last-child td { border-bottom: none; }
    tr:hover { background: #f8fafc; }
    
    .badge { padding: 5px 10px; border-radius: 6px; font-size: 11px; font-weight: 800; display: inline-flex; align-items: center; gap: 5px; white-space: nowrap; }
    .bg-green { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
    .bg-blue { background: #dbeafe; color: #1e40af; border: 1px solid #bfdbfe; }
    .bg-red { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }
    .bg-gray { background: #f1f5f9; color: #475569; border: 1px solid #e2e8f0; }

    .matrix-alert { background: #eff6ff; color: #1e40af; padding: 12px 20px; border-radius: 8px; margin-bottom: 20px; font-size: 14px; font-weight: 700; border: 1px solid #bfdbfe; display: flex; align-items: center; gap: 10px; }
</style>
</head>
<body>

<?php include('../../dripend/statpages/sidebar.php'); ?>

<div class="page-wrapper">
    <div class="header-bar">
        <h2><i class="fa-solid fa-layer-group"></i> Enterprise Catalog Rules</h2>
        <a href="addGdrgProcedures.php" class="btn-add"><i class="fa-solid fa-plus"></i> Configure New Service</a>
    </div>

    <!-- LIVE KPI DASHBOARD -->
    <div class="kpi-grid">
        <div class="kpi-card">
            <div class="kpi-info"><h3>Total Services</h3><p><?= number_format($kpis['total_services']) ?></p></div>
            <i class="fa-solid fa-list kpi-icon"></i>
        </div>
        <div class="kpi-card purple">
            <div class="kpi-info"><h3>Consultations</h3><p><?= number_format($kpis['consultations']) ?></p></div>
            <i class="fa-solid fa-user-doctor kpi-icon"></i>
        </div>
        <div class="kpi-card orange">
            <div class="kpi-info"><h3>Procedures</h3><p><?= number_format($kpis['procedures']) ?></p></div>
            <i class="fa-solid fa-syringe kpi-icon"></i>
        </div>
        <div class="kpi-card green">
            <div class="kpi-info"><h3>Investigations</h3><p><?= number_format($kpis['investigations']) ?></p></div>
            <i class="fa-solid fa-microscope kpi-icon"></i>
        </div>
    </div>

    <!-- ADVANCED FILTERS -->
    <div class="filter-panel">
        <form method="GET" action="">
            <div class="filter-grid">
                <div class="filter-group">
                    <label>Search Directory</label>
                    <input type="text" name="search" class="filter-control" placeholder="Search service name, GDRG..." value="<?= htmlspecialchars($search_text) ?>">
                </div>
                
                <!-- NEW: DEPARTMENT FILTER -->
                <div class="filter-group">
                    <label>Department</label>
                    <select name="department_id" class="filter-control">
                        <option value="">All Departments</option>
                        <?php foreach($departments as $dept): ?>
                            <option value="<?= $dept['id'] ?>" <?= $filter_dept == $dept['id'] ? 'selected' : '' ?>><?= htmlspecialchars($dept['department_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="filter-group">
                    <label>Service Modality</label>
                    <select name="service_type" class="filter-control">
                        <option value="">All Modalities</option>
                        <option value="Procedure" <?= $filter_type == 'Procedure' ? 'selected' : '' ?>>Procedures</option>
                        <option value="Consultation" <?= $filter_type == 'Consultation' ? 'selected' : '' ?>>Consultations</option>
                        <option value="Investigation" <?= $filter_type == 'Investigation' ? 'selected' : '' ?>>Investigations</option>
                        <option value="Drug" <?= $filter_type == 'Drug' ? 'selected' : '' ?>>Pharmacy / Drugs</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label style="color:#0284c7;">Insurance Matrix View</label>
                    <select name="provider_id" class="filter-control" style="border-color:#3b82f6; background:#f0f9ff; font-weight:600; color:#0284c7;">
                        <option value="">NHIS & Cash Standard</option>
                        <?php foreach($insurances as $ins): ?>
                            <option value="<?= $ins['id'] ?>" <?= $filter_ins_id == $ins['id'] ? 'selected' : '' ?>><?= htmlspecialchars($ins['insurance_name']) ?> Policy</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <button type="submit" class="btn-filter"><i class="fa-solid fa-filter"></i> Apply Filters</button>
                </div>
            </div>
            <?php if($search_text || $filter_type || $filter_dept || $filter_ins_id): ?>
                <a href="gdrgProcedures.php" class="btn-reset"><i class="fa-solid fa-rotate-left"></i> Reset Dashboard</a>
            <?php endif; ?>
        </form>
    </div>

    <?php if($filter_ins_id): ?>
        <div class="matrix-alert">
            <i class="fa-solid fa-building-shield"></i> You are currently viewing isolated pricing matrices and co-payment rules strictly for the selected Corporate Provider.
        </div>
    <?php endif; ?>

    <!-- DYNAMIC DEPARTMENT ACCORDIONS -->
    <?php if(empty($grouped_services)): ?>
        <div style="background:#fff; padding:50px; text-align:center; border-radius:12px; border:1px dashed #cbd5e1;">
            <i class="fa-solid fa-folder-open" style="font-size:40px; color:#94a3b8; margin-bottom:15px;"></i>
            <h3 style="color:#475569; margin:0;">No Services Found</h3>
            <p style="color:#94a3b8; margin-top:5px;">Try adjusting your search or matrix filters.</p>
        </div>
    <?php else: ?>
        <?php foreach($grouped_services as $dept_name => $data): ?>
            <div class="accordion-item">
                <div class="accordion-header" onclick="toggleAccordion(this)">
                    <div class="accordion-title">
                        <i class="fa-regular fa-folder-open"></i> <?= htmlspecialchars($dept_name) ?>
                    </div>
                    <div class="accordion-stats">
                        <span class="badge bg-gray">Total: <?= $data['stats']['total'] ?></span>
                        <?php if($data['stats']['consults'] > 0): ?>
                            <span class="badge bg-blue"><i class="fa-solid fa-stethoscope"></i> <?= $data['stats']['consults'] ?> Consults</span>
                        <?php endif; ?>
                        <i class="fa-solid fa-chevron-down accordion-toggle-icon" style="margin-left:10px;"></i>
                    </div>
                </div>
                
                <div class="accordion-body">
                    <table>
                        <thead>
                            <tr>
                                <th style="width:35%;">Service Profile</th>
                                <th>Cash Rate</th>
                                <?php if($filter_ins_id): ?>
                                    <th>Provider Tariff</th>
                                    <th>Corporate Co-Pay</th>
                                <?php else: ?>
                                    <th>NHIS Tariff (Adult/Child)</th>
                                    <th>NHIS Co-Pay</th>
                                <?php endif; ?>
                                <th style="text-align:right;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($data['services'] as $s): ?>
                                <tr>
                                    <td>
                                        <strong style="color:#0f172a; font-size:15px; display:block; margin-bottom:4px;"><?= htmlspecialchars($s['service_name']) ?></strong>
                                        <span style="color:#64748b; font-size:12px;"><?= htmlspecialchars($s['service_type']) ?></span>
                                    </td>
                                    <td style="font-weight:800; color:#334155;">GHS <?= number_format($s['cash_price'], 2) ?></td>
                                    
                                    <?php if($filter_ins_id): ?>
                                        <!-- CORPORATE MATRIX -->
                                        <td>
                                            <?= isset($s['corp_tariff']) ? '<strong style="color:#0284c7;">GHS ' . number_format($s['corp_tariff'], 2) . '</strong>' : '<span class="badge bg-gray">Not Mapped</span>' ?>
                                        </td>
                                        <td>
                                            <?php 
                                            if(isset($s['corp_req']) && $s['corp_req'] == 1) {
                                                echo "<span class='badge bg-red'>Yes - GHS " . number_format($s['corp_copay'], 2) . "</span>";
                                            } else if(isset($s['corp_req'])) {
                                                echo "<span class='badge bg-green'><i class='fa-solid fa-check'></i> No</span>";
                                            } else {
                                                echo "<span style='color:#cbd5e1;'>--</span>";
                                            }
                                            ?>
                                        </td>
                                    <?php else: ?>
                                        <!-- NHIS MATRIX -->
                                        <td>
                                            <?php if($s['gdrg_adult_code'] || $s['gdrg_child_code']): ?>
                                                <div style="font-size:12px; color:#64748b; margin-bottom:3px;">
                                                    <span style="font-family:monospace; background:#f1f5f9; padding:2px 4px; border-radius:4px;"><?= $s['gdrg_adult_code'] ?: 'N/A' ?></span> : <span style="color:#16a34a; font-weight:700;">GHS <?= number_format($s['tariff_adult'], 2) ?></span>
                                                </div>
                                                <div style="font-size:12px; color:#64748b;">
                                                    <span style="font-family:monospace; background:#f1f5f9; padding:2px 4px; border-radius:4px;"><?= $s['gdrg_child_code'] ?: 'N/A' ?></span> : <span style="color:#16a34a; font-weight:700;">GHS <?= number_format($s['tariff_child'], 2) ?></span>
                                                </div>
                                            <?php else: ?>
                                                <span style="color:#cbd5e1;">--</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php 
                                            if($s['is_copay_required'] == 1) {
                                                echo "<span class='badge bg-red'>Yes - GHS " . number_format($s['copay_amount'], 2) . "</span>"; 
                                            } elseif($s['tariff_adult'] > 0 || $s['tariff_child'] > 0) {
                                                echo "<span class='badge bg-green'><i class='fa-solid fa-check'></i> No</span>";
                                            } else {
                                                echo "<span style='color:#cbd5e1;'>--</span>";
                                            }
                                            ?>
                                        </td>
                                    <?php endif; ?>
                                    
                                    <td style="text-align:right;">
                                        <a href="#" style="color:#1e3a8a; text-decoration:none; font-weight:700; font-size:13px; background:#eff6ff; padding:8px 14px; border-radius:6px; border:1px solid #bfdbfe; transition:0.2s;"><i class="fa-solid fa-pen-to-square"></i> Manage</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<script>
// Simple Accordion Toggle Logic
function toggleAccordion(element) {
    const parentItem = element.closest('.accordion-item');
    parentItem.classList.toggle('active');
}
</script>

</body>
</html>