<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/telegram_lib.php';
require_once __DIR__ . '/user_auth_lib.php';
require_once __DIR__ . '/level_lib.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

$uid = isset($_SESSION['mocker_user_id']) ? (int) $_SESSION['mocker_user_id'] : 0;
if ($uid <= 0) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'auth'], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $pdo = mocker_db();
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE);
    exit;
}

mocker_user_auth_migrate($pdo);

$st = $pdo->prepare(
    'SELECT u.id, u.username, u.email, u.phone, u.coins, u.created_at, u.profile_completed_at,
     COALESCE(u.twofa_enabled, 0) AS twofa_enabled,
     COALESCE(u.must_change_password, 0) AS must_change_password, u.external_player_id,
     u.telegram_verified_at, u.telegram_username, u.telegram_pending_expires,
     c.btc, c.eth, c.usdt_erc20, c.usdt_trc20, c.ltc, c.trx, c.doge, c.other, c.updated_at AS crypto_updated_at
     FROM users u
     LEFT JOIN user_crypto_wallets c ON c.user_id = u.id
     WHERE u.id = :id LIMIT 1'
);
$st->execute([':id' => $uid]);
$row = $st->fetch();

if (!$row) {
    unset($_SESSION['mocker_user_id']);
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'auth'], JSON_UNESCAPED_UNICODE);
    exit;
}

$st2 = $pdo->prepare(
    'SELECT id, item_id, item_title, price, COALESCE(status, \'pending\') AS status, created_at FROM purchases WHERE user_id = :uid ORDER BY created_at DESC LIMIT 200'
);
$st2->execute([':uid' => $uid]);
$purchases = [];
foreach ($st2->fetchAll() as $p) {
    $purchases[] = [
        'id' => (int) $p['id'],
        'itemId' => $p['item_id'],
        'itemTitle' => $p['item_title'],
        'price' => (int) $p['price'],
        'status' => (string) ($p['status'] ?? 'pending'),
        'createdAt' => (int) $p['created_at'],
    ];
}

$st3 = $pdo->prepare(
    'SELECT id, category, sponsor_id, sponsor_title, message, COALESCE(status, \'pending\') AS status, created_at
     FROM complaints
     WHERE user_id = :uid
     ORDER BY created_at DESC, id DESC
     LIMIT 200'
);
$st3->execute([':uid' => $uid]);
$complaints = [];
foreach ($st3->fetchAll() as $c) {
    $complaints[] = [
        'id' => (int) $c['id'],
        'category' => (string) ($c['category'] ?? 'other'),
        'sponsorId' => $c['sponsor_id'] !== null ? (string) $c['sponsor_id'] : '',
        'sponsorTitle' => $c['sponsor_title'] !== null ? (string) $c['sponsor_title'] : '',
        'message' => (string) ($c['message'] ?? ''),
        'status' => (string) ($c['status'] ?? 'pending'),
        'createdAt' => (int) $c['created_at'],
    ];
}

$st4 = $pdo->prepare(
    'SELECT sponsor_id, sponsor_title, account_value, updated_at
     FROM user_sponsor_accounts
     WHERE user_id = :uid
     ORDER BY updated_at DESC, sponsor_id ASC
     LIMIT 300'
);
$st4->execute([':uid' => $uid]);
$sponsorAccounts = [];
foreach ($st4->fetchAll() as $r) {
    $sponsorAccounts[] = [
        'sponsorId' => (string) $r['sponsor_id'],
        'sponsorTitle' => $r['sponsor_title'] !== null ? (string) $r['sponsor_title'] : '',
        'accountValue' => $r['account_value'] !== null ? (string) $r['account_value'] : '',
        'updatedAt' => $r['updated_at'] !== null ? (int) $r['updated_at'] : null,
    ];
}

$wheelHistory = [];
try {
    $st5 = $pdo->prepare(
        'SELECT id, segment, amount, created_at
         FROM wheel_spins
         WHERE user_id = :uid
         ORDER BY created_at DESC, id DESC
         LIMIT 200'
    );
    $st5->execute([':uid' => $uid]);
    foreach ($st5->fetchAll() as $w) {
        $wheelHistory[] = [
            'id' => (int) $w['id'],
            'segment' => (int) $w['segment'],
            'amount' => (int) $w['amount'],
            'createdAt' => (int) $w['created_at'],
        ];
    }
} catch (Throwable $e) {

    $wheelHistory = [];
}

$blackjackRounds = [];
$blackjackMaxBet = 0;
try {
    $stBjMax = $pdo->prepare('SELECT COALESCE(MAX(bet), 0) AS m FROM blackjack_rounds WHERE user_id = :uid');
    $stBjMax->execute([':uid' => $uid]);
    $blackjackMaxBet = (int) ($stBjMax->fetch()['m'] ?? 0);

    $stBj = $pdo->prepare(
        'SELECT id, created_at, bet, doubled, outcome, stake, payout
         FROM blackjack_rounds WHERE user_id = :uid ORDER BY created_at DESC, id DESC LIMIT 100'
    );
    $stBj->execute([':uid' => $uid]);
    foreach ($stBj->fetchAll(PDO::FETCH_ASSOC) as $br) {
        $blackjackRounds[] = [
            'id' => (int) $br['id'],
            'createdAt' => (int) $br['created_at'],
            'bet' => (int) $br['bet'],
            'doubled' => (int) $br['doubled'] === 1,
            'outcome' => (string) $br['outcome'],
            'stake' => (int) $br['stake'],
            'payout' => (int) $br['payout'],
        ];
    }
} catch (Throwable $e) {
    $blackjackRounds = [];
    $blackjackMaxBet = 0;
}

$slotRounds = [];
$slotMaxBet = 0;
try {
    $stSlotMax = $pdo->prepare('SELECT COALESCE(MAX(bet), 0) AS m FROM slot_rounds WHERE user_id = :uid');
    $stSlotMax->execute([':uid' => $uid]);
    $slotMaxBet = (int) ($stSlotMax->fetch()['m'] ?? 0);

    $stSlot = $pdo->prepare(
        'SELECT id, created_at, bet, reels_json, multiplier, payout
         FROM slot_rounds WHERE user_id = :uid ORDER BY created_at DESC, id DESC LIMIT 100'
    );
    $stSlot->execute([':uid' => $uid]);
    foreach ($stSlot->fetchAll(PDO::FETCH_ASSOC) as $sr) {
        $rj = $sr['reels_json'] ?? '[]';
        $decoded = json_decode((string) $rj, true);
        $reels = is_array($decoded) ? $decoded : [];
        $slotRounds[] = [
            'id' => (int) $sr['id'],
            'createdAt' => (int) $sr['created_at'],
            'bet' => (int) $sr['bet'],
            'reels' => $reels,
            'multiplier' => (int) $sr['multiplier'],
            'payout' => (int) $sr['payout'],
        ];
    }
} catch (Throwable $e) {
    $slotRounds = [];
    $slotMaxBet = 0;
}

$rouletteRounds = [];
$rouletteMaxBet = 0;
try {
    $stRlMax = $pdo->prepare('SELECT COALESCE(MAX(bet), 0) AS m FROM roulette_rounds WHERE user_id = :uid');
    $stRlMax->execute([':uid' => $uid]);
    $rouletteMaxBet = (int) ($stRlMax->fetch()['m'] ?? 0);

    $stRl = $pdo->prepare(
        'SELECT id, created_at, bet, bet_type, bet_value, winning_number, multiplier, payout
         FROM roulette_rounds WHERE user_id = :uid ORDER BY created_at DESC, id DESC LIMIT 100'
    );
    $stRl->execute([':uid' => $uid]);
    foreach ($stRl->fetchAll(PDO::FETCH_ASSOC) as $rr) {
        $bv = $rr['bet_value'];
        $rouletteRounds[] = [
            'id' => (int) $rr['id'],
            'createdAt' => (int) $rr['created_at'],
            'bet' => (int) $rr['bet'],
            'betType' => (string) $rr['bet_type'],
            'betValue' => $bv !== null && $bv !== '' ? (int) $bv : null,
            'winningNumber' => (int) $rr['winning_number'],
            'multiplier' => (int) $rr['multiplier'],
            'payout' => (int) $rr['payout'],
        ];
    }
} catch (Throwable $e) {
    $rouletteRounds = [];
    $rouletteMaxBet = 0;
}

$totalSpent = array_sum(array_column($purchases, 'price'));

$tgVerifiedAt = $row['telegram_verified_at'] ?? null;
$tgVerified = $tgVerifiedAt !== null && (int) $tgVerifiedAt > 0;
$tgUsername = '';
if ($tgVerified && isset($row['telegram_username']) && $row['telegram_username'] !== null && $row['telegram_username'] !== '') {
    $tgUsername = (string) $row['telegram_username'];
}
$tgPendingExp = null;
if (!$tgVerified && isset($row['telegram_pending_expires'])) {
    $pe = $row['telegram_pending_expires'];
    if ($pe !== null && (int) $pe > time()) {
        $tgPendingExp = (int) $pe;
    }
}

$crypto = [
    'btc' => $row['btc'] !== null && $row['btc'] !== '' ? (string) $row['btc'] : '',
    'eth' => $row['eth'] !== null && $row['eth'] !== '' ? (string) $row['eth'] : '',
    'usdtErc20' => $row['usdt_erc20'] !== null && $row['usdt_erc20'] !== '' ? (string) $row['usdt_erc20'] : '',
    'usdtTrc20' => $row['usdt_trc20'] !== null && $row['usdt_trc20'] !== '' ? (string) $row['usdt_trc20'] : '',
    'ltc' => $row['ltc'] !== null && $row['ltc'] !== '' ? (string) $row['ltc'] : '',
    'trx' => $row['trx'] !== null && $row['trx'] !== '' ? (string) $row['trx'] : '',
    'doge' => $row['doge'] !== null && $row['doge'] !== '' ? (string) $row['doge'] : '',
    'other' => $row['other'] !== null && $row['other'] !== '' ? (string) $row['other'] : '',
    'updatedAt' => isset($row['crypto_updated_at']) && $row['crypto_updated_at'] !== null ? (int) $row['crypto_updated_at'] : null,
];

$needsProfileCompletion = mocker_user_needs_profile_completion($row);
$needsPasswordChange = mocker_user_needs_password_change($row);
$twofaEnabled = (int) ($row['twofa_enabled'] ?? 0) === 1;
$levelProgress = mocker_level_progress_for_user($pdo, $uid);

echo json_encode(
    [
        'ok' => true,
        'needsProfileCompletion' => $needsProfileCompletion,
        'needsPasswordChange' => $needsPasswordChange,
        'twofa' => [
            'enabled' => $twofaEnabled,
        ],
        'user' => [
            'id' => (int) $row['id'],
            'username' => $row['username'],
            'email' => $needsProfileCompletion ? '' : $row['email'],
            'phone' => isset($row['phone']) && $row['phone'] !== null && $row['phone'] !== ''
                ? (string) $row['phone']
                : '',
            'coins' => (int) $row['coins'],
            'createdAt' => (int) $row['created_at'],
            'totalSpent' => $totalSpent,
        ],
        'crypto' => $crypto,
        'purchases' => $purchases,
        'complaints' => $complaints,
        'sponsorAccounts' => $sponsorAccounts,
        'wheelHistory' => $wheelHistory,
        'blackjack' => [
            'maxBet' => $blackjackMaxBet,
            'rounds' => $blackjackRounds,
        ],
        'slot' => [
            'maxBet' => $slotMaxBet,
            'rounds' => $slotRounds,
        ],
        'roulette' => [
            'maxBet' => $rouletteMaxBet,
            'rounds' => $rouletteRounds,
        ],
        'telegram' => [
            'botConfigured' => mocker_telegram_is_configured(),
            'verified' => $tgVerified,
            'username' => $tgUsername !== '' ? $tgUsername : null,
            'pendingExpiresAt' => $tgPendingExp,
        ],
        'level' => $levelProgress,
    ],
    JSON_UNESCAPED_UNICODE
);
