<?php
declare(strict_types=1);

include 'config.php';
require __DIR__ . '/jwt/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$jwtSecret = "Shuvo_2025_SECURE49797567697979696967676967696979797969796f796f796f";

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

date_default_timezone_set('Asia/Dhaka');
$conn->query("SET time_zone = '+06:00'");

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(["error" => "Invalid Request Method"], JSON_UNESCAPED_UNICODE);
    exit;
}

function normalizeResult($value): string
{
    return strtoupper(trim((string)$value));
}

function sortByIdAsc(array &$items): void
{
    usort($items, static function ($a, $b) {
        return ((int)($a['id'] ?? 0)) <=> ((int)($b['id'] ?? 0));
    });
}

function buildMatchRow(array $row, bool $joined, bool $isCompleted = false): array
{
    return [
        "id" => (string)($row["id"] ?? ""),
        "match_title" => (string)($row["match_title"] ?? ""),
        "match_time" => (string)($row["match_time"] ?? ""),
        "total_prize" => (string)($row["total_prize"] ?? ""),
        "per_kill" => (string)($row["per_kill"] ?? ""),
        "entry_fee" => (string)($row["entry_fee"] ?? ""),
        "entry_type" => (string)($row["entry_type"] ?? ""),
        "match_type" => (string)($row["match_type"] ?? ""),
        "version" => (string)($row["version"] ?? ""),
        "play_map" => (string)($row["play_map"] ?? ""),
        "registration" => (string)($row["registration"] ?? ""),
        "prize_details" => (string)($row["prize_details"] ?? ""),
        "room_id" => (string)($row["room_id"] ?? ""),
        "room_pass" => (string)($row["room_pass"] ?? ""),
        "total_player" => (string)($row["total_player"] ?? ""),
        "total_joiner" => (string)($row["total_joiner"] ?? "0"),
        "match_result" => $isCompleted ? "YES" : (string)($row["match_result"] ?? ""),
        "timer" => (string)($row["timer"] ?? ""),
        "join_type" => (string)($row["join_type"] ?? ""),
        "image_link" => (string)($row["image_link"] ?? ""),
        "locked" => (string)($row["locked"] ?? "0"),
        "locked_type" => (string)($row["locked_type"] ?? ""),
        "player_name_change" => (string)($row["player_name_change"] ?? "0"),
        "joined" => $joined
    ];
}

function fetchJoinedMap(mysqli $conn, string $email): array
{
    $joinedMap = [];

    $stmt = $conn->prepare("SELECT DISTINCT match_id FROM joiners WHERE email = ?");
    if (!$stmt) {
        return $joinedMap;
    }

    $stmt->bind_param("s", $email);
    $stmt->execute();
    $res = $stmt->get_result();

    while ($row = $res->fetch_assoc()) {
        $joinedMap[(string)$row["match_id"]] = true;
    }

    $stmt->close();
    return $joinedMap;
}

function appendMatchRow(array $row, array $joinedMap, array &$activeMatches, array &$resultMatches, bool $forceCompleted = false): void
{
    $rawResult = normalizeResult($row["match_result"] ?? "");

    // Going value হলে একদম JSON-এ ঢুকবে না
    if ($rawResult === 'GOING') {
        return;
    }

    $matchId = (string)($row["id"] ?? "");
    $isJoined = isset($joinedMap[$matchId]);

    $formattedRow = buildMatchRow($row, $isJoined, $forceCompleted);

    if ($forceCompleted || normalizeResult($formattedRow["match_result"] ?? '') === "YES") {
        $resultMatches[] = $formattedRow;
    } else {
        $activeMatches[] = $formattedRow;
    }
}

try {
    $token = trim((string)($_POST["token"] ?? ''));
    $match_type = trim((string)($_POST["match_type"] ?? ''));
    $result_filter = strtolower(trim((string)($_POST["result_filter"] ?? '')));

    if ($token === '' || $match_type === '') {
        echo json_encode(["error" => "Token and Match Type are required"], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $decoded = JWT::decode($token, new Key($jwtSecret, 'HS256'));
    $email = (string)($decoded->email ?? '');

    if ($email === '') {
        echo json_encode(["error" => "Invalid Token Data"], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $current_time = date('Y-m-d H:i:s');
    $current_timestamp = time();

    $pending_count = 0;
    $next_match_in_minutes = 0;

    $activeMatches = [];
    $resultMatches = [];
    $match_schedule_count = 0;
    $freefire_count = 0;

    $joinedMap = fetchJoinedMap($conn, $email);

    // Pending count + next match time
    $sqlPending = "
        SELECT
            COUNT(*) AS p_count,
            MIN(REPLACE(start_time, 'T', ' ')) AS next_time
        FROM match_schedule
        WHERE match_type = ?
          AND REPLACE(start_time, 'T', ' ') > ?
          AND status != 'Completed'
          AND LOWER(TRIM(COALESCE(match_result, ''))) <> 'going'
    ";
    $stmtP = $conn->prepare($sqlPending);
    $stmtP->bind_param("ss", $match_type, $current_time);
    $stmtP->execute();
    $resP = $stmtP->get_result()->fetch_assoc();
    $stmtP->close();

    if ($resP) {
        $pending_count = (int)($resP["p_count"] ?? 0);
        if (!empty($resP["next_time"])) {
            $diff = strtotime($resP["next_time"]) - $current_timestamp;
            $next_match_in_minutes = max(0, (int)floor($diff / 60));
        }
    }

    // Active schedule
    $sqlActiveSchedule = "
        SELECT id, match_title, match_time, total_prize, per_kill, entry_fee, entry_type, match_type, version,
               play_map, registration, prize_details, room_id, room_pass, total_player, total_joiner,
               match_result, timer, join_type, image_link, locked, locked_type, player_name_change
        FROM match_schedule
        WHERE match_type = ?
          AND REPLACE(start_time, 'T', ' ') <= ?
          AND status != 'Completed'
          AND LOWER(TRIM(COALESCE(match_result, ''))) <> 'going'
        ORDER BY id ASC
    ";
    $stmt1 = $conn->prepare($sqlActiveSchedule);
    $stmt1->bind_param("ss", $match_type, $current_time);
    $stmt1->execute();
    $res1 = $stmt1->get_result();

    while ($row = $res1->fetch_assoc()) {
        $match_schedule_count++;
        appendMatchRow($row, $joinedMap, $activeMatches, $resultMatches, false);
    }
    $stmt1->close();

    // Freefire
    $sqlFreefire = "
        SELECT id, match_title, match_time, total_prize, per_kill, entry_fee, entry_type, match_type, version,
               play_map, registration, prize_details, room_id, room_pass, total_player, total_joiner,
               match_result, timer, join_type, image_link, locked, locked_type, player_name_change
        FROM freefire
        WHERE match_type = ?
          AND LOWER(TRIM(COALESCE(match_result, ''))) <> 'going'
        ORDER BY id ASC
    ";
    $stmt3 = $conn->prepare($sqlFreefire);
    $stmt3->bind_param("s", $match_type);
    $stmt3->execute();
    $res3 = $stmt3->get_result();

    while ($row = $res3->fetch_assoc()) {
        $freefire_count++;
        appendMatchRow($row, $joinedMap, $activeMatches, $resultMatches, false);
    }
    $stmt3->close();

    // Completed matches
    $sqlCompleted = "
        SELECT id, match_title, match_time, total_prize, per_kill, entry_fee, entry_type, match_type, version,
               play_map, registration, prize_details, room_id, room_pass, total_player, total_joiner,
               match_result, timer, join_type, image_link, locked, locked_type, player_name_change
        FROM match_schedule
        WHERE match_type = ?
          AND status = 'Completed'
          AND LOWER(TRIM(COALESCE(match_result, ''))) <> 'going'
        ORDER BY id ASC
    ";
    $stmt2 = $conn->prepare($sqlCompleted);
    $stmt2->bind_param("s", $match_type);
    $stmt2->execute();
    $res2 = $stmt2->get_result();

    while ($row2 = $res2->fetch_assoc()) {
        $match_schedule_count++;
        appendMatchRow($row2, $joinedMap, $activeMatches, $resultMatches, true);
    }
    $stmt2->close();

    sortByIdAsc($activeMatches);
    sortByIdAsc($resultMatches);

    $total_matches = $match_schedule_count + $freefire_count;

    if ($result_filter === 'yes') {
        $activeMatches = $resultMatches;
        $resultMatches = [];
    } elseif ($result_filter === 'no') {
        $filtered = [];
        foreach ($activeMatches as $match) {
            if (normalizeResult($match['match_result'] ?? '') === 'NO') {
                $filtered[] = $match;
            }
        }
        $activeMatches = $filtered;
        $resultMatches = [];
    } elseif ($result_filter === 'all') {
        $allMatches = array_merge($activeMatches, $resultMatches);
        sortByIdAsc($allMatches);
        $activeMatches = $allMatches;
        $resultMatches = [];
    }

    echo json_encode([
        "status" => "success",
        "total_matches" => (string)$total_matches,
        "match_schedule_count" => (string)$match_schedule_count,
        "freefire_count" => (string)$freefire_count,
        "pending_matches" => (string)$pending_count,
        "next_match_in_minutes" => (string)$next_match_in_minutes,
        "matches" => $activeMatches,
        "results" => $resultMatches
    ], JSON_UNESCAPED_UNICODE);

    $conn->close();
} catch (Exception $e) {
    echo json_encode([
        "error" => "Invalid or Expired Token",
        "message" => $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
?>