<?php
include 'config.php';
$conn->set_charset("utf8mb4");

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

$email = trim($_POST['email'] ?? '');

if (empty($email)) {
    echo json_encode([
        "status" => "error",
        "message" => "Email required"
    ]);
    exit;
}

function parseMatchTime($timer_str) {
    $timer_str = trim($timer_str);
    $timer_str = str_replace(' At ', ' ', $timer_str);
    $timer_str = str_replace('At ', ' ', $timer_str);
    $timer_str = preg_replace('/^(Time:|Foment)\s*/i', '', $timer_str);
    $timer_str = preg_replace('/\s+/', ' ', trim($timer_str));
    $match_time = DateTime::createFromFormat('d/m/Y h:i A', $timer_str);
    return $match_time ?: false;
}

$data = [];
$now = new DateTime();

$sql = "
    SELECT f.*
    FROM joiners j
    INNER JOIN freefire f ON j.match_id = f.id
    WHERE j.email = ?
    AND f.match_result = 'NO'
    GROUP BY f.id
";

$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $timer_str = $row['timer'] ?? '';
        $match_time = parseMatchTime($timer_str);
        if ($match_time && $match_time > $now) {
            $data[] = $row;
        }
    }
}

$stmt->close();

if (empty($data)) {
    $sql = "
        SELECT m.*
        FROM joiners j
        INNER JOIN match_schedule m ON j.match_id = m.id
        WHERE j.email = ?
        AND m.match_result = 'NO'
        GROUP BY m.id
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $timer_str = $row['timer'] ?? '';
            $match_time = parseMatchTime($timer_str);
            if ($match_time && $match_time > $now) {
                $data[] = $row;
            }
        }
    }

    $stmt->close();
}

if (empty($data)) {
    echo json_encode([
        "status" => "error",
        "message" => "No Upcoming Matches Found"
    ]);
} else {
    echo json_encode([
        "status" => "success",
        "count" => count($data),
        "matches" => $data
    ]);
}

$conn->close();
?>