<?php
/**
 * Get All Users API
 * Endpoint: /admin/adminapi/get_all_users.php
 */
require_once(__DIR__ . '/includes/db.php');
require_once(__DIR__ . '/includes/auth.php');

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

// Require valid auth token
requireAuth();

try {
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $limit = isset($_GET['limit']) ? min(100, max(10, intval($_GET['limit']))) : 50;
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';

    $offset = ($page - 1) * $limit;

    // Build query
    $whereConditions = [];
    $params = [];

    if (!empty($search)) {
        $whereConditions[] = "(firstname LIKE ? OR lastname LIKE ? OR mobile LIKE ? OR email LIKE ? OR cardnumber LIKE ? OR bankname LIKE ?)";
        $searchParam = "%{$search}%";
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
    }

    $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';

    // Get total count
    $countSql = "SELECT COUNT(*) as total FROM users {$whereClause}";
    $countStmt = $pdo->prepare($countSql);
    $countStmt->execute($params);
    $totalCount = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];

    // Get users - use direct integer values in query (safe since we validated them)
    $sql = "SELECT * FROM users 
            {$whereClause}
            ORDER BY id DESC 
            LIMIT {$limit} OFFSET {$offset}";

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

    // Mask card numbers
    foreach ($users as &$user) {
        if (!empty($user['cardnumber']) && strlen($user['cardnumber']) >= 8) {
            $card = $user['cardnumber'];
            $user['cardnumber_masked'] = substr($card, 0, 4) . '****' . substr($card, -4);
        } else {
            $user['cardnumber_masked'] = $user['cardnumber'] ?? '';
        }
    }

    $totalPages = $totalCount > 0 ? ceil($totalCount / $limit) : 1;

    echo json_encode([
        'success' => true,
        'status' => true,
        'users' => $users,
        'pagination' => [
            'current_page' => $page,
            'total_pages' => $totalPages,
            'total_count' => (int)$totalCount,
            'per_page' => $limit,
            'has_more' => $page < $totalPages
        ]
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
