<?php
declare(strict_types=1);

require_once __DIR__ . '/admin_bootstrap.php';

admin_require_auth();

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    admin_json_error('Metoda niedozwolona', 405);
}

$userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
if ($userId <= 0) {
    admin_json_error('Nieprawidłowy user_id');
}

$pdo = admin_get_pdo();

// Fetch full user data
$userData = null;
try {
    $stmt = $pdo->prepare(
        "SELECT u.id, u.username, u.email, u.first_name, u.last_name, u.role,
                u.email_verified, u.account_suspended, u.created_at, u.disabled,
                COALESCE(u.suspension_reason, '') AS suspension_reason,
                u.suspended_until, u.suspended_by,
                COALESCE(us.balance, 0) AS balance,
                COALESCE(us.matches_played, 0) AS matches_played,
                COALESCE(us.matches_won, 0) AS matches_won,
                COALESCE(us.matches_lost, 0) AS matches_lost
         FROM users u
         LEFT JOIN user_stats us ON us.user_id = u.id
         WHERE u.id = ?
         LIMIT 1"
    );
    $stmt->execute([$userId]);
    $userData = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    // suspension columns may not exist yet — fallback to basic query
    try {
        $stmt = $pdo->prepare(
            "SELECT u.id, u.username, u.email, u.first_name, u.last_name, u.role,
                    u.email_verified, u.account_suspended, u.created_at, u.disabled,
                    '' AS suspension_reason, NULL AS suspended_until, NULL AS suspended_by,
                    COALESCE(us.balance, 0) AS balance,
                    COALESCE(us.matches_played, 0) AS matches_played,
                    COALESCE(us.matches_won, 0) AS matches_won,
                    COALESCE(us.matches_lost, 0) AS matches_lost
             FROM users u
             LEFT JOIN user_stats us ON us.user_id = u.id
             WHERE u.id = ?
             LIMIT 1"
        );
        $stmt->execute([$userId]);
        $userData = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Throwable $e2) {
        admin_json_error('Błąd pobierania danych użytkownika: ' . $e2->getMessage(), 500);
    }
}

if (!$userData) {
    admin_json_error('Użytkownik nie istnieje', 404);
}

// Fetch account history
$history = [];
try {
    $stmtH = $pdo->prepare(
        "SELECT id, user_id, action, reason, suspended_until, performed_by, performed_by_username, created_at
         FROM user_account_history
         WHERE user_id = ?
         ORDER BY created_at DESC
         LIMIT 200"
    );
    $stmtH->execute([$userId]);
    $history = $stmtH->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (Throwable $e) {
    // Table may not exist yet
    $history = [];
}

admin_json_response(['success' => true, 'user' => $userData, 'history' => $history]);
