<?php
require_once '../config.php';
require_once '../../includes/Auth.php';
require_once '../../includes/Database.php';

$auth = new Auth();
$auth->requireRole('admin');

try {
    $db = new Database();
    
    // Pagination parameters
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = 10; // Items per page
    $offset = ($page - 1) * $limit;

    $searchTerm = $_GET['search'] ?? '';
    $params = [];
    $countParams = [];

    // Sorting parameters
    $sort_by_whitelist = ['name', 'email', 'role', 'created_at'];
    $sort_by = in_array($_GET['sort_by'] ?? '', $sort_by_whitelist) ? $_GET['sort_by'] : 'created_at';
    $sort_dir_whitelist = ['asc', 'desc'];
    $sort_dir = in_array(strtolower($_GET['sort_dir'] ?? ''), $sort_dir_whitelist) ? strtoupper($_GET['sort_dir']) : 'DESC';
    
    // The ORDER BY clause is built from validated parameters, so it's safe.
    $orderBySql = "ORDER BY {$sort_by} {$sort_dir}";


    $baseSql = "FROM users";
    $whereSql = "";

    if (!empty($searchTerm)) {
        $whereSql = " WHERE name LIKE ? OR email LIKE ?";
        $likeTerm = "%$searchTerm%";
        $params[] = $likeTerm;
        $params[] = $likeTerm;
        $countParams = $params;
    }

    // Get total count for pagination
    $countStmt = $db->query("SELECT COUNT(*) as total " . $baseSql . " " . $whereSql, $countParams);
    $totalItems = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
    $totalPages = ceil($totalItems / $limit);

    // Get paginated results
    $stmt = $db->query("SELECT id, name, email, phone, role, created_at " . $baseSql . " " . $whereSql . " " . $orderBySql . " LIMIT " . (int)$limit . " OFFSET " . (int)$offset, $params);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

    jsonResponse(['success' => true, 'users' => $users, 'pagination' => [
        'total_items' => $totalItems, 'total_pages' => $totalPages, 'current_page' => $page, 'limit' => $limit
    ]]);
} catch (Exception $e) {
    jsonResponse(['success' => false, 'message' => $e->getMessage()], 500);
}
?>