<?php
session_start();
header('Content-Type: application/json');

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

try {
    // 1. Sanitize Inputs
    $page  = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT) ?: 1;
    $limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT) ?: 50;
    $offset = ($page - 1) * $limit;

    $search    = $conn->real_escape_string($_GET['search'] ?? '');
    $dept      = $conn->real_escape_string($_GET['dept'] ?? 'ALL');
    $modality  = $conn->real_escape_string($_GET['modality'] ?? 'ALL');
    $insurance = $conn->real_escape_string($_GET['insurance'] ?? 'ALL');

    // 2. Build Query Filters
    $where = ["1=1"];
    
    if (!empty($search)) {
        $where[] = "(s.service_name LIKE '%$search%' OR s.gdrg_adult_code LIKE '%$search%' OR s.gdrg_child_code LIKE '%$search%')";
    }
    if ($dept !== 'ALL') {
        $where[] = "s.department_id = " . (int)$dept;
    }
    if ($modality !== 'ALL') {
        $where[] = "s.service_type = '$modality'";
    }

    $where_sql = implode(" AND ", $where);

    // 3. Define Join Logic (Keep as LEFT JOIN to ensure all records show)
    $corp_join = "";
    $corp_selects = "";
    
    if (is_numeric($insurance)) {
        $ins_id = (int)$insurance;
        $corp_join = "LEFT JOIN service_corporate_tariffs t ON (s.id = t.service_id AND t.insurance_type_id = $ins_id)";
        $corp_selects = ", t.tariff_amount as corp_tariff, t.is_copay_required as corp_copay_req, t.copay_amount_adult as corp_copay_adult, t.copay_amount_child as corp_copay_child";
    }

    // 4. Count Total Records
    $count_sql = "SELECT COUNT(s.id) as total 
                  FROM service_catalog s 
                  LEFT JOIN departments d ON s.department_id = d.id 
                  $corp_join
                  WHERE $where_sql";
    
    $count_res = $conn->query($count_sql);
    if (!$count_res) throw new Exception("Database Error: " . $conn->error);
    
    $total_records = (int)$count_res->fetch_assoc()['total'];
    $total_pages = ceil($total_records / $limit);

    // 5. Fetch Data
    $records = [];
    if ($total_records > 0) {
        $sql = "SELECT 
                    s.id as service_id, s.service_name, s.service_type, s.target_age_group, s.applicable_gender,
                    s.cash_price_adult, s.cash_price_child, s.nhis_covered, 
                    s.gdrg_adult_code, s.tariff_adult, s.gdrg_child_code, s.tariff_child,
                    s.is_copay_required, s.nhis_copay_adult, s.nhis_copay_child, s.is_active,
                    d.department_name
                    $corp_selects
                FROM service_catalog s
                LEFT JOIN departments d ON s.department_id = d.id
                $corp_join
                WHERE $where_sql 
                ORDER BY d.department_name ASC, s.service_name ASC 
                LIMIT $limit OFFSET $offset";

        $res = $conn->query($sql);
        if (!$res) throw new Exception("Fetch Error: " . $conn->error);

        while ($row = $res->fetch_assoc()) {
            $records[] = $row;
        }
    }

    echo json_encode([
        'records'       => $records,
        'total_records' => $total_records,
        'total_pages'   => $total_pages,
        'current_page'  => $page,
        'limit'         => $limit,
        'insurance_view'=> is_numeric($insurance) ? 'CORP' : 'NHIS'
    ]);

} catch (Throwable $e) {
    // Return error as JSON so the JS console can handle it
    echo json_encode(['error' => $e->getMessage()]);
}
?>