<?php
// error_reporting(0); // লাইভ সার্ভারে এটি অন রাখবেন
ini_set('display_errors', 1); // টেস্টিং এর জন্য এরর অন রাখা হলো

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

// JWT ফাইলটি ঠিক এই ডিরেক্টরিতে না থাকলে 500 error আসবে, তাই লোকেশন ঠিক আছে কিনা চেক করবেন
require __DIR__ . '/jwt/autoload.php';

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

$jwtSecret = "Shuvo_2025_SECURE49797567697979696967676967696979797969796f796f796f";

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $token = $_POST["token"] ?? '';
    $match_type = $_POST["match_type"] ?? '';

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

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

        if (empty($email)) {
            echo json_encode(["error" => "Invalid Token Data"]);
            exit;
        }
    } catch (Exception $e) {
        echo json_encode(["error" => "Invalid or Expired Token"]);
        exit;
    }

    $activeMatches = [];
    $resultMatches = [];
    $match_schedule_count = 0;
    $freefire_count = 0;
    
    $current_time = date('Y-m-d H:i:s');

    // FIX: start_time <= ? করা হয়েছে
    $sql = "(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, 'match_schedule' AS source FROM match_schedule WHERE match_type = ? AND start_time <= ? AND status != 'Completed') UNION ALL (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, 'freefire' AS source FROM freefire WHERE match_type = ?)";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sss", $match_type, $current_time, $match_type);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $match_id = $row["id"]; 
        $source = $row["source"]; 

        if ($source === 'match_schedule') {
            $match_schedule_count++;
        } elseif ($source === 'freefire') {
            $freefire_count++;
        }

        $sqlCheck = "SELECT id FROM joiners WHERE email = ? AND match_id = ? LIMIT 1";
        $stmtCheck = $conn->prepare($sqlCheck);
        $stmtCheck->bind_param("si", $email, $match_id);
        $stmtCheck->execute();
        $resultCheck = $stmtCheck->get_result();
        
        $is_joined = ($resultCheck->num_rows === 1) ? true : false;
        $stmtCheck->close();

        $formattedRow = [
            "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" => (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" => $is_joined
        ];

        if (strtoupper(trim($formattedRow["match_result"])) === "YES") {
            $resultMatches[] = $formattedRow;
        } else {
            $activeMatches[] = $formattedRow;
        }
    }
    $stmt->close();

    $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'";
    
    $stmt2 = $conn->prepare($sqlCompleted);
    $stmt2->bind_param("s", $match_type);
    $stmt2->execute();
    $res2 = $stmt2->get_result();

    while ($row2 = $res2->fetch_assoc()) {
        $match_schedule_count++;
        $match_id2 = $row2["id"];
        
        $sqlCheck2 = "SELECT id FROM joiners WHERE email = ? AND match_id = ? LIMIT 1";
        $stmtCheck2 = $conn->prepare($sqlCheck2);
        $stmtCheck2->bind_param("si", $email, $match_id2);
        $stmtCheck2->execute();
        $resultCheck2 = $stmtCheck2->get_result();
        $is_joined2 = ($resultCheck2->num_rows === 1) ? true : false;
        $stmtCheck2->close();
        
        $formattedRow2 = [
            "id" => (string) $row2["id"],
            "match_title" => (string) ($row2["match_title"] ?? ""),
            "match_time" => (string) ($row2["match_time"] ?? ""),
            "total_prize" => (string) ($row2["total_prize"] ?? ""),
            "per_kill" => (string) ($row2["per_kill"] ?? ""),
            "entry_fee" => (string) ($row2["entry_fee"] ?? ""),
            "entry_type" => (string) ($row2["entry_type"] ?? ""),
            "match_type" => (string) ($row2["match_type"] ?? ""),
            "version" => (string) ($row2["version"] ?? ""),
            "play_map" => (string) ($row2["play_map"] ?? ""),
            "registration" => (string) ($row2["registration"] ?? ""),
            "prize_details" => (string) ($row2["prize_details"] ?? ""),
            "room_id" => (string) ($row2["room_id"] ?? ""),
            "room_pass" => (string) ($row2["room_pass"] ?? ""),
            "total_player" => (string) ($row2["total_player"] ?? ""),
            "total_joiner" => (string) ($row2["total_joiner"] ?? "0"),
            "match_result" => "YES",
            "timer" => (string) ($row2["timer"] ?? ""),
            "join_type" => (string) ($row2["join_type"] ?? ""),
            "image_link" => (string) ($row2["image_link"] ?? ""),
            "locked" => (string) ($row2["locked"] ?? "0"),
            "locked_type" => (string) ($row2["locked_type"] ?? ""),
            "player_name_change" => (string) ($row2["player_name_change"] ?? "0"),
            "joined" => $is_joined2
        ];
        $resultMatches[] = $formattedRow2;
    }
    $stmt2->close();

    $total_matches = $match_schedule_count + $freefire_count;

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

    $conn->close();
    exit;
} else {
    echo json_encode(["error" => "Invalid Request Method"]);
}
?>
