<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
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;

    // FIXED: Using Object-Oriented real_escape_string
    $search = isset($_GET['search']) ? trim($conn->real_escape_string($_GET['search'])) : '';

    $where_sql = "";
    if (!empty($search)) {
        $where_sql = "WHERE m.gdrg_code LIKE '%$search%' 
                         OR m.icd10_code LIKE '%$search%' 
                         OR g.description LIKE '%$search%' 
                         OR i.description LIKE '%$search%'";
    }

    // 1. Count Total Records
    $count_sql = "SELECT COUNT(m.id) as total 
                  FROM gdrg_icd_mapping m
                  LEFT JOIN gdrg_dictionary g ON TRIM(m.gdrg_code) = TRIM(g.code)
                  LEFT JOIN icd10_dictionary i ON TRIM(m.icd10_code) = TRIM(i.code)
                  $where_sql";
                  
    // FIXED: Using Object-Oriented query
    $count_res = $conn->query($count_sql);
    
    // FIXED: Using Object-Oriented error reporting
    if (!$count_res) { throw new Exception("Count Query Failed: " . $conn->error); }
    
    // FIXED: Using Object-Oriented fetch
    $total_records = (int)$count_res->fetch_assoc()['total'];
    $total_pages = ceil($total_records / $limit);

    // 2. Fetch Data with Prepared Statements (MUCH SAFER)
$records = [];
if ($total_records > 0) {
    // Note: Removed direct variable injection, using Limit/Offset placeholders
    $fetch_sql = "
        SELECT m.id, m.gdrg_code, m.icd10_code, m.is_active,
               COALESCE(g.description, n.description, s.service_name, 'Description Pending Update') as gdrg_desc, 
               COALESCE(i.description, 'Diagnosis Pending Update') as icd10_desc
        FROM gdrg_icd_mapping m
        LEFT JOIN gdrg_dictionary g ON TRIM(m.gdrg_code) = TRIM(g.code)
        LEFT JOIN icd10_dictionary i ON TRIM(m.icd10_code) = TRIM(i.code)
        LEFT JOIN nhis_tariffs n ON (TRIM(m.gdrg_code) = TRIM(n.gdrg_code_adult) OR TRIM(m.gdrg_code) = TRIM(n.gdrg_code_child))
        LEFT JOIN service_catalog s ON (TRIM(m.gdrg_code) = TRIM(s.gdrg_adult_code) OR TRIM(m.gdrg_code) = TRIM(s.gdrg_child_code))
        $where_sql 
        GROUP BY m.id
        ORDER BY m.gdrg_code ASC, m.icd10_code ASC 
        LIMIT ? OFFSET ?
    ";
    
    $stmt = $conn->prepare($fetch_sql);
    $stmt->bind_param("ii", $limit, $offset);
    $stmt->execute();
    $fetch_res = $stmt->get_result();

    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 (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>