<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/jwt.php';

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

function jsonResponse(int $code, array $data): void
{
    http_response_code($code);
    echo json_encode($data);
    exit;
}

try {
    $userId = verifyToken();

    if (!$userId) {
        jsonResponse(401, [
            "success" => false,
            "message" => "Unauthorized"
        ]);
    }

    $matchId = 0;

    if (isset($_GET['match_id'])) {
        $matchId = (int)$_GET['match_id'];
    } else {
        $data = json_decode(file_get_contents("php://input"), true);
        $matchId = (int)($data['match_id'] ?? 0);
    }

    if ($matchId <= 0) {
        jsonResponse(400, [
            "success" => false,
            "message" => "Invalid match_id"
        ]);
    }

    // Make sure this user is part of this match
    $stmt = $pdo->prepare("
        SELECT mp.id
        FROM match_players mp
        WHERE mp.match_id = ? AND mp.user_id = ?
        LIMIT 1
    ");
    $stmt->execute([$matchId, $userId]);
    $membership = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$membership) {
        jsonResponse(403, [
            "success" => false,
            "message" => "You are not part of this match"
        ]);
    }

    // Match info
    $stmt = $pdo->prepare("
        SELECT
            id,
            template_id,
            match_type,
            mode,
            status,
            entry_fee,
            max_players,
            country_code,
            platform_fee_percent,
            prize_split_json,
            created_at,
            started_at,
            finished_at
        FROM matches
        WHERE id = ?
        LIMIT 1
    ");
    $stmt->execute([$matchId]);
    $match = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$match) {
        jsonResponse(404, [
            "success" => false,
            "message" => "Match not found"
        ]);
    }

    // Current players
    $stmt = $pdo->prepare("
        SELECT
            mp.user_id,
            mp.status,
            mp.moves_made,
            mp.skips_used,
            mp.result_status,
            mp.payout_status,
            mp.joined_at,
            u.name
        FROM match_players mp
        INNER JOIN users u ON u.id = mp.user_id
        WHERE mp.match_id = ?
        ORDER BY mp.id ASC
    ");
    $stmt->execute([$matchId]);
    $players = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $currentPlayers = count($players);
    $maxPlayers = (int)$match['max_players'];
    $isFull = ($currentPlayers >= $maxPlayers);

    $status = (string)$match['status'];

    // Safety sync: if full but status still waiting/open, fix it
    if ($isFull && in_array($status, ['waiting', 'open'], true)) {
        $stmt = $pdo->prepare("
            UPDATE matches
            SET status = 'full'
            WHERE id = ?
        ");
        $stmt->execute([$matchId]);
        $status = 'full';
    }

    $readyToStart = in_array($status, ['full', 'in_progress'], true) && $isFull;

     

$expiresAt = $match['expires_at'] ?? null;
$secondsLeft = null;
$timedOut = false;

if ($expiresAt) {
    $secondsLeft = strtotime($expiresAt) - time();
    if ($secondsLeft < 0) {
        $secondsLeft = 0;
    }

    if (in_array($status, ['waiting', 'open'], true) && $secondsLeft <= 0 && !$isFull) {
        $timedOut = true;
    }
}    $playerList = array_map(function ($row) {
        return [
            "user_id" => (int)$row['user_id'],
            "name" => $row['name'],
            "status" => $row['status'],
            "moves_made" => (int)$row['moves_made'],
            "skips_used" => (int)$row['skips_used'],
            "result_status" => $row['result_status'],
            "payout_status" => $row['payout_status'],
            "joined_at" => $row['joined_at']
        ];
    }, $players);

    jsonResponse(200, [
        "success" => true,
        "match" => [
            "match_id" => (int)$match['id'],

            "template_id" => $match['template_id'] !== null ? (int)$match['template_id'] : null,
            "match_type" => $match['match_type'],
            "mode" => $match['mode'],
            "status" => $status,
            "entry_fee" => number_format((float)$match['entry_fee'], 2, '.', ''),
            "max_players" => $maxPlayers,
            "current_players" => $currentPlayers,
            "is_full" => $isFull,
            "ready_to_start" => $readyToStart,
            "country_code" => $match['country_code'],
            "platform_fee_percent" => number_format((float)$match['platform_fee_percent'], 2, '.', ''),
            "prize_split_json" => $match['prize_split_json'],
            "created_at" => $match['created_at'],
            "started_at" => $match['started_at'],
            "finished_at" => $match['finished_at']
        ],
        "players" => $playerList
    ]);
} catch (Throwable $e) {
    jsonResponse(500, [
        "success" => false,
        "message" => "Server error",
        "error" => $e->getMessage()
    ]);
}
