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

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']) ? trim($conn->real_escape_string($_GET['search'])) : '';

    $where_sql = "1=1";
    if (!empty($search)) {
        // GDRG search condition removed
        $where_sql .= " AND (p.insurance_name LIKE '%$search%' OR s.service_name LIKE '%$search%')";
    }

    $count_sql = "SELECT COUNT(*) as total 
                  FROM insurance_type p
                  LEFT JOIN service_corporate_tariffs t ON p.id = t.insurance_type_id
                  LEFT JOIN service_catalog s ON t.service_id = s.id
                  WHERE $where_sql";
                  
    $count_res = $conn->query($count_sql);
    if (!$count_res) { throw new Exception("Database Count Query Failed: " . $conn->error); }
    
    $total_records = (int)$count_res->fetch_assoc()['total'];
    $total_pages = ceil($total_records / $limit);

    // Removed s.gdrg_adult_code from SELECT
    $fetch_sql = "
        SELECT 
            p.id AS provider_id,
            p.insurance_name AS provider_name,
            p.is_active AS provider_status,
            t.id AS map_id,
            t.tariff_amount,
            t.is_copay_required,
            t.copay_amount_adult,
            t.copay_amount_child,
            s.service_name,
            s.cash_price_adult,
            s.cash_price_child
        FROM insurance_type p
        LEFT JOIN service_corporate_tariffs t ON p.id = t.insurance_type_id
        LEFT JOIN service_catalog s ON t.service_id = s.id
        WHERE $where_sql 
        ORDER BY p.insurance_name ASC, s.service_name ASC 
        LIMIT $limit OFFSET $offset
    ";
                  
    $fetch_res = $conn->query($fetch_sql);
    if (!$fetch_res) { throw new Exception("Database Fetch Query Failed: " . $conn->error); }

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

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

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