<?php

require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../middleware/admin.php';
require_once __DIR__ . '/UserRepository.php';

if (getMethod() !== 'GET') {
    jsonResponse(false, 'Method not allowed', null, 405);
}

function respondPaginated(string $message, array $items, array $pagination, int $status = 200): void
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');

    echo json_encode([
        'ok' => true,
        'message' => $message,
        'data' => $items,
        'pagination' => $pagination,
    ]);
    exit;
}

$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 10;
$page = max(1, $page);
$limit = max(1, min($limit, 100));

global $pdo;
requireAdmin();
$repo = new UserRepository($pdo);
$result = $repo->paginate($page, $limit);

respondPaginated('Users fetched successfully', $result['items'], $result['pagination']);
