<?php
declare(strict_types=1);

require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/session_bootstrap.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/user_avatar.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

if (empty($_SESSION['logged_in']) || empty($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'error' => 'Brak autoryzacji'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$pdo = og_session_get_pdo();
if (!$pdo instanceof PDO) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Błąd połączenia z bazą danych'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$userId = (int) $_SESSION['user_id'];

try {
    $pdo->prepare(
        "INSERT IGNORE INTO user_stats (
            user_id, balance, matches_played, matches_won, matches_lost, matches_draw,
            tournaments_played, tournaments_won, leagues_participated,
            total_income, total_expenses, total_transactions, account_status
        ) VALUES (?, 0.00, 0, 0, 0, 0, 0, 0, 0, 0.00, 0.00, 0, 'active')"
    )->execute([$userId]);

    $stmt = $pdo->prepare(
        'SELECT
            u.id,
            u.username,
            u.email,
            COALESCE(u.role, "user") AS role,
            u.created_at,
            COALESCE(u.email_verified, 0) AS email_verified,
            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,
            COALESCE(us.matches_draw, 0) AS matches_draw,
            COALESCE(us.tournaments_played, 0) AS tournaments_played,
            COALESCE(us.tournaments_won, 0) AS tournaments_won,
            COALESCE(us.leagues_participated, 0) AS leagues_participated,
            COALESCE(us.total_income, 0) AS total_income,
            COALESCE(us.total_expenses, 0) AS total_expenses,
            COALESCE(us.total_transactions, 0) AS total_transactions,
            COALESCE(us.account_status, "active") AS account_status,
            COALESCE(ds.matches_played, 0) AS pp_matches_played,
            COALESCE(ds.matches_won, 0) AS pp_matches_won,
            COALESCE(ds.matches_lost, 0) AS pp_matches_lost,
            COALESCE(ds.matches_draw, 0) AS pp_matches_draw,
            COALESCE(ds.total_income, 0) AS pp_total_income
         FROM users u
         LEFT JOIN user_stats us ON us.user_id = u.id
         LEFT JOIN discipline_stats ds ON ds.user_id = u.id AND ds.discipline = "ping-pong" AND ds.mode = "1v1"
         WHERE u.id = :userId
         LIMIT 1'
    );
    $stmt->execute([':userId' => $userId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'error' => 'Nie znaleziono użytkownika'
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $matchesPlayed = (int) $row['matches_played'];
    $matchesWon = (int) $row['matches_won'];
    $matchesLost = (int) $row['matches_lost'];
    $decisiveMatches = $matchesWon + $matchesLost;
    $winRate = $decisiveMatches > 0 ? round(($matchesWon / $decisiveMatches) * 100, 1) : 0.0;

    $ppPlayed = (int) $row['pp_matches_played'];
    $ppWon = (int) $row['pp_matches_won'];
    $ppLost = (int) $row['pp_matches_lost'];
    $ppDecisive = $ppWon + $ppLost;
    $ppWinRate = $ppDecisive > 0 ? round(($ppWon / $ppDecisive) * 100, 1) : 0.0;
    $avatarFile = og_get_user_avatar_file($pdo, $userId);
    $avatarUrl = og_avatar_file_to_url($avatarFile);

    echo json_encode([
        'success' => true,
        'data' => [
            'userId' => (int) $row['id'],
            'username' => (string) $row['username'],
            'email' => (string) $row['email'],
            'role' => (string) $row['role'],
            'memberSince' => (string) ($row['created_at'] ?? ''),
            'emailVerified' => (int) $row['email_verified'] === 1,
            'accountStatus' => (string) $row['account_status'],
            'balance' => (float) $row['balance'],
            'matchesPlayed' => $matchesPlayed,
            'matchesWon' => $matchesWon,
            'matchesLost' => $matchesLost,
            'matchesDraw' => (int) $row['matches_draw'],
            'winRate' => $winRate,
            'tournamentsPlayed' => (int) $row['tournaments_played'],
            'tournamentsWon' => (int) $row['tournaments_won'],
            'leaguesParticipated' => (int) $row['leagues_participated'],
            'totalIncome' => (float) $row['total_income'],
            'totalExpenses' => (float) $row['total_expenses'],
            'totalTransactions' => (int) $row['total_transactions'],
            'pingPongStats' => [
                'matchesPlayed' => $ppPlayed,
                'matchesWon'    => $ppWon,
                'matchesLost'   => (int) $row['pp_matches_lost'],
                'matchesDraw'   => (int) $row['pp_matches_draw'],
                'winRate'       => $ppWinRate,
                'totalIncome'   => (float) $row['pp_total_income'],
            ],
            'avatarUrl' => $avatarUrl,
        ],
    ], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Nie udało się pobrać statystyk gracza'
    ], JSON_UNESCAPED_UNICODE);
}