<?php
// get_events.php
// Returns list of ongoing and upcoming events in JSON format

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

try {
    include 'db.php';
    if ($conn->connect_error) {
        throw new Exception("Database connection failed: " . $conn->connect_error);
    }
} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => "Server configuration error"]);
    exit();
}

// Set dynamic base URL
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$host = $_SERVER['HTTP_HOST'];
$script_name = $_SERVER['SCRIPT_NAME']; // e.g., /api/get_events.php
$base_dir = dirname(dirname($script_name)); // e.g., /
$server_base = $protocol . $host . rtrim($base_dir, '/') . '/';

$response = ["status" => "success", "ongoing" => [], "upcoming" => [], "past" => []];

$user_id = isset($_GET['user_id']) ? $conn->real_escape_string($_GET['user_id']) : null;

try {
    // Helper function to fetch events with game info and join status
    function getEventsWithGame($conn, $condition, $user_id, $base)
    {
        $events = [];
        $join_sql = "";
        $is_joined_col = "NULL as is_joined";
        if ($user_id) {
            $is_joined_col = "(SELECT status FROM event_participants WHERE event_id = e.event_id AND user_id = '$user_id' LIMIT 1) as is_joined";
        }

        $sql = "SELECT e.*, g.game_name, g.game_icon, g.game_type, g.download_link, g.package_name, $is_joined_col 
                FROM events e 
                JOIN games g ON e.game_id = g.game_id 
                WHERE $condition";

        $result = $conn->query($sql);
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $row['event_image'] = formatEventImage($row['event_image'], $base);

                // Format game data
                $iconName = basename($row['game_icon']);
                $row['game_icon'] = $base . "assets/icons/" . $iconName;

                $linkName = basename($row['download_link']);
                $row['game_link'] = $base . "uploads/" . $linkName;

                $events[] = $row;
            }
        }
        return $events;
    }

    $response['ongoing'] = getEventsWithGame($conn, "e.start_date <= NOW() AND e.end_date >= NOW() ORDER BY e.start_date ASC", $user_id, $server_base);
    $response['upcoming'] = getEventsWithGame($conn, "e.start_date > NOW() ORDER BY e.start_date ASC", $user_id, $server_base);
    $response['past'] = getEventsWithGame($conn, "e.end_date < NOW() ORDER BY e.end_date DESC LIMIT 10", $user_id, $server_base);

} catch (Exception $e) {
    $response = ["status" => "error", "message" => $e->getMessage()];
}

function formatEventImage($image, $base)
{
    if (empty($image))
        return "";
    $imageName = basename($image);
    return $base . "assets/images/" . $imageName;
}

echo json_encode($response);
$conn->close();
?>