<?php
header('Content-Type: application/json');
require_once 'db.php';

$response = [
    "status" => "success",
    "video_feed" => [],
    "hero_slider" => [],
    "instant_games" => [],
    "trending" => [],
    "recommended" => [],
    "editors_choice" => [],
    "events" => [],
    "all_games" => []
];

// 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_home.php
$base_dir = dirname(dirname($script_name)); // if /api/get_home.php -> /
$server_base = $protocol . $host . rtrim($base_dir, '/') . '/';

// 1. Fetch Top 5 Videos for the Feed
$sql_videos = "SELECT * FROM videos ORDER BY created_at DESC LIMIT 5";
$res_videos = $conn->query($sql_videos);
if ($res_videos && $res_videos->num_rows > 0) {
    while ($row = $res_videos->fetch_assoc()) {
        $video_url = $row['video_url'];
        if (!filter_var($video_url, FILTER_VALIDATE_URL) && !empty($video_url)) {
            $video_url = $server_base . "assets/videos/" . ltrim($video_url, '/');
        }
        $response['video_feed'][] = [
            "id" => $row['video_id'],
            "url" => $video_url,
            "title" => $row['title'] ?? $row['video_title'] ?? 'Video',
            "thumbnail" => $row['thumbnail'] ?? $row['thumbnail_url'] ?? ''
        ];
    }
}

// 2. Fetch Instant Games
$sql_instant = "SELECT * FROM games WHERE game_type = 'instant' ORDER BY game_id DESC";
$res_instant = $conn->query($sql_instant);
if ($res_instant && $res_instant->num_rows > 0) {
    while ($row = $res_instant->fetch_assoc()) {
        $response['instant_games'][] = formatGame($row, $server_base);
    }
}

// 3. Fetch Trending (Top 10 by plays + downloads)
$sql_trending = "SELECT * FROM games ORDER BY (plays + downloads) DESC LIMIT 10";
$res_trending = $conn->query($sql_trending);
if ($res_trending && $res_trending->num_rows > 0) {
    while ($row = $res_trending->fetch_assoc()) {
        $response['trending'][] = formatGame($row, $server_base);
    }
}

// 4. Fetch Recommended
$sql_rec = "SELECT * FROM games WHERE is_recommended = 1 ORDER BY game_id DESC";
$res_rec = $conn->query($sql_rec);
if ($res_rec && $res_rec->num_rows > 0) {
    while ($row = $res_rec->fetch_assoc()) {
        $response['recommended'][] = formatGame($row, $server_base);
    }
}

// 5. Fetch Events
$user_id = isset($_GET['user_id']) ? $conn->real_escape_string($_GET['user_id']) : null;
$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_events = "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 e.end_date >= NOW() 
               ORDER BY e.start_date ASC";
$res_events = $conn->query($sql_events);
if ($res_events && $res_events->num_rows > 0) {
    while ($row = $res_events->fetch_assoc()) {
        $iconName = basename($row['game_icon']);
        $game_icon = $server_base . "assets/icons/" . $iconName;

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

        $response['events'][] = [
            "id" => $row['event_id'],
            "name" => $row['event_name'],
            "description" => $row['event_description'],
            "image" => formatEventImage($row['event_image'], $server_base),
            "entry_fee" => (float) $row['entry_fee'],
            "start_date" => $row['start_date'],
            "end_date" => $row['end_date'],
            "is_joined" => $row['is_joined'],
            "game_id" => $row['game_id'],
            "game_name" => $row['game_name'],
            "game_icon" => $game_icon,
            "game_link" => $game_link,
            "game_type" => $row['game_type'],
            "package_name" => $row['package_name']
        ];
    }
}

// 6. Fetch Hero Slider Games (category = 'slider')
$sql_slider = "SELECT g.* FROM games g JOIN game_categories gc ON g.game_id = gc.game_id WHERE gc.category = 'slider' ORDER BY g.game_id DESC";
$res_slider = $conn->query($sql_slider);
if ($res_slider && $res_slider->num_rows > 0) {
    while ($row = $res_slider->fetch_assoc()) {
        $response['hero_slider'][] = formatGame($row, $server_base);
    }
}

// 7. Fetch Editor's Choice Games (category = 'editor_choice')
$sql_editor = "SELECT g.* FROM games g JOIN game_categories gc ON g.game_id = gc.game_id WHERE gc.category = 'editor_choice' ORDER BY g.game_id DESC";
$res_editor = $conn->query($sql_editor);
if ($res_editor && $res_editor->num_rows > 0) {
    while ($row = $res_editor->fetch_assoc()) {
        $response['editors_choice'][] = formatGame($row, $server_base);
    }
}

// 8. Fetch All Games for Master List (for My Games filtering)
$sql_all = "SELECT * FROM games ORDER BY game_name ASC";
$res_all = $conn->query($sql_all);
if ($res_all && $res_all->num_rows > 0) {
    while ($row = $res_all->fetch_assoc()) {
        $response['all_games'][] = formatGame($row, $server_base);
    }
}

// Helper function to format game data
function formatGame($row, $base)
{
    // Icon Path - Strictly assets/icons/
    $icon = $row['game_icon'];
    if (!empty($icon)) {
        $iconName = basename($icon);
        $icon = $base . "assets/icons/" . $iconName;
    }

    // Download Link Path - Strictly uploads/
    $link = $row['download_link'];
    if (!empty($link)) {
        $linkName = basename($link);
        $link = $base . "uploads/" . $linkName;
    }

    // Video Path - Strictly assets/videos/
    $hero_video = $row['hero_video'] ?? null;
    if ($hero_video) {
        $videoName = basename($hero_video);
        $hero_video = $base . "assets/videos/" . $videoName;
    }

    return [
        "id" => $row['game_id'],
        "name" => $row['game_name'],
        "icon" => $icon,
        "link" => $link,
        "package_name" => $row['package_name'],
        "type" => $row['game_type'],
        "plays" => (int) ($row['plays'] ?? 0),
        "downloads" => (int) ($row['downloads'] ?? 0),
        "description" => $row['game_description'] ?? '',
        "hero_video" => $hero_video
    ];
}

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

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