<?php
require_once __DIR__ . '/../includes/config.php';

/**
 * Make TMDB API Request
 */
function makeRequest($endpoint, $params = []) {
    $url = TMDB_BASE_URL . $endpoint;
    
    if (!empty($params)) {
        $url .= '?' . http_build_query($params);
    }
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . TMDB_ACCESS_TOKEN,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200) {
        return json_decode($response, true);
    }
    
    return null;
}

/**
 * Get Trending Movies
 */
function getTrendingMovies($timeWindow = 'week') {
    return makeRequest("/trending/movie/{$timeWindow}");
}

/**
 * Get Trending TV Shows
 */
function getTrendingTV($timeWindow = 'week') {
    return makeRequest("/trending/tv/{$timeWindow}");
}

/**
 * Get Trending Anime (Animation Genre)
 */
function getTrendingAnime($timeWindow = 'week') {
    // Fetch 2 pages to get more items
    $page1 = makeRequest("/discover/tv", [
        'with_genres' => '16', // Animation genre ID
        'sort_by' => 'popularity.desc',
        'with_origin_country' => 'JP', // Japanese origin for anime
        'page' => 1
    ]);
    
    $page2 = makeRequest("/discover/tv", [
        'with_genres' => '16',
        'sort_by' => 'popularity.desc',
        'with_origin_country' => 'JP',
        'page' => 2
    ]);
    
    // Merge results
    if ($page1 && $page2) {
        $page1['results'] = array_merge($page1['results'] ?? [], $page2['results'] ?? []);
    }
    
    return $page1;
}

/**
 * Search Media
 */
function searchMedia($query, $type = 'multi') {
    if (empty($query)) {
        return null;
    }
    
    return makeRequest("/search/{$type}", [
        'query' => $query,
        'include_adult' => 'false'
    ]);
}

/**
 * Get Media Details
 */
function getDetails($id, $type = 'movie') {
    return makeRequest("/{$type}/{$id}", [
        'append_to_response' => 'credits,videos,recommendations,similar'
    ]);
}

/**
 * Get Cast
 */
function getCast($id, $type = 'movie') {
    $data = makeRequest("/{$type}/{$id}/credits");
    return $data['cast'] ?? [];
}

/**
 * Get Videos/Trailers
 */
function getVideos($id, $type = 'movie') {
    $data = makeRequest("/{$type}/{$id}/videos");
    $videos = $data['results'] ?? [];
    
    // Filter and prioritize actual trailers
    $trailers = [];
    $teasers = [];
    $others = [];
    
    foreach ($videos as $video) {
        if ($video['site'] !== 'YouTube') continue;
        
        $videoType = strtolower($video['type'] ?? '');
        $videoName = strtolower($video['name'] ?? '');
        
        // Skip clips, featurettes, behind the scenes
        if (strpos($videoName, 'clip') !== false || 
            strpos($videoName, 'scene') !== false ||
            strpos($videoType, 'clip') !== false ||
            strpos($videoType, 'featurette') !== false ||
            strpos($videoType, 'behind') !== false) {
            continue;
        }
        
        // Prioritize official trailers
        if ($videoType === 'trailer' && 
            (strpos($videoName, 'official') !== false || 
             strpos($videoName, 'main') !== false ||
             strpos($videoName, 'final') !== false)) {
            array_unshift($trailers, $video);
        } elseif ($videoType === 'trailer') {
            $trailers[] = $video;
        } elseif ($videoType === 'teaser') {
            $teasers[] = $video;
        } else {
            $others[] = $video;
        }
    }
    
    // Return in priority order
    return array_merge($trailers, $teasers, $others);
}

/**
 * Get Recommendations
 */
function getRecommendations($id, $type = 'movie') {
    return makeRequest("/{$type}/{$id}/recommendations");
}

/**
 * Get Popular Media
 */
function getPopular($type = 'movie') {
    return makeRequest("/{$type}/popular");
}

/**
 * Get Top Rated Media
 */
function getTopRated($type = 'movie') {
    return makeRequest("/{$type}/top_rated");
}

/**
 * Get Image URL
 */
function getImageUrl($path, $size = 'w500') {
    if (empty($path)) {
        return 'assets/images/placeholder.jpg';
    }
    return TMDB_IMAGE_BASE . "/{$size}{$path}";
}

/**
 * Get Backdrop URL
 */
function getBackdropUrl($path, $size = 'original') {
    if (empty($path)) {
        return 'assets/images/placeholder-backdrop.jpg';
    }
    return TMDB_IMAGE_BASE . "/{$size}{$path}";
}

/**
 * Format Runtime
 */
function formatRuntime($minutes) {
    if (empty($minutes)) return 'N/A';
    $hours = floor($minutes / 60);
    $mins = $minutes % 60;
    return "{$hours}h {$mins}m";
}

/**
 * Get Year from Date
 */
function getYear($date) {
    return !empty($date) ? date('Y', strtotime($date)) : 'N/A';
}

/**
 * Format Rating
 */
function formatRating($rating) {
    return number_format($rating, 1);
}
