<?php
header('Content-Type: application/json');
header('X-Content-Type-Options: nosniff'); // Security header
require_once("../../includes/config.php");

// 1. Sanitize and Validate Input
$limit = 10; 
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;

$offset = ($page - 1) * $limit;
$search = isset($_GET['q']) ? trim($_GET['q']) : '';

try {
    // 2. Base Query Logic
    $queryStr = "FROM exam_terms WHERE 1=1";
    $params = [];

    if (!empty($search)) {
        $queryStr .= " AND term_name LIKE :search";
        $params[':search'] = "%$search%";
    }

    // 3. Get total count for pagination
    $countStmt = $pdo->prepare("SELECT COUNT(*) $queryStr");
    $countStmt->execute($params);
    $totalItems = (int)$countStmt->fetchColumn();
    $totalPages = ceil($totalItems / $limit);

    // 4. Get paginated results
    // We bind LIMIT and OFFSET separately to ensure they are treated as Integers
    $dataSql = "SELECT * $queryStr ORDER BY id DESC LIMIT :limit OFFSET :offset";
    $dataStmt = $pdo->prepare($dataSql);

    // Bind search param if it exists
    if (!empty($search)) {
        $dataStmt->bindValue(':search', "%$search%", PDO::PARAM_STR);
    }
    
    $dataStmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $dataStmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $dataStmt->execute();
    
    $terms = $dataStmt->fetchAll(PDO::FETCH_ASSOC);

    // 5. Professional JSON Response
    echo json_encode([
        'status' => 'success',
        'data' => $terms,
        'pagination' => [
            'current_page' => $page,
            'total_pages' => $totalPages,
            'total_items' => $totalItems,
            'limit' => $limit
        ]
    ]);

} catch (PDOException $e) {
    // Log error internally and show generic message to user for security
    error_log("Database Error: " . $e->getMessage());
    echo json_encode([
        'status' => 'error', 
        'message' => 'Internal server error occurred.'
    ]);
}
?>