<?php
require_once __DIR__ . '/../admin_middleware.php';

// Verify basic admin access (no specific permission required to view list, but role must be admin/mod)
verifyAdmin(); 

header('Content-Type: application/json');

try {
    $search = isset($_GET['search']) ? $_GET['search'] : '';
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = 20;
    $offset = ($page - 1) * $limit;

    $sql = "SELECT iuid AS id, i_username AS username, i_user_email AS email, level, xp, diamonds, registered AS created_at, uStatus AS status 
            FROM i_users 
            WHERE 1=1";
            
    $params = [];

    if ($search) {
        $sql .= " AND (i_username LIKE ? OR i_user_email LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }

    $sql .= " ORDER BY id DESC LIMIT $limit OFFSET $offset";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Decode permissions for frontend
    foreach ($users as &$u) {
        $u['permissions'] = !empty($u['permissions']) ? json_decode($u['permissions'], true) : [];
        $u['is_verified'] = (bool)$u['is_verified'];
    }

    // Get total count for pagination
    $countSql = "SELECT COUNT(*) FROM i_users WHERE 1=1";
    if ($search) {
        $countSql .= " AND (i_username LIKE ? OR i_user_email LIKE ?)";
    }
    $countStmt = $pdo->prepare($countSql);
    $countStmt->execute($params);
    $total = $countStmt->fetchColumn();

    echo json_encode([
        'users' => $users,
        'total' => $total,
        'page' => $page,
        'pages' => ceil($total / $limit)
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
