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

    $where_sql = "";
    if (!empty($search)) {
        $where_sql = "WHERE code LIKE '%$search%' OR description LIKE '%$search%'";
    }

    // 1. Count Total Records
    $count_sql = "SELECT COUNT(code) as total FROM icd10_dictionary $where_sql";
    
    // FIXED: Using Object-Oriented query
    $count_res = $conn->query($count_sql);
    if (!$count_res) { throw new Exception("Count Query Failed: " . $conn->error); }
    
    $total_records = (int)$count_res->fetch_assoc()['total'];
    $total_pages = ceil($total_records / $limit);

    // 2. Fetch Paginated Data
    $records = [];
    if ($total_records > 0) {
        $fetch_sql = "SELECT * FROM icd10_dictionary 
                      $where_sql 
                      ORDER BY code ASC 
                      LIMIT $limit OFFSET $offset";
                      
        // FIXED: Using Object-Oriented query
        $fetch_res = $conn->query($fetch_sql);

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

        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()]);
}
?>