<?php
include 'config.php';
header('Content-Type: application/json; charset=utf-8');
$conn->set_charset("utf8mb4");

$tab = isset($_GET['tab']) ? $_GET['tab'] : 'all';

if ($tab === 'upcoming') {
    $result = mysqli_query($conn, "SELECT * FROM ZabbarXLudoMatch WHERE tab_category = 'upcoming' ORDER BY id DESC");
} elseif ($tab === 'live') {
    $result = mysqli_query($conn, "SELECT * FROM ZabbarXLudoMatch WHERE tab_category = 'live' ORDER BY id DESC");
} elseif ($tab === 'completed') {
    $result = mysqli_query($conn, "SELECT * FROM ZabbarXLudoMatch WHERE tab_category = 'completed' ORDER BY id DESC");
} else {
    $result = mysqli_query($conn, "SELECT * FROM ZabbarXLudoMatch ORDER BY id DESC");
}

if ($result && mysqli_num_rows($result) > 0) {
    $data = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $cat = strtolower($row['tab_category'] ?? '');
        
        if ($cat === 'live') {
            $row['button_text'] = 'WATCH';
            $row['players_status'] = "Playing";
        } else if ($cat === 'completed') {
            $row['button_text'] = 'RESULTS';
            $row['players_status'] = $row['players_status'] ?? "Finished";
        } else {
            $row['button_text'] = 'JOIN';
            $row['players_status'] = ($row['total_joined'] ?? '0') . "/" . ($row['total_join'] ?? '2');
        }
        
        $data[] = $row;
    }
    
    echo json_encode([
        "status" => true,
        "data" => $data,
        "total" => count($data)
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} else {
    echo json_encode([
        "status" => false,
        "message" => "No matches found"
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
mysqli_close($conn);
?>