<?php
// We put error reporting up top so it gets caught by our JS text reader if it fails
ini_set('display_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');

// Connect to Database
require_once __DIR__ . '/../../includes/db.php';
try {
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;
    $offset = ($page - 1) * $limit;

    $search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
    $dept = isset($_GET['dept']) ? mysqli_real_escape_string($conn, $_GET['dept']) : 'ALL';
    $modality = isset($_GET['modality']) ? mysqli_real_escape_string($conn, $_GET['modality']) : 'ALL';
    $insurance = isset($_GET['insurance']) ? mysqli_real_escape_string($conn, $_GET['insurance']) : 'ALL';

    $where_clauses = ["1=1"]; 

    if (!empty($search)) {
        $where_clauses[] = "(s.service_name LIKE '%$search%' OR s.gdrg_adult_code LIKE '%$search%' OR s.gdrg_child_code LIKE '%$search%')";
    }

    if ($dept !== 'ALL') {
        $where_clauses[] = "s.department_id = " . (int)$dept;
    }

    if ($modality !== 'ALL') {
        $where_clauses[] = "s.service_type = '$modality'";
    }

    $where_sql = "WHERE " . implode(' AND ', $where_clauses);

    $join_sql = "LEFT JOIN departments d ON s.department_id = d.id";
    $select_fields = "s.id, s.service_name, s.service_type, s.applicable_gender, s.target_age_group, s.cash_price, 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";

    if ($insurance !== 'ALL' && $insurance !== 'NHIS') {
        $ins_id = (int)$insurance;
        $join_sql .= " LEFT JOIN service_corporate_tariffs c ON s.id = c.service_id AND c.insurance_type_id = $ins_id";
        $select_fields .= ", c.tariff_amount as corp_tariff, c.is_copay_required as corp_copay_req, c.copay_amount_adult as corp_copay_adult";
    }

    $count_sql = "SELECT COUNT(s.id) as total FROM service_catalog s $join_sql $where_sql";
    $count_res = mysqli_query($conn, $count_sql);
    
    if (!$count_res) {
        throw new Exception("Count Query Failed: " . mysqli_error($conn));
    }
    
    $total_records = (int)mysqli_fetch_assoc($count_res)['total'];
    $total_pages = ceil($total_records / $limit);

    $records = [];
    if ($total_records > 0) {
        $fetch_sql = "SELECT $select_fields 
                      FROM service_catalog s 
                      $join_sql 
                      $where_sql 
                      ORDER BY d.department_name ASC, s.service_name ASC 
                      LIMIT $limit OFFSET $offset";
                      
        $fetch_res = mysqli_query($conn, $fetch_sql);

        if (!$fetch_res) {
            throw new Exception("Fetch Query Failed: " . mysqli_error($conn));
        }

        while ($row = mysqli_fetch_assoc($fetch_res)) {
            $records[] = $row;
        }
    }

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

} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>