<?php

ini_set('memory_limit', '1024M');
ini_set('max_execution_time', '300');
ini_set('max_input_time', '300');
require_once 'config.php';
require_once 'generate_live_playlist.php';

set_time_limit(0);
accessLog();


if (!$GLOBALS['DEBUG']) {
    error_reporting(0);	
}	


$BasePath = locateBaseURL();
$urlComponents = parse_url($BasePath);
$scheme = 'https';
$host = $urlComponents['host'];
$domain = $scheme . '://' . $host;

$expectedUsername = 'base';
$expectedPassword = 'base';
if (
    (isset($_GET['username']) || isset($_GET['password'])) &&
    (($_GET['username'] ?? '') !== $expectedUsername || ($_GET['password'] ?? '') !== $expectedPassword)
) {
    echo json_encode([
        'user_info' => [
            'auth' => 0,
            'status' => 'Disabled',
            'message' => 'Invalid username or password'
        ],
        'server_info' => [
            'url' => parse_url($domain, PHP_URL_HOST),
            'timestamp_now' => time(),
            'time_now' => date("Y-m-d H:i:s", time())
        ]
    ]);
    exit();
}


//Publicly exposed private API key for YouTube.
$yt_api_key = 'AIzaSyA-dlBUjVQeuc4a6ZN4RkNUYDFddrVLxrA';

//Set header to always return json.
header('Content-Type: application/json');

function spandaman_api_json_file($path) {
	if (!is_file($path)) return array();
	$raw = file_get_contents($path);
	if (is_string($raw) && substr($raw, 0, 3) === "\xEF\xBB\xBF") {
		$raw = substr($raw, 3);
	}
	$data = json_decode($raw, true);
	return is_array($data) ? $data : array();
}

function spandaman_api_url_host($url) {
	$host = parse_url((string)$url, PHP_URL_HOST);
	return strtolower((string)$host);
}

function spandaman_api_url_path_extension($url) {
	$path = parse_url((string)$url, PHP_URL_PATH);
	if (!is_string($path) || $path === '') {
		return '';
	}
	$ext = pathinfo($path, PATHINFO_EXTENSION);
	return strtolower((string)$ext);
}

function spandaman_api_is_ip_bound_google_media($url) {
	$host = spandaman_api_url_host($url);
	if ($host === '') {
		return false;
	}
	return $host === 'googlevideo.com'
		|| substr($host, -16) === '.googlevideo.com'
		|| $host === 'googleusercontent.com'
		|| substr($host, -21) === '.googleusercontent.com';
}

function spandaman_api_extra_vod_ready_for_xtream($row) {
	if (!is_array($row)) {
		return false;
	}
	$url = (string)($row['url'] ?? ($row['direct_source'] ?? ''));
	if ($url === '' || empty($row['verified'])) {
		return false;
	}
	if (spandaman_api_is_ip_bound_google_media($url)) {
		return false;
	}
	$ext = spandaman_api_url_path_extension($url);
	// Imported HLS rows here are usually linear channels mislabelled as VOD.
	// Keep true file-like VODs only; the full scanner can promote HLS VODs after route verification.
	return in_array($ext, array('mp4', 'mkv', 'avi', 'mov', 'webm', 'm4v'), true);
}

function spandaman_api_playable_only_default() {
	if (isset($_GET['full']) && $_GET['full'] === '1') {
		return false;
	}
	if (isset($_GET['playable_only'])) {
		return $_GET['playable_only'] !== '0';
	}
	if (isset($_GET['action']) && in_array($_GET['action'], array('get_series', 'get_vod_streams'), true)) {
		return false;
	}
	return true;
}

function spandaman_api_live_group_name($row) {
	$group = trim((string)($row['group'] ?? ($row['group-title'] ?? ($row['category'] ?? ''))));
	if ($group === '' || strcasecmp($group, 'Undefined') === 0) {
		return 'Live';
	}
	if (preg_match('/\b(vod|movie|movies|film|films|series|empty name)\b/i', $group)) {
		return 'Live TV';
	}
	return $group;
}

function spandaman_api_live_category_map($rows) {
	$map = array();
	$next = 881000;
	foreach ($rows as $row) {
		if (!is_array($row)) continue;
		$group = spandaman_api_live_group_name($row);
		if (!isset($map[$group])) {
			$map[$group] = (string)$next;
			$next++;
		}
	}
	if (empty($map)) {
		$map['Live'] = '881000';
	}
	return $map;
}

function spandaman_api_hosted_live_route($id, $extension = 'm3u8') {
	global $BasePath;
	$id = (string)$id;
	if ($id === '' || !ctype_digit($id)) {
		return '';
	}
	$extension = strtolower((string)$extension) === 'ts' ? 'ts' : 'm3u8';
	return rtrim($BasePath, '/') . '/live/base/base/' . rawurlencode($id) . '.' . $extension;
}

function spandaman_api_normalize_live_player_row($row) {
	if (!is_array($row)) {
		return $row;
	}
	$id = (string)($row['stream_id'] ?? ($row['id'] ?? ''));
	$route = spandaman_api_hosted_live_route($id, 'm3u8');
	if ($route !== '') {
		$original = (string)($row['direct_source'] ?? ($row['video_url'] ?? ($row['url'] ?? '')));
		if ($original !== '' && empty($row['spandaman_source_url'])) {
			$row['spandaman_source_url'] = $original;
		}
		$row['direct_source'] = $route;
		$row['video_url'] = $route;
	}
	$row['container_extension'] = 'm3u8';
	$row['stream_type'] = 'live';
	return $row;
}

function spandaman_api_extra_verified_live_source_rows() {
	$rows = spandaman_api_json_file(__DIR__ . '/spandaman_extra_verified_live_streams.json');
	if (empty($rows)) {
		$rows = spandaman_api_json_file(__DIR__ . '/channels/spandaman_extra_verified_live_streams.json');
	}
	return $rows;
}

function spandaman_api_player_movie_row($row, $isAdult = false) {
	global $BasePath;
	if (!is_array($row)) {
		return $row;
	}
	$id = (string)($row['stream_id'] ?? '');
	if ($id !== '') {
		$base = rtrim($BasePath, '/');
		$row['direct_source'] = $base . '/movie/base/base/' . rawurlencode($id) . ($isAdult ? '.mp4' : '.m3u8');
	}
	$row['container_extension'] = $isAdult ? 'mp4' : 'm3u8';
	return $row;
}

function spandaman_api_series_episode_map_path() {
	return __DIR__ . '/spandaman_series_episode_map.json';
}

function spandaman_api_merge_series_episode_map($episodeMap) {
	if (empty($episodeMap) || !is_array($episodeMap)) {
		return;
	}
	$path = spandaman_api_series_episode_map_path();
	$current = spandaman_api_json_file($path);
	if (!is_array($current)) {
		$current = array();
	}
	foreach ($episodeMap as $id => $token) {
		$current[(string)$id] = (string)$token;
	}
	$tmp = $path . '.tmp';
	@file_put_contents($tmp, json_encode($current, JSON_UNESCAPED_SLASHES));
	@rename($tmp, $path);
	@chmod($path, 0777);
}

function spandaman_api_small_cached_rows($cachePath, $sourcePath, $idKeys, $ids) {
	$cached = spandaman_api_json_file($cachePath);
	if (!empty($cached)) {
		return $cached;
	}
	if (!is_file($sourcePath) || filesize($sourcePath) > 80000000) {
		return array();
	}
	$out = array();
	foreach (spandaman_api_json_file($sourcePath) as $row) {
		if (!is_array($row)) continue;
		foreach ($idKeys as $key) {
			$id = (string)($row[$key] ?? '');
			if ($id !== '' && !empty($ids[$id])) {
				$out[] = $row;
				break;
			}
		}
	}
	return $out;
}

function spandaman_api_stream_json_array_inner($path, &$first) {
	if (!is_file($path)) return;
	$size = filesize($path);
	if ($size <= 2) return;
	$fh = fopen($path, 'rb');
	if (!$fh) return;
	fseek($fh, 1);
	$remaining = $size - 2;
	$started = false;
	while ($remaining > 0 && !feof($fh)) {
		$take = min(1048576, $remaining);
		$chunk = fread($fh, $take);
		if ($chunk === false || $chunk === '') break;
		if (!$started) {
			$chunk = ltrim($chunk);
			if ($chunk === '') {
				$remaining -= $take;
				continue;
			}
			if (!$first) echo ',';
			$started = true;
			$first = false;
		}
		$remaining -= strlen($chunk);
		echo $chunk;
	}
	fclose($fh);
}

function spandaman_api_stream_json_arrays($paths, $extraRows = array()) {
	header('Content-Type: application/json');
	while (ob_get_level() > 0) {
		@ob_end_clean();
	}
	echo '[';
	$first = true;
	foreach ($paths as $path) {
		spandaman_api_stream_json_array_inner($path, $first);
	}
	foreach ($extraRows as $row) {
		if (!is_array($row)) continue;
		if (!$first) echo ',';
		echo json_encode($row);
		$first = false;
	}
	echo ']';
	exit();
}

function spandaman_api_playable_ids($kind) {
	$ids = array();
	$paths = array(__DIR__ . '/spandaman_playable_tmdb_cache.json', __DIR__ . '/channels/spandaman_playable_tmdb_cache.json');
	foreach ($paths as $path) {
		if (!is_file($path)) continue;
		$cache = json_decode(file_get_contents($path), true);
		if (!is_array($cache)) continue;
		foreach ($cache as $key => $entry) {
			if (!is_array($entry)) continue;
			if (($entry['kind'] ?? '') !== $kind) continue;
			$id = preg_replace('/_tmdb_url$/', '', (string)$key);
			if (ctype_digit($id) && !empty($entry['url'])) {
				$ids[$id] = true;
			}
		}
		if (!empty($ids)) break;
	}
	return $ids;
}

function spandaman_api_verified_adult_ids() {
	$ids = array();
	if (!is_file(__DIR__ . '/spandaman_allow_verified_adult_playlist.flag')) {
		return $ids;
	}
	$paths = array(__DIR__ . '/spandaman_verified_adult_ids.json', __DIR__ . '/channels/spandaman_verified_adult_ids.json');
	foreach ($paths as $path) {
		if (!is_file($path)) continue;
		$data = json_decode(file_get_contents($path), true);
		if (!is_array($data)) continue;
		$rows = $data['ids'] ?? $data;
		if (!is_array($rows)) continue;
		foreach ($rows as $id) {
			$id = (string)$id;
			if (ctype_digit($id)) {
				$ids[$id] = true;
			}
		}
		if (!empty($ids)) break;
	}
	return $ids;
}

function spandaman_api_extra_verified_series_rows() {
	$rows = spandaman_api_json_file(__DIR__ . '/spandaman_extra_verified_streams.json');
	if (empty($rows)) {
		$rows = spandaman_api_json_file(__DIR__ . '/channels/spandaman_extra_verified_streams.json');
	}
	$out = array();
	$idx = 1;
	foreach ($rows as $row) {
		if (!is_array($row)) continue;
		if (($row['kind'] ?? '') !== 'series') continue;
		if (empty($row['verified']) || empty($row['url'])) continue;
		$url = trim((string)$row['url']);
		$name = trim((string)($row['name'] ?? ('Verified Series ' . $idx)));
		$id = intval($row['id'] ?? (900000000 + $idx));
		if ($id < 900000001) {
			$id = 900000000 + $idx;
		}
		$out[] = array(
			'num' => $idx,
			'name' => $name,
			'series_id' => $id,
			'cover' => (string)($row['logo'] ?? ''),
			'plot' => '',
			'cast' => '',
			'director' => '',
			'genre' => (string)($row['group'] ?? 'Verified Series'),
			'releaseDate' => '',
			'last_modified' => time(),
			'rating' => 0,
			'rating_5based' => 0,
			'backdrop_path' => array((string)($row['logo'] ?? '')),
			'youtube_trailer' => '',
			'episode_run_time' => 0,
			'category_id' => '900000',
			'spandaman_verified_url' => $url
		);
		$idx++;
	}
	return $out;
}

function spandaman_api_extra_verified_vod_rows() {
	$rows = spandaman_api_json_file(__DIR__ . '/spandaman_extra_verified_streams.json');
	if (empty($rows)) {
		$rows = spandaman_api_json_file(__DIR__ . '/channels/spandaman_extra_verified_streams.json');
	}
	$out = array();
	$idx = 1;
	foreach ($rows as $row) {
		if (!is_array($row)) continue;
		if (($row['kind'] ?? '') !== 'vod') continue;
		if (!spandaman_api_extra_vod_ready_for_xtream($row)) continue;
		$id = intval($row['id'] ?? (890000000 + $idx));
		if ($id < 890000001 || $id >= 900000000) {
			$id = 890000000 + $idx;
		}
		$extension = spandaman_api_url_path_extension((string)$row['url']);
		if (!in_array($extension, array('mp4', 'mkv', 'avi', 'mov', 'webm', 'm4v'), true)) {
			$extension = 'mp4';
		}
		$out[] = array(
			'num' => 600000 + count($out) + 1,
			'name' => (string)($row['name'] ?? ('Verified VOD ' . $idx)),
			'stream_type' => 'movie',
			'stream_id' => $id,
			'stream_icon' => (string)($row['logo'] ?? ($row['stream_icon'] ?? '')),
			'rating' => '',
			'rating_5based' => 0,
			'category_id' => '9998',
			'container_extension' => $extension,
			'custom_sid' => '',
			'direct_source' => (string)$row['url'],
			'added' => time(),
		);
		$idx++;
	}
	return $out;
}

function spandaman_api_extra_verified_vod_info($streamId) {
	$streamId = (string)$streamId;
	foreach (spandaman_api_extra_verified_vod_rows() as $row) {
		if ((string)($row['stream_id'] ?? '') !== $streamId) {
			continue;
		}
		$name = (string)($row['name'] ?? ('Verified VOD ' . $streamId));
		$directSource = (string)($row['direct_source'] ?? '');
		$icon = (string)($row['stream_icon'] ?? '');
		return array(
			'info' => array(
				'name' => $name,
				'title' => $name,
				'movie_image' => $icon,
				'cover_big' => $icon,
				'stream_icon' => $icon,
				'tmdb_id' => intval($streamId),
				'youtube_trailer' => '',
				'genre' => 'Verified VOD',
				'director' => '',
				'plot' => $name,
				'description' => $name,
				'rating' => 0,
				'rating_5based' => 0,
				'releasedate' => '',
				'release_date' => '',
				'duration_secs' => 0,
				'duration' => '00:00:00',
				'cast' => '',
				'video' => array(),
				'audio' => array(),
				'bitrate' => 0
			),
			'movie_data' => array(
				'stream_id' => intval($streamId),
				'name' => $name,
				'title' => $name,
				'added' => intval($row['added'] ?? time()),
				'category_id' => (string)($row['category_id'] ?? '9998'),
				'stream_icon' => $icon,
				'container_extension' => (string)($row['container_extension'] ?? 'm3u8'),
				'custom_sid' => null,
				'direct_source' => $directSource
			)
		);
	}
	return null;
}

function spandaman_api_extra_verified_adult_rows() {
	$rows = spandaman_api_json_file(__DIR__ . '/spandaman_extra_verified_adult_streams.json');
	if (empty($rows)) {
		$rows = spandaman_api_json_file(__DIR__ . '/channels/spandaman_extra_verified_adult_streams.json');
	}
	$out = array();
	foreach ($rows as $row) {
		if (!is_array($row) || empty($row['url']) || empty($row['id'])) continue;
		$id = (string)$row['id'];
		if (!ctype_digit($id)) continue;
		$out[] = array(
			'num' => 500000 + count($out) + 1,
			'name' => (string)($row['name'] ?? ('Adult Verified ' . $id)),
			'stream_type' => 'movie',
			'stream_id' => intval($id),
			'stream_icon' => (string)($row['logo'] ?? ''),
			'rating' => '',
			'category_id' => '9999',
			'container_extension' => 'mp4',
			'custom_sid' => '',
			'direct_source' => (string)$row['url']
		);
	}
	return $out;
}

function spandaman_api_extra_verified_live_rows() {
	$rows = spandaman_api_extra_verified_live_source_rows();
	$categoryMap = spandaman_api_live_category_map($rows);
	$out = array();
	foreach ($rows as $row) {
		if (!is_array($row) || empty($row['url']) || empty($row['id'])) continue;
		$id = (string)$row['id'];
		if (!ctype_digit($id) || empty($row['verified'])) continue;
		$group = spandaman_api_live_group_name($row);
		$out[] = array(
			'num' => 880000000 + count($out) + 1,
			'name' => (string)($row['name'] ?? ('Verified Live ' . $id)),
			'stream_type' => 'live',
			'stream_id' => intval($id),
			'stream_icon' => (string)($row['logo'] ?? ($row['stream_icon'] ?? '')),
			'epg_channel_id' => (string)($row['tvg_id'] ?? ''),
			'added' => time(),
			'category_id' => (string)($categoryMap[$group] ?? '881000'),
			'custom_sid' => '',
			'tv_archive' => 0,
			'spandaman_source_url' => (string)$row['url'],
			'direct_source' => spandaman_api_hosted_live_route($id, 'm3u8'),
			'tv_archive_duration' => 0,
			'container_extension' => 'm3u8',
			'video_url' => spandaman_api_hosted_live_route($id, 'm3u8')
		);
	}
	return $out;
}

function spandaman_api_extra_verified_live_categories() {
	$rows = spandaman_api_extra_verified_live_source_rows();
	$categoryMap = spandaman_api_live_category_map($rows);
	$out = array();
	foreach ($categoryMap as $group => $id) {
		$out[] = array(
			'category_id' => (string)$id,
			'category_name' => (string)$group,
			'parent_id' => 0
		);
	}
	return $out;
}

function spandaman_api_extra_verified_series_info($seriesId) {
	$rows = spandaman_api_extra_verified_series_rows();
	foreach ($rows as $row) {
		if ((string)($row['series_id'] ?? '') !== (string)$seriesId) continue;
		return array(
			'seasons' => array(array(
				'air_date' => '',
				'episode_count' => 1,
				'id' => (string)$seriesId,
				'name' => 'Season 1',
				'overview' => '',
				'season_number' => 1,
				'backdrop_path' => $row['cover'] ?? '',
				'cover' => $row['cover'] ?? '',
				'cover_big' => $row['cover'] ?? ''
			)),
			'info' => $row,
			'episodes' => array(
				1 => array(array(
					'id' => intval($seriesId),
					'episode_num' => 1,
					'title' => 'S01E01 - ' . ($row['name'] ?? 'Verified Episode'),
					'container_extension' => 'm3u8',
					'custom_sid' => '',
					'added' => '',
					'season' => 1,
					'direct_source' => $row['spandaman_verified_url'] ?? '',
					'info' => array(
						'tmdb_id' => intval($seriesId),
						'name' => $row['name'] ?? 'Verified Episode',
						'cover_big' => $row['cover'] ?? '',
						'plot' => '',
						'movie_image' => $row['cover'] ?? ''
					)
				))
			)
		);
	}
	return null;
}

//Get and setup Live playlist and return json.
if (isset($_GET['action']) && $_GET['action'] == 'get_live_streams') {
	
	$playableOnly = spandaman_api_playable_only_default();
	if ($playableOnly && ($_GET['type'] ?? '') !== 'm3u' && ($_GET['type'] ?? '') !== 'm3u8') {
		header('Content-Type: application/json');
		echo json_encode(array_values(spandaman_api_extra_verified_live_rows()));
		exit();
	}

	if(shouldUpdateLiveStreams()){
		runLivePlaylistGenerate();
	}	

	if ($_GET['type'] == 'm3u' || $_GET['type'] == 'm3u8') {
		
		$m3uCreate = file_get_contents('channels/live_playlist.m3u8');
		header('Content-Type: audio/x-mpegurl');
		echo $m3uCreate;

	} else {
		header('Content-Type: application/json');
		$liveRows = spandaman_api_json_file(__DIR__ . '/channels/live_playlist.json');
		$liveRows = array_merge(spandaman_api_extra_verified_live_rows(), $liveRows);
		$liveRows = array_map('spandaman_api_normalize_live_player_row', $liveRows);
		echo json_encode(array_values($liveRows));
	}
	exit();
}	

//Setup live categories and return json.
if (isset($_GET['action']) && $_GET['action'] == 'get_live_categories') {
	
	$playableOnly = spandaman_api_playable_only_default();
	if ($playableOnly) {
		header('Content-Type: application/json');
		echo json_encode(array_values(spandaman_api_extra_verified_live_categories()));
		exit();
	}

	if(shouldUpdateLiveStreams()){
		runLivePlaylistGenerate();
	}	
	
	echo file_get_contents('channels/get_live_categories.json');
	exit();	
}	

//Get movie categories from TMDB and return json.
if (isset($_GET['action']) && $_GET['action'] == 'get_vod_categories') {	
	
    $genresUrl = "https://api.themoviedb.org/3/genre/movie/list?api_key=$apiKey&include_adult=false&language=$language";
    $fetchGenres = file_get_contents($genresUrl);
    $genresArray = json_decode($fetchGenres, true);

	$output = [
		[
			'category_id' => "999992",
			'category_name' => 'Now Playing',
			'parent_id' => 0
		],
		[
			'category_id' => "999991",
			'category_name' => 'Popular',
			'parent_id' => 0
		]
	];

	// Then append the genres from the loop
	foreach ($genresArray['genres'] as $genre) {
		$output[] = [
			'category_id' => (string) $genre['id'],
			'category_name' => $genre['name'],
			'parent_id' => 0
		];
	}
	
	if($GLOBALS['INCLUDE_ADULT_VOD']){
		$output[] = [
			'category_id' => "999993",
			'category_name' => 'XXX Adult Movies',
			'parent_id' => 0
		];
		$output[] = [
			'category_id' => "9999",
			'category_name' => 'XXX Verified Adult',
			'parent_id' => 0
		];
		
	}

	$spandamanVodFallbackCategories = [
		'999990' => 'Other Movies',
		'9998' => 'Verified VOD'
	];
	$existingVodCategoryIds = [];
	foreach ($output as $categoryRow) {
		$existingVodCategoryIds[(string)($categoryRow['category_id'] ?? '')] = true;
	}
	foreach ($spandamanVodFallbackCategories as $fallbackId => $fallbackName) {
		if (empty($existingVodCategoryIds[(string)$fallbackId])) {
			$output[] = [
				'category_id' => (string)$fallbackId,
				'category_name' => $fallbackName,
				'parent_id' => 0
			];
		}
	}

    echo json_encode($output);
    exit();
}

//Get tv categories from TMDB and return json.
if (isset($_GET['action']) && $_GET['action'] == 'get_series_categories') {
    $genresUrl = "https://api.themoviedb.org/3/genre/tv/list?api_key=$apiKey&include_adult=false&language=$language";
    $fetchGenres = file_get_contents($genresUrl);
    $genresArray = json_decode($fetchGenres, true);
	
	$output = [];
	
	// Setup a top level category for the networks. 

	$tvNetworks = [
		"Apple Tv" => 2552,
		"Discovery" => 64,
		"Disney+" => 2739,
		"HBO" => 49,
		"History" => 65,
		"Hulu" => 453,
		"Investigation" => 244,
		"Lifetime" => 34,
		"Netflix" => 213,
		"Oxygen" => 132
	];
	
		$output[] = [
		'category_id' => "88883",
		'category_name' => 'On The Air',
		'parent_id' => 0
	];
	
	$output[] = [
		'category_id' => "88882",
		'category_name' => 'Top Rated',
		'parent_id' => 0
	];
	
	$output[] = [
			'category_id' => "88881",
			'category_name' => 'Popular',
			'parent_id' => 0
		];

	foreach ($tvNetworks as $networkName => $networkId) {
		$output[] = [
			'category_id' => "99999".$networkId,
			'category_name' => $networkName,
			'parent_id' => 0
		];
	}

	// Then append the genres from the loop
	foreach ($genresArray['genres'] as $genre) {
		$output[] = [
			'category_id' => (string) $genre['id'],
			'category_name' => $genre['name'],
			'parent_id' => 0
		];
	}

	// Some locally merged/hosted series rows use fallback or movie-style genre
	// IDs that TMDB's TV genre endpoint does not advertise. XC/IBO-style apps
	// often hide streams when their category_id is missing from this list.
	$spandamanSeriesFallbackCategories = [
		'999990' => 'Other Series',
		'36' => 'History',
		'10749' => 'Romance'
	];
	$existingSeriesCategoryIds = [];
	foreach ($output as $categoryRow) {
		$existingSeriesCategoryIds[(string)($categoryRow['category_id'] ?? '')] = true;
	}
	foreach ($spandamanSeriesFallbackCategories as $fallbackId => $fallbackName) {
		if (empty($existingSeriesCategoryIds[(string)$fallbackId])) {
			$output[] = [
				'category_id' => (string)$fallbackId,
				'category_name' => $fallbackName,
				'parent_id' => 0
			];
		}
	}

    echo json_encode($output);
    exit();
}


// Send the request to the playlist.
if (isset($_GET['action']) && $_GET['action'] == 'get_vod_streams') {

	if (spandaman_api_playable_only_default()) {
		$movieIds = spandaman_api_playable_ids('movie');
		$out = array();
		foreach (spandaman_api_small_cached_rows(__DIR__ . '/spandaman_playable_vod_rows.json', __DIR__ . '/playlist.json', array('stream_id'), $movieIds) as $row) {
			$id = (string)($row['stream_id'] ?? '');
			if ($id !== '' && !empty($movieIds[$id])) {
				$out[] = spandaman_api_player_movie_row($row, false);
			}
		}
		foreach (spandaman_api_extra_verified_vod_rows() as $row) {
			$out[] = $row;
		}
		$adultIds = spandaman_api_verified_adult_ids();
		foreach (spandaman_api_json_file(__DIR__ . '/adult-movies.json') as $row) {
			$id = (string)($row['stream_id'] ?? '');
			if ($id !== '' && !empty($adultIds[$id])) {
				$out[] = spandaman_api_player_movie_row($row, true);
			}
		}
		foreach (spandaman_api_extra_verified_adult_rows() as $row) {
			$out[] = spandaman_api_player_movie_row($row, true);
		}
		header('Content-Type: application/json');
		echo json_encode(array_values($out));
		exit();
	}

	if ($GLOBALS['userCreatePlaylist']) {
		$paths = array(__DIR__ . '/playlist.json');
		if ($GLOBALS['INCLUDE_ADULT_VOD']) {
			$paths[] = __DIR__ . '/adult-movies.json';
		}
		spandaman_api_stream_json_arrays($paths, array_merge(spandaman_api_extra_verified_vod_rows(), spandaman_api_extra_verified_adult_rows()));
	}

	
	if ($GLOBALS['INCLUDE_ADULT_VOD']) {
		$localAdultContent = is_file('adult-movies.json') ? file_get_contents('adult-movies.json') : false;
		$localAdultValid = false;
		if ($localAdultContent !== false) {
			$localAdultData = json_decode($localAdultContent, true);
			$localAdultValid = (json_last_error() === JSON_ERROR_NONE && is_array($localAdultData) && count($localAdultData) > 0);
		}
		if (!$localAdultValid) {
			$jsonUrl = "https://raw.githubusercontent.com/gogetta69/public-files/main/adult-movies.json";
			$jsonContent = file_get_contents($jsonUrl);

			if ($jsonContent !== false) {
				$BasePath = rtrim($BasePath, '/');
				$jsonContent = str_replace('[[SERVER_URL]]', $BasePath, $jsonContent);

				if (file_put_contents('adult-movies.json', $jsonContent) === false) {
					echo "Failed to save the modified JSON file.";
					exit;
				}
			} else {
				echo "Failed to load the JSON file.";
				exit;
			}
		}

		
	}
	
	if (!$GLOBALS['userCreatePlaylist']) {
		$localPlaylistContent = is_file('playlist.json') ? file_get_contents('playlist.json') : false;
		$localPlaylistValid = false;
		if ($localPlaylistContent !== false) {
			$localPlaylistData = json_decode($localPlaylistContent, true);
			$localPlaylistValid = (json_last_error() === JSON_ERROR_NONE && is_array($localPlaylistData) && count($localPlaylistData) > 0);
		}
		if (!$localPlaylistValid) {
			$jsonUrl = "https://raw.githubusercontent.com/gogetta69/public-files/main/playlist.json";
			$jsonContent = file_get_contents($jsonUrl);

			if ($jsonContent !== false) {
				$BasePath = rtrim($BasePath, '/');
				$jsonContent = str_replace('[[SERVER_URL]]', $BasePath, $jsonContent);

				if (file_put_contents('playlist.json', $jsonContent) === false) {
					echo "Failed to save the modified JSON file.";
					exit;
				}
			} else {
				echo "Failed to load the JSON file.";
				exit;
			}
		}

		if (!is_file('playlist.m3u8') || filesize('playlist.m3u8') === 0) {
			$m3u8Url = "https://raw.githubusercontent.com/gogetta69/public-files/main/playlist.m3u8";
			$m3u8Content = file_get_contents($m3u8Url);
			$m3u8Content = str_replace('[[SERVER_URL]]', $BasePath, $m3u8Content);

			if (file_put_contents('playlist.m3u8', $m3u8Content) === false) {
				echo "Failed to save the modified M3U8 file.";
				exit;
			}
		}
	}

	if ($GLOBALS['INCLUDE_ADULT_VOD']) {
		$playlistJson = file_get_contents('playlist.json');
		$playlist = json_decode($playlistJson, true);

		if (json_last_error() !== JSON_ERROR_NONE) {
			echo json_encode(["error" => "JSON decoding error in playlist.json: " . json_last_error_msg()]);
			exit;
		}

		$adultJsonUrl = "adult-movies.json";
		$adultJsonContent = file_get_contents($adultJsonUrl);

		if ($adultJsonContent !== false) {
			$adultMovies = json_decode($adultJsonContent, true);

			if (json_last_error() === JSON_ERROR_NONE) {
				// Merge adult movies into the playlist
				$playlist = array_merge($playlist, $adultMovies);

				// Output the combined JSON
				header('Content-Type: application/json');
				echo json_encode($playlist);
				exit();
			} else {
				echo json_encode(["error" => "Failed to decode adult-movies.json: " . json_last_error_msg()]);
				exit();
			}
		} else {
			echo json_encode(["error" => "Failed to load adult-movies.json."]);
			exit();
		}
	}

	if ($_GET['type'] == 'm3u8' || $_GET['type'] == 'm3u') {
		header('HTTP/1.1 302 Moved Temporarily');
		header('Location: playlist.m3u8');
	} else {
		header('HTTP/1.1 302 Moved Temporarily');
		header('Location: playlist.json');
		//header('Location: adult-movies.json');
	}

	exit();
}

//Send the request to the playlist.
if (isset($_GET['action']) && $_GET['action'] == 'get_series') {

	if (spandaman_api_playable_only_default()) {
		$seriesIds = spandaman_api_playable_ids('series');
		$out = array();
		foreach (spandaman_api_small_cached_rows(__DIR__ . '/spandaman_playable_series_rows.json', __DIR__ . '/tv_playlist.json', array('series_id', 'stream_id'), $seriesIds) as $row) {
			$id = (string)($row['series_id'] ?? ($row['stream_id'] ?? ''));
			if ($id !== '') {
				$out[] = $row;
			}
		}
		$out = array_merge($out, spandaman_api_extra_verified_series_rows());
		header('Content-Type: application/json');
		echo json_encode(array_values($out));
		exit();
	}

	if (is_file(__DIR__ . '/tv_playlist.json')) {
		header('Content-Type: application/json');
		readfile(__DIR__ . '/tv_playlist.json');
		exit();
	}
	
		if(!$GLOBALS['userCreatePlaylist']){
		
		$jsonUrl = "https://raw.githubusercontent.com/gogetta69/public-files/main/tv_playlist.json";
		$jsonContent = file_get_contents($jsonUrl);

		if ($jsonContent !== false) {
			
			$BasePath = rtrim($BasePath, '/');	
			$jsonContent = str_replace('[[SERVER_URL]]', $BasePath, $jsonContent);
			
			if (file_put_contents('tv_playlist.json', $jsonContent) === false) {
				echo "Failed to save the modified JSON file.";
				exit;
			}
		} else {
			echo "Failed to load the JSON file.";
			exit;
		}		
	} 
	
	header('HTTP/1.1 302 Moved Temporarily');
	header('Location: tv_playlist.json');
	exit();
}

//Look up the movie info on TMDB and return json.
if (isset($_GET['action']) && $_GET['action'] == 'get_vod_info') {
    if (!isset($_GET['vod_id'])) {
        echo 'Missing the vod_id parameter.';
        exit();
	}
	$vodId = $_GET['vod_id'];
	$extraVodInfo = spandaman_api_extra_verified_vod_info($vodId);
	if ($extraVodInfo !== null) {
		header('Content-Type: application/json');
		echo json_encode($extraVodInfo);
		exit();
	}
	// If $vodId is greater than 10000000 the movie type is adult.
	if (intval($vodId) > 10000000) {
		getAdultInfo($vodId);
	}
    
    $infoUrl = "https://api.themoviedb.org/3/movie/{$vodId}?api_key={$apiKey}&append_to_response=credits&include_adult=false&language={$language}";
    $fetchDetails = @file_get_contents($infoUrl);
    $details = json_decode($fetchDetails, true);
 
	$output = [];
	
	$runtimeMinutes = $details['runtime'];

	// Calculate hours, minutes, and seconds
	$hours = floor($runtimeMinutes / 60);
	$minutes = $runtimeMinutes % 60;
	$seconds = 0;

	// Format the time as HH:MM:SS
	$formattedRuntime = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);	


	if (isset($details['release_date'])) {
		$dateParts = explode("-", $details['release_date']);
		$year = $dateParts[0];
	} else {
		$year = '';
	}
	
	//Try and get a trailer from TMDB, if not try Youtube.
	$ytId = getTMDBTrailer($vodId, 'movie');
	
/* 	if ($ytId == false){
	//Run Youtube trailer search.
	$ytId = getYoutubeTrailer($details['original_title'].' '.$year);
	} */
	if($ytId == false){
		$ytId = '';
	}
	
		// Ensure that 'genres' key exists and is an array
	if (isset($details['genres']) && is_array($details['genres'])) {
		// Extract the 'name' values
		$genreNames = array_map(function($genre) {
			return $genre['name'];
		}, $details['genres']);
		
		// Convert the names array to a comma-separated string
		$genresString = implode(', ', $genreNames);
	} else {
		$genresString = '';
	}
	
	$actorsString = '';

	if (isset($details['credits']['cast']) && is_array($details['credits']['cast'])) {
		$cast = $details['credits']['cast'];

		$actorNames = array_map(function($actor) {
			return (isset($actor['known_for_department']) && $actor['known_for_department'] == 'Acting' && isset($actor['name'])) ? $actor['name'] : null;
		}, $cast);

		// Remove null values from the list
		$actorNames = array_filter($actorNames);

		// Take only the first 4 actor names
		$actorNames = array_slice($actorNames, 0, 4);

		// Concatenate the names with a comma separator
		$actorsString = implode(', ', $actorNames);
	}
	
	$directors = [];

	if (isset($details['credits']['crew']) && is_array($details['credits']['crew'])) {
		$crew = $details['credits']['crew'];

		$directorNames = array_filter(array_map(function($member) {
			return (isset($member['job']) && $member['job'] == 'Director' && isset($member['name'])) ? $member['name'] : null;
		}, $crew));

		// Since we want only up to 2 directors, take the first two (if they exist)
		$directors = array_slice($directorNames, 0, 2);
	}

$directorsString = implode(', ', $directors);

$vodRouteBase = rtrim($BasePath, '/') . "/movie/base/base/" . rawurlencode($vodId);
$vodRouteExtension = "m3u8";
	
  $output = [
    "info" => [
        "name" => $details['title'] ?? $details['original_title'] ?? '',
        "title" => $details['title'] ?? $details['original_title'] ?? '',
        "movie_image" => "https://image.tmdb.org/t/p/original" . $details['poster_path'],
        "cover_big" => "https://image.tmdb.org/t/p/original" . $details['poster_path'],
        "stream_icon" => "https://image.tmdb.org/t/p/original" . $details['poster_path'],
		"tmdb_id"  => $vodId,
        "youtube_trailer" => $ytId,
        "genre" => $genresString,
        "director" => $directorsString,
        "plot" => $details['overview'],
        "description" => $details['overview'],
        "rating" => round($details['vote_average'], 1),
        "rating_5based" => round($details['vote_average'], 1) / 2,
        "releasedate" => $details['release_date'],
        "release_date" => $details['release_date'],
        "duration_secs" => $details['runtime'] * 60,
        "duration" => $formattedRuntime,
        "cast" => $actorsString,
	"video" => [],
        "audio" => [],
        "bitrate" => 0
    ],
    "movie_data" => [
        "stream_id" => intval($_GET['vod_id']),
        "name" => $details['title'] ?? $details['original_title'] ?? '',
        "title" => $details['title'] ?? $details['original_title'] ?? '',
        "added" => 1696275436,
        "category_id" => "22",
        "stream_icon" => "https://image.tmdb.org/t/p/original" . $details['poster_path'],
        "container_extension" => $vodRouteExtension,
        "custom_sid" => null,
        "direct_source" => $vodRouteBase . "." . $vodRouteExtension
    ]
];
	
	echo json_encode($output);
	exit();
}
 
//Look up the series info on TMDB and return json.
if (isset($_GET['action']) && $_GET['action'] == 'get_series_info') {
    if (!isset($_GET['series_id'])) {
        echo 'Missing the series_id parameter.';
        exit();
    }
	
		
	$vodId = $_GET['series_id'];
	$extraSeriesInfo = spandaman_api_extra_verified_series_info($vodId);
	if ($extraSeriesInfo !== null) {
		echo json_encode($extraSeriesInfo);
		exit();
	}
	// First, get the details of the series
	$infoUrl = "https://api.themoviedb.org/3/tv/{$vodId}?api_key={$apiKey}&include_adult=false&append_to_response=external_ids,credits&language={$language}";
	$fetchDetails = @file_get_contents($infoUrl);
	$details = json_decode($fetchDetails, true);
	
		$actorsString = '';

	if (isset($details['credits']['cast']) && is_array($details['credits']['cast'])) {
		$cast = $details['credits']['cast'];

		$actorNames = array_map(function($actor) {
			return (isset($actor['known_for_department']) && $actor['known_for_department'] == 'Acting' && isset($actor['name'])) ? $actor['name'] : null;
		}, $cast);

		// Remove null values from the list
		$actorNames = array_filter($actorNames);

		// Take only the first 4 actor names
		$actorNames = array_slice($actorNames, 0, 4);

		// Concatenate the names with a comma separator
		$actorsString = implode(', ', $actorNames);
	}

	// Number of seasons in the series
	$totalSeasons = $details['number_of_seasons'];

	// Array to store all the details including individual seasons
	$fullDetails = [];

	// If number of seasons is less than or equal to 20, just make one call
	if ($totalSeasons <= 20) {
		$seasons = range(1, $totalSeasons);
		$seasonsToFetch = implode(',', array_map(function ($season) {
			return "season/{$season}";
		}, $seasons));
		
		$url = "https://api.themoviedb.org/3/tv/{$vodId}?api_key={$apiKey}&append_to_response={$seasonsToFetch}";
		$fullDetails = json_decode(@file_get_contents($url), true);
	} else {
		// If more than 20, loop and fetch in batches of 20
		$batches = ceil($totalSeasons / 20);
		$fullDetails = $details;  // start with the basic series details
		
		for ($i = 0; $i < $batches; $i++) {
			$start = ($i * 20) + 1;
			$end = min($start + 19, $totalSeasons);
			$seasons = range($start, $end);
			
			$seasonsToFetch = implode(',', array_map(function ($season) {
				return "season/{$season}";
			}, $seasons));
			
			$url = "https://api.themoviedb.org/3/tv/{$vodId}?api_key={$apiKey}&append_to_response={$seasonsToFetch}";
			$batchDetails = json_decode(@file_get_contents($url), true);
			
			// Merge the seasons details with the main details array
			foreach ($seasons as $season) {
				$fullDetails["season/{$season}"] = $batchDetails["season/{$season}"];
			}
		}
	}
	 
	
	if (isset($fullDetails['first_air_date'])) {
		$dateParts = explode("-", $fullDetails['first_air_date']);
		$year = $dateParts[0];
		$date = $fullDetails['first_air_date'];
		$timestamp = strtotime($date);
		$lastAirdate = strtotime($fullDetails['last_air_date']);
	} else {
		$date = '1970-01-01';
		$year = '1970'; //Set to 1970 since its unknown.
		$timestamp = '24034884';
		$lastAirdate = '24034884';
	}
	
	//Try and get a trailer from TMDB, if not try Youtube.
	$ytId = getTMDBTrailer($vodId, 'tv');
/* 	if ($ytId == false){
		//Run Youtube trailer search.
	$ytId = getYoutubeTrailer($fullDetails['name'].' '.$year);
	} */
	if($ytId == false){
		$ytId = '';
	}
	
	// Ensure that 'genres' key exists and is an array
	if (isset($fullDetails['genres']) && is_array($fullDetails['genres'])) {
		// Extract the 'name' values
		$genreNames = array_map(function($genre) {
			return $genre['name'];
		}, $fullDetails['genres']);
		
		// Convert the names array to a comma-separated string
		$genresString = implode(', ', $genreNames);
	} else {
		$genresString = '';
	}
	
	// Construct the array
	$result = [
		"seasons" => [],
		"info" => [ 
    "name" => $fullDetails['name'],
    "cover" => "https://image.tmdb.org/t/p/original" . $fullDetails['poster_path'],
    "plot" => $fullDetails['overview'],
    "cast" => $actorsString,
    "director" => isset($fullDetails['created_by'][0]['name']) ? $fullDetails['created_by'][0]['name'] : '',
    "genre" => $genresString,
    "releaseDate" => $date,
    "last_modified" => $lastAirdate,
    "rating" => isset($fullDetails['vote_average']) ? round($fullDetails['vote_average'], 1) : 0,
    "rating_5based" => isset($fullDetails['vote_average']) ? (round($fullDetails['vote_average'], 1) / 2) : 0,
    "backdrop_path" => [
      "https://image.tmdb.org/t/p/original" . $fullDetails['backdrop_path']
    ],
    "youtube_trailer" => $ytId,
    "episode_run_time" => isset($fullDetails['episode_run_time'][0]) ? $fullDetails['episode_run_time'][0] : 0,
    "category_id" => ""
  ],
		"episodes" => []
	];
	

// Add seasons
foreach (range(1, $totalSeasons) as $seasonNumber) {
    if (isset($fullDetails["season/{$seasonNumber}"]) && is_array($fullDetails["season/{$seasonNumber}"])) {
        $seasonData = $fullDetails["season/{$seasonNumber}"];
        
        // Assuming 'episodes' is always an array, but still checking to be safe
        $episodeCount = isset($seasonData['episodes']) && is_array($seasonData['episodes']) ? count($seasonData['episodes']) : 0;

        $result["seasons"][] = [
            "air_date" => $seasonData['air_date'] ?? '',
            "episode_count" => $episodeCount,
            "id" => $seasonData['_id'] ?? '',
            "name" => "Season " . $seasonNumber,
            "overview" => $seasonData['overview'] ?? '',
            "season_number" => $seasonData['season_number'] ?? '',
            "backdrop_path" => "https://image.tmdb.org/t/p/original" . $fullDetails['backdrop_path'],
            "cover" => "https://image.tmdb.org/t/p/original" . $fullDetails['poster_path'],
            "cover_big" => "https://image.tmdb.org/t/p/original" . $fullDetails['poster_path']
        ];

        if (isset($seasonData['episodes']) && is_array($seasonData['episodes'])) {
            foreach ($seasonData['episodes'] as $episode) {			
				// Check if the episode has aired yet
				$airDate = new DateTime($episode['air_date']);
				$today = new DateTime();

				if ($airDate > $today) {
					continue; // If the episode's air date is in the future, skip it
				}		
				
								
				$episodeToken = base64_encode($details['external_ids']['imdb_id'] . ':' . $vodId . "/season/" . $seasonNumber . "/episode/" . $episode['episode_number']);
				$episodeIdForRoute = (string)$episode['id'];
				$episodeRouteMap[$episodeIdForRoute] = $episodeToken;
                $result["episodes"][$seasonNumber][] = [
                    "id" => $episode['id'],
                    "episode_num" => $episode['episode_number'],
                    "title" => "S" . str_pad($seasonNumber, 2, '0', STR_PAD_LEFT) . "E" . str_pad($episode['episode_number'], 2, '0', STR_PAD_LEFT).' - ' . $episode['name'],
					// Keep XC/IBO-facing routes clean while the resolver map preserves the TMDB episode data.
                    "container_extension" => "m3u8",
                    "custom_sid" => "",
                    "added" => "",
                    "season" => $seasonNumber,
                    "direct_source" => rtrim($BasePath, '/') . "/series/base/base/" . rawurlencode($episodeIdForRoute) . ".m3u8",
                    "info" => [
                        "tmdb_id" => $vodId,
                        "name" => $episode['name'],
                        "cover_big" => "https://image.tmdb.org/t/p/original" . (isset($episode['still_path']) && !empty($episode['still_path']) ? $episode['still_path'] : $fullDetails['backdrop_path']),
                        "plot" => $episode['overview'],
                        "movie_image" => "https://image.tmdb.org/t/p/original" . (isset($episode['still_path']) && !empty($episode['still_path']) ? $episode['still_path'] : $fullDetails['backdrop_path'])
                    ]
                ];
            }
        }
    }
}
	spandaman_api_merge_series_episode_map($episodeRouteMap ?? array());
	
	echo json_encode($result);
	exit();
}
  
//All unhandled action requests should return dummy user info. Need to change this.
//Set the url in the user info json or Smarters Pro can't locate the streams.

$scheme = parse_url($domain, PHP_URL_SCHEME);
$host = parse_url($domain, PHP_URL_HOST);
$port = parse_url($domain, PHP_URL_PORT);
if(!$scheme) {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
}
if(!$port) {
    $port = ($scheme === 'https') ? 443 : 80;
}
$httpsPort = ($scheme === 'https') ? (string)$port : '';

echo json_encode(array(
    'user_info' => array(
        'username' => 'base',
        'password' => 'base',
        'message' => '',
        'auth' => 1,
        'status' => 'Active',
        'exp_date' => '4095101905',
        'is_trial' => '0',
        'active_cons' => '0',
        'created_at' => '1684851647',
        'max_connections' => '1000',
        'allowed_output_formats' => array('m3u8', 'ts')
    ),
    'server_info' => array(
        'url' => $host,
        'port' => '80',
        'https_port' => '443',
        'server_protocol' => 'https',
        'rtmp_port' => '',
        'timezone' => 'America/New_York',
        'timestamp_now' => time(),
        'time_now' => date('Y-m-d H:i:s', time())
    )
));
exit();

function getYoutubeTrailer($keyword){
    global $yt_api_key;

    // Fetch the JSON data
    $json = @file_get_contents("https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=20&q=".urlencode($keyword)."%20AND%20intitle%3A%22Trailer&type=video&key=".$yt_api_key);

    if ($json === false) {
        // Failed to fetch data from the API
        return false;
    }

    $data = json_decode($json, true);

    // Check if 'items' key exists and is an array
    if (!isset($data['items']) || !is_array($data['items'])) {
        return false;
    }

    $videoId = null;

    // Loop through the items
    foreach ($data['items'] as $item) {
        // Check if the necessary keys exist
        if (isset($item['snippet']['title']) && isset($item['id']['videoId'])) {
            $title = $item['snippet']['title'];

            // Check if the title contains the word "Official" (case-insensitive)
            if (stripos($title, 'Official') !== false) {
                $videoId = $item['id']['videoId'];
                break;
            }
        }
    }

    // If none of the videos contains the word "Official", grab the first videoId
    if (!$videoId && isset($data['items'][0]['id']['videoId'])) {
        $videoId = $data['items'][0]['id']['videoId'];
    }

    // Return the videoId or false if not found
    return $videoId ? $videoId : false;
}
	
function getTMDBTrailer($movieId, $type) {
    global $apiKey;

    $url = "https://api.themoviedb.org/3/$type/$movieId/videos?language=en-US&site=YouTube&api_key=$apiKey";

    // Fetch and decode the JSON data
    $data = @file_get_contents($url);
    if ($data === false) {
        // Failed to fetch data from the API
        return false;
    }

    $jsonData = json_decode($data, true);

    // Check if 'results' key exists
    if (!isset($jsonData['results']) || !is_array($jsonData['results'])) {
        return false;
    }

    // Filter for trailers
    $trailers = array_filter($jsonData['results'], function($video) {
        return isset($video['type']) && $video['type'] == 'Trailer';
    });

    if (empty($trailers)) {
        return false;
    }

    // Look for an official trailer
    foreach ($trailers as $trailer) {
        if (isset($trailer['official']) && $trailer['official'] == true) {
            return $trailer['key'];
        }
    }

    // If none are official, return the key of the first trailer
    return reset($trailers)['key'];  // Use reset to get the first element without relying on indexes
}

function shouldUpdateLiveStreams()
{
    $lastUpdatedFile = "channels/last_updated_channels.txt";
    $liveJsonFile = "channels/live_playlist.json";
    $liveM3uFile = "channels/live_playlist.m3u8";

    if (isset($_GET['refresh_live']) && $_GET['refresh_live'] == '1') {
        return true;
    }

    if (!file_exists($liveJsonFile) || filesize($liveJsonFile) < 100 || !file_exists($liveM3uFile) || filesize($liveM3uFile) < 100) {
        return true;
    }
	
	if (!file_exists($lastUpdatedFile)) {
		
		file_put_contents($lastUpdatedFile, (string)time());
        return false;
	}
   
    if (file_exists($lastUpdatedFile)) {
        $lastUpdatedContent = file_get_contents($lastUpdatedFile);
        $lastUpdatedTimestamp = (int)$lastUpdatedContent;
        $currentTime = time();
        $timeDifference = $currentTime - $lastUpdatedTimestamp;   

        if ($timeDifference > 21600) {
            return true;
        }
    }
    
    return false; 
}

function getAdultInfo($vodId){
    // Read the contents of the JSON file
    $fetchDetails = @file_get_contents('adult-movies.json');
    $movies = json_decode($fetchDetails, true);

	$index = array_search($vodId, array_column($movies, 'stream_id'));

    // Check if the calculated index is within bounds
    if (!isset($movies[$index])) {
        echo json_encode(["error" => "Movie not found"]);
        exit();
    }
  
    $details = $movies[$index];

    // Prepare the output
    $output = [
        "info" => [
            "name" => $details['name'] ?? '',
            "title" => $details['name'] ?? '',
            "movie_image" => $details['stream_icon'],
            "cover_big" => $details['stream_icon'],
            "stream_icon" => $details['stream_icon'],
            "tmdb_id"  => '',
            "youtube_trailer" => '',
            "genre" => $details['genres'],
            "director" => $details['director'],
            "plot" => $details['plot'],
            "description" => $details['plot'],
            "rating" => $details['rating'] ?? 0,
            "rating_5based" => isset($details['rating']) ? floatval($details['rating']) / 2 : 0,
            "releasedate" => $details['release_date'] ?? '',
            "release_date" => $details['release_date'] ?? '',
            "duration_secs" => $details['duration_secs'] ?? 0,
            "duration" => $details['duration'] ?? '00:00:00',
            "cast" => $details['cast'],
            "video" => [],
            "audio" => [],
            "bitrate" => 0
        ],
        "movie_data" => [
            "stream_id" => intval($vodId),
            "name" => $details['name'],
            "title" => $details['name'],
            "added" => $details['added'],
            "category_id" => $details['category_id'],
            "stream_icon" => $details['stream_icon'],
            "container_extension" => $details['container_extension'],
            "custom_sid" => $details['custom_sid'],
            "direct_source" => $details['direct_source']
        ]
    ];
	
    // Output the JSON
    echo json_encode($output);
    exit();
}

?>
