<?php
header('Content-Type: application/json');
require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/Auth.php';

if (session_status() === PHP_SESSION_NONE) session_start();
$user = auth()->getUser();
if (!$user) { echo json_encode(['success' => false, 'error' => 'Not logged in']); exit; }

$input = json_decode(file_get_contents('php://input'), true);
$tournamentId = (int)($input['tournament_id'] ?? 0);

try {
    $tournament = dbFetch("SELECT * FROM tournaments WHERE id = ? AND status = 'active'", [$tournamentId]);
    if (!$tournament) { echo json_encode(['success' => false, 'error' => 'Tournament not found']); exit; }
    
    $wallet = dbFetch("SELECT * FROM user_wallets WHERE user_id = ?", [$user['id']]);
    if ((float)$wallet['balance'] < (float)$tournament['entry_fee']) {
        echo json_encode(['success' => false, 'error' => 'Insufficient balance']); exit;
    }
    
    // Check if already joined
    $existing = dbFetch("SELECT id FROM tournament_participants WHERE tournament_id = ? AND user_id = ?", [$tournamentId, $user['id']]);
    if ($existing) { echo json_encode(['success' => false, 'error' => 'Already joined']); exit; }
    
    // Deduct fee and add to tournament
    dbQuery("UPDATE user_wallets SET balance = balance - ?, tournament_balance = ? WHERE user_id = ?", 
        [$tournament['entry_fee'], $tournament['starting_balance'] ?? 10000, $user['id']]);
    
    dbInsert('tournament_participants', [
        'tournament_id' => $tournamentId,
        'user_id' => $user['id'],
        'balance' => $tournament['starting_balance'] ?? 10000,
        'joined_at' => date('Y-m-d H:i:s')
    ]);
    
    echo json_encode(['success' => true, 'balance' => $tournament['starting_balance'] ?? 10000]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
