<?php
error_reporting(0);

//All paras sanoj//

$mDNS;

urlparasing();


function urlparasing(){
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    $uri = $_SERVER['REQUEST_URI'];
    $currentUrl = "$protocol://$host$uri";
    $parsedUrl = parse_url($currentUrl);
    if (isset($parsedUrl['query'])) {
        parse_str($parsedUrl['query'], $queryParameters);
        if (isset($queryParameters['msi'])) {
       		$msiValue = $queryParameters['msi'];
            $movies_latestValue = $queryParameters['movieslatest'];
        	$series_latestValue = $queryParameters['serieslatest'];
       		$tab1_Value = $queryParameters['tabo'];
        	$tab2_Value = $queryParameters['tabt'];
       		$tab3_Value = $queryParameters['tabtr'];
        	$tab4_Value = $queryParameters['tabf'];
        	$tab5_Value = $queryParameters['tabfv'];
        	$tab6_Value = $queryParameters['tabsix'];
            $mDNS =  $msiValue;

            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                $originalText = file_get_contents('php://input');
                $oldText = "json=";
                $newText = "";
                $f_data = str_replace($oldText, $newText, $originalText);
                $decodedData = urldecode($f_data);
                $decoded_data = json_decode($decodedData, true);
            
                if ($decoded_data !== null) {
                    
                    $code = $decoded_data['code'];
                    $user = $decoded_data['user'];
                    $pass = $decoded_data['pass'];
                    $mac = $decoded_data['mac'];
                    $sn = $decoded_data['sn'];
                    $model = $decoded_data['model'];
                    $group = $decoded_data['group'];
                    $token = $decoded_data['token'];
                    $mode = $decoded_data['mode'];
                    $catid = $decoded_data['catid'];
                    $movie_id = $decoded_data['movie_id'];
                    $series_id = $decoded_data['series_id'];
                    $search  = $decoded_data['search'];


                    if($mode == "login"){
                        logincall($mDNS,$user,$pass);
                    }elseif($mode == "channels"){
                        get_live($mDNS,$user,$pass);
                    }elseif($mode == "packages"){
                        get_live_cat($mDNS,$user,$pass);
                    }elseif($mode == "movies_cat"){
                        get_movies_cat($mDNS,$user,$pass);
                    }elseif($mode == "movies_list"){
                        get_movies_list($mDNS,$user,$pass,$catid);
                    }elseif($mode == "movies_info"){
                        get_movies_info($mDNS,$user,$pass,$movie_id);
                    }elseif($mode == "movies_latest"){  
                        get_movies_latest($mDNS,$user,$pass,$movies_latestValue);
                    }elseif($mode == "series_cat"){  
                        get_series_cat($mDNS,$user,$pass);
                    }elseif($mode == "series_list"){  
                        get_series_list($mDNS,$user,$pass,$catid);
                    }elseif($mode == "series_info"){  
                        get_series_info($mDNS,$user,$pass,$series_id);
                    }elseif($mode == "series_latest"){  
                        get_series_latest($mDNS,$user,$pass,$series_latestValue);
                    }elseif($mode == "search_movies"){
                        $originalText_search = $search;
                        $oldText_search = "base64:";
                        $newText_search = "";
                        $f_data_search = str_replace($oldText_search, $newText_search, $originalText_search);
                        $decodedString = base64_decode($f_data_search);
                        get_search_movies($mDNS,$user,$pass,$decodedString);
                    }elseif($mode == "search_series"){
                        $originalText_search = $search;
                        $oldText_search = "base64:";
                        $newText_search = "";
                        $f_data_search = str_replace($oldText_search, $newText_search, $originalText_search);
                        $decodedString = base64_decode($f_data_search);
                        get_search_series($mDNS,$user,$pass,$decodedString);
                    }elseif($mode == "kids"){
                        get_movies_one_cat($mDNS,$user,$pass,$tab1_Value);
                    }elseif($mode == "trends"){
                        get_movies_tow_cat($mDNS,$user,$pass,$tab2_Value);
                    }elseif($mode == "movies_netflix"){
                        get_movies_one_cat($mDNS,$user,$pass,$tab3_Value);
                    }elseif($mode == "movies_shahid"){
                        get_movies_one_cat($mDNS,$user,$pass,$tab4_Value);
                    }elseif($mode == "movies_top"){
                        get_movies_one_cat($mDNS,$user,$pass,$tab5_Value);
                    }elseif($mode == "series_top"){  
                        get_series_cat_top($mDNS,$user,$pass,$tab6_Value);
                    }
                        
                    
                } else {
               
                    echo "Error decoding JSON data";
                }
            } else {
                
                echo "Error decoding JSON data";
            }    

            //logincall($mDNS);
            
            //alloutput($mDNS);
    
        } else {
            echo "'msi' parameter not found in the URL.";
        }
    } else {
       echo "Error decoding JSON data";
    }
}


function call_api($api_link){
    $returnData = "0";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_link);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 25);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'accept: application/json, text/plain, */*',
        'Accept-Language: en-US,en;q=0.5',
        'x-application-type: WebClient',
        'x-client-version: 2.10.4',
        'Origin: https://www.googe.com',
        'user-agent: Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0',
	));
    $result = json_decode(curl_exec($ch));
    if (!empty($result)) {
        $returndata = $result;
        return ["result" => "success", "data" => $returndata];
    }
}

function call_non_api($link){
    $returnData = "0";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $link);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 25);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'accept: application/json, text/plain, */*',
        'Accept-Language: en-US,en;q=0.5',
        'x-application-type: WebClient',
        'x-client-version: 2.10.4',
        'Origin: https://www.googe.com',
        'user-agent: Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0',
	));
    $result = curl_exec($ch);
    if (!empty($result)) {
        $returndata = $result;
        return $returndata;
    }
}

function mainfkr($str) {
    try {
        $keyValue = "06A15%Uy[u53u[8";
        if ($str !== null && $keyValue !== null) {
            $charArray = str_split($keyValue);
            $charArray2 = str_split($str);
            $length = count($charArray2);
            $length2 = count($charArray);
            $cArr = [];
            
            for ($i = 0; $i < $length; $i++) {
                $cArr[$i] = chr(ord($charArray2[$i]) ^ ord($charArray[$i % $length2]));
            }
            
            return implode('', $cArr);
        }
    } catch (Exception $unused) {
    }
    
    return null;
}

function logincall($uDNS,$uUsername,$uPassowrd){
    $response_error = '{
        "status": 103,
        "server_name": "",
        "apk_ver_code": "",
        "message": "Login error: Please check username/password or maybe expired.",
        "osd_msg": "",
        "osd_msg_global": null,
        "expire": "",
        "user_agent": "",
        "username": "",
        "password": "",
        "allowed_output_formats": [],
        "max_connections": 0,
        "host": "",
        "player_api": "",
        "epg_api": "",
        "code_id": "",
        "force_update": "",
        "update_url": "",
        "apk_page": "",
        "update_ch": "",
        "timezone": "",
        "server_info": [],
        "total_streams": 0,
        "total_movies": 0,
        "total_series": 0,
        "token": ""
      }';
    $maincall = "/player_api.php?username=$uUsername&password=$uPassowrd";
    $api_link = $uDNS . $maincall;
    $api_req = call_api($api_link);
    $result = $api_req;
    if ($result["result"] == "success") {
        if (isset($result["data"]->user_info->auth)) {
            if ($result["data"]->user_info->auth != 0) {
                if ($result["data"]->user_info->status == "Active") {
                    $response = '{
                        "status": 100,
                        "server_name": "V6apk",
                        "osd_msg": "",
                        "osd_msg_global": null,
                        "message": "Login Success.",
                        "expire": "' . date("Y-m-d", $result["data"]->user_info->exp_date) . '",
                        "user_agent": "",
                        "username": "' . $result["data"]->user_info->username . '",
                        "password": "' . $result["data"]->user_info->password . '",
                        "max_connections": "' . $result["data"]->user_info->max_connections . '",
                        "allowed_output_formats": ' . json_encode($result["data"]->user_info->allowed_output_formats). ',
                        "host": "'.$uDNS.'",
                        "player_api": "'.$uDNS.'/player_api.php",
                        "epg_api": "'.$uDNS.'/xmltv.php",
                        "code_id": 0,
                        "apk_ver_code": null,
                        "force_update": 0,
                        "update_url": "http://play.google.com/?id",
                        "apk_page": "",
                        "update_ch": "true",
                        "timezone": "'. $result["data"]->server_info->timezone .'",
                        "server_info": ' . json_encode($result["data"]->server_info). ',
                        "total_streams": 0,
                        "total_movies": 0,
                        "total_series": 0,
                        "token": "'.generateRandomToken().'"
                    }';
                    alloutput($response);
                    //alloutput(json_encode($result));
                }
            } else {
                alloutput($response_error);
            }
        }
    } else {
        alloutput($response_error);
    }
}
function generateRandomToken() {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $token = '';

    for ($i = 0; $i < 90; $i++) {
        $token .= $characters[rand(0, strlen($characters) - 1)];
    }

    return $token;
}

function get_live($uDNS, $uUsername, $uPassword)
{
    $maincall = "/player_api.php?username=$uUsername&password=$uPassword&action=get_live_streams";
    $live_link = $uDNS . $maincall;
    $live_req = call_non_api($live_link);
    if ($live_req === false) {
        return json_encode(['error' => 'Unable to fetch live streams.']);
    }
    $result = json_decode($live_req, true);
    if ($result === null) {
        return json_encode(['error' => 'Invalid JSON response.']);
    }
    $outputData = [];
    foreach ($result as $item) {
        $outputData[] = [
            "id" => $item["stream_id"],
            "type" => "1",
            "stream_display_name" => $item["name"],
            "category_id" => $item["category_id"],
            "catid" => $item["category_id"],
            "stream_icon" => $item["stream_icon"],
            "view_order" => $item["num"],
            "tv_archive" => $item["tv_archive"],
            "has_epg" => 1,
            "stream_url" => "$uDNS/$uUsername/$uPassword/" . $item["stream_id"]
        ];
    }
    $outputJson = json_encode($outputData);
    echo alloutput($outputJson);
}



function get_live_cat($uDNS, $uUsername, $uPassword)
{
    $maincall = "/player_api.php?username=$uUsername&password=$uPassword&action=get_live_categories";
    $live_link = $uDNS . $maincall;
    $live_req = call_non_api($live_link);
    if ($live_req === false) {
        return json_encode(['error' => 'Unable to fetch live streams.']);
    }
    $result = json_decode($live_req, true);
    if ($result === null) {
        return json_encode(['error' => 'Invalid JSON response.']);
    }
    $outputData = [];
    foreach ($result as $item) {
        $outputData[] = [
            "id" => $item["category_id"],
            "category_name" => $item["category_name"],
            "category_type" => 0,
            "category_icon" => "http://intro.ps/uploads/logo/movie.png",
            "view_order" => array_search($item, $result) + 1,
            "isLocked" => false,
            "ch_count" => 1,
            "parent" => $item["parent_id"]
        ];
    }
    $outputJson = json_encode($outputData);
    alloutput($outputJson);
}

function get_movies_cat($uDNS, $uUsername, $uPassword) {
    $maincall = "/player_api.php?username=$uUsername&password=$uPassword&action=get_vod_categories";
    $live_link = $uDNS . $maincall;
    $live_req = call_non_api($live_link);
    if ($live_req === false) {
        return json_encode(['error' => 'Unable to fetch live streams.']);
    }
    $result = json_decode($live_req, true);
    if ($result === null) {
        return json_encode(['error' => 'Invalid JSON response.']);
    }
    $outputData = [];

    foreach ($result as $item) {
        $outputData[] = [
            "id" => $item["category_id"],
            "category_name" => $item["category_name"],
            "category_type" => "movie",
            "category_icon" => "http://intro.ps/uploads/logo/movie.png",
            "cat_order" => array_search($item, $result) + 1, 
            "isLocked" => false, 
            "stream_count" => array_search($item, $result) + 1, 
            "parent_id" => $item["parent_id"]
        ];
    }

    $outputJson = json_encode($outputData);
    alloutput($outputJson);
    
}

function get_steam_count($uDNS, $uUsername, $uPassword,$uCatID) {
    $maincall = "/player_api.php?username=$uUsername&password=$uPassword&action=get_vod_streams&category_id=$uCatID";
    $live_link = $uDNS . $maincall;
    $live_req = call_non_api($live_link);
    if ($live_req === false) {
        return json_encode(['error' => 'Unable to fetch live streams.']);
    }
    $result = json_decode($live_req, true);
    if ($result === null) {
        return json_encode(['error' => 'Invalid JSON response.']);
    }

    $arrayLength = count($result);

    return $arrayLength;
    
}

function get_movies_list($uDNS, $uUsername, $uPassword,$uCatID) {
    $maincall = "/player_api.php?username=$uUsername&password=$uPassword&action=get_vod_streams&category_id=$uCatID";
    $live_link = $uDNS . $maincall;
    $live_req = call_non_api($live_link);
    if ($live_req === false) {
        return json_encode(['error' => 'Unable to fetch live streams.']);
    }
    $result = json_decode($live_req, true);
    if ($result === null) {
        return json_encode(['error' => 'Invalid JSON response.']);
    }
    $outputData = [];

    foreach ($result as $item) {
        // Asegurar que siempre haya un backdrop, usando el stream_icon si no está disponible
        $backdrop = !empty($item["stream_icon"]) ? $item["stream_icon"] : "http://intro.ps/uploads/logo/movie.png";
        
        $outputData[] = [
            "id" => $item["stream_id"],
            "stream_display_name" => $item["name"],
            "trailer" => "10203040",
            "category_id" => $item["category_id"],
            "stream_icon" => !empty($item["stream_icon"]) ? $item["stream_icon"] : "http://intro.ps/uploads/logo/movie.png",
            "backdrop" => $backdrop,
            "view_order" => $item["num"],
            "views" => 0,
            "plot" => $item["name"],
            "rating" => (string)$item["rating"],
            "genre" => $item["stream_type"],
            "cast" => $item["stream_type"],
            "year" => date("Y", $item["added"]),
            "added" => $item["added"],
            "stream_url" => "$uDNS/movie/$uUsername/$uPassword/{$item['stream_id']}.{$item['container_extension']}"
        ];
    }
    $outputJson = json_encode($outputData);
    alloutput($outputJson);
}

function get_movies_latest($uDNS, $uUsername, $uPassword,$uCatID) {
    $maincall = "/player_api.php?username=$uUsername&password=$uPassword&action=get_vod_streams&category_id=$uCatID";
    $live_link = $uDNS . $maincall;
    $live_req = call_non_api($live_link);
    if ($live_req === false) {
        return json_encode(['error' => 'Unable to fetch live streams.']);
    }
    $result = json_decode($live_req, true);
    if ($result === null) {
        return json_encode(['error' => 'Invalid JSON response.']);
    }
    $outputData = [];

    foreach ($result as $item) {
        // Asegurar que siempre haya un backdrop
        $backdrop = !empty($item["stream_icon"]) ? $item["stream_icon"] : "http://intro.ps/uploads/logo/movie.png";
        
        $outputData[] = [
            "id" => $item["stream_id"],
            "stream_display_name" => $item["name"],
            "trailer" => "",
            "category_id" => $item["category_id"],
            "stream_icon" => !empty($item["stream_icon"]) ? $item["stream_icon"] : "http://intro.ps/uploads/logo/movie.png",
            "backdrop" => $backdrop,
            "view_order" => $item["num"],
            "views" => 0,
            "plot" => "",
            "rating" => (string)$item["rating"],
            "genre" => "",
            "cast" => "",
            "year" => date("Y", $item["added"]),
            "added" => $item["added"],
            "stream_url" => "$uDNS/movie/$uUsername/$uPassword/{$item['stream_id']}.{$item['container_extension']}"
        ];
    }
    $outputJson = json_encode($outputData);
    alloutput($outputJson);
}

function get_movies_info($uDNS, $uUsername, $uPassword,$uStreamID) {
    $maincall = "/player_api.php?username=$uUsername&password=$uPassword&action=get_vod_info&vod_id=$uStreamID";
    $live_link = $uDNS . $maincall;
    $live_req = call_non_api($live_link);
    if ($live_req === false) {
        return json_encode(['error' => 'Unable to fetch live streams.']);
    }
    $result = json_decode($live_req, true);
    if ($result === null) {
        return json_encode(['error' => 'Invalid JSON response.']);
    }
    
    $data = $result;

    // Asegurar que siempre haya una imagen de fondo
    $backdrop = !empty($data["info"]["backdrop_path"]) ? $data["info"]["backdrop_path"] : 
                (!empty($data["info"]["cover_big"]) ? $data["info"]["cover_big"] : 
                "http://intro.ps/uploads/logo/movie.png");

    // Extract relevant information
    $outputData = [
        [
            "id" => $data["movie_data"]["category_id"],
            "title" => $data["info"]["name"],
            "trailer" => $data["info"]["youtube_trailer"] ?? "",
            "catid" => $data["movie_data"]["category_id"],
            "icon" => !empty($data["info"]["cover_big"]) ? $data["info"]["cover_big"] : "http://intro.ps/uploads/logo/movie.png",
            "backdrop" => $backdrop,
            "stream" => "$uDNS/movie/$uUsername/$uPassword/" . $data["movie_data"]["stream_id"] . "." . $data["movie_data"]["container_extension"],
            "stream_url" => [
                "480p" => "",
                "720p" => "$uDNS/movie/$uUsername/$uPassword/" . $data["movie_data"]["stream_id"] . "." . $data["movie_data"]["container_extension"],
                "1080p" => "",
                "4k" => ""
            ],
            "subtitle" => "https://dl.opensubtitles.org/en/download/sub/9814116",
            "genre" => $data["info"]["genre"] ?? "",
            "MPAA" => $data["info"]["mpaa_rating"] ?? "",
            "release_date" => $data["info"]["releasedate"] ?? "",
            "plot" => $data["info"]["plot"] ?? "",
            "cast" => $data["info"]["cast"] ?? "",
            "duration" => $data["info"]["duration"] ?? "",
            "rating" => (string)($data["info"]["rating"] ?? "0"),
            "director" => $data["info"]["director"] ?? "",
            "year" => isset($data["info"]["releasedate"]) ? substr($data["info"]["releasedate"], 0, 4) : "",
            "user_rating" => 0,
            "likes" => 0,
            "dislikes" => 0
        ]
    ];
    $outputJson = json_encode($outputData);
    alloutput($outputJson);
}

//////////////////////////////////////////////////////////////////////////////////

function get_series_cat($uDNS, $uUsername, $uPassword) {
    $maincall = "/player_api.php?username=$uUsername&password=$uPassword&action=get_series_categories";
    $live_link = $uDNS . $maincall;
    $live_req = call_non_api($live_link);
    if ($live_req === false) {
        return json_encode(['error' => 'Unable to fetch live streams.']);
    }
    $result = json_decode($live_req, true);
    if ($result === null) {
        return json_encode(['error' => 'Invalid JSON response.']);
    }
    $outputData = [];

    foreach ($result as $item) {
        $outputData[] = [
            "id" => $item["category_id"],
            "category_name" => $item["category_name"],
            "category_type" => "movie",
            "category_icon" => "http://intro.ps/uploads/logo/movie.png",
            "cat_order" => array_search($item, $result) + 1, 
            "isLocked" => false, 
            "stream_count" => array_search($item, $result) + 1, 
            "parent_id" => $item["parent_id"]
        ];
    }

    $outputJson = json_encode($outputData);
    alloutput($outputJson);
    
}

function get_series_list($uDNS, $uUsername, $uPassword,$uCatID) {
    $maincall = "/player_api.php?username=$uUsername&password=$uPassword&action=get_series&category_id=$uCatID";
    $live_link = $uDNS . $maincall;
    $live_req = call_non_api($live_link);
    if ($live_req === false) {
        return json_encode(['error' => 'Unable to fetch live streams.']);
    }
    $result = json_decode($live_req, true);
    if ($result === null) {
        return json_encode(['error' => 'Invalid JSON response.']);
    }
    $outputData = [];

    foreach ($result as $item) {
        // Asegurar que siempre haya una imagen de fondo para backdrop
        $backdrop = "";
        if (isset($item["backdrop_path"]) && is_array($item["backdrop_path"]) && !empty($item["backdrop_path"][0])) {
            $backdrop = $item["backdrop_path"][0];
        } else {
            $backdrop = !empty($item["cover"]) ? $item["cover"] : "http://intro.ps/uploads/logo/movie.png";
        }
        
        $outputData[] = [
            "id" => $item["series_id"],
            "title" => $item["name"],
            "icon" => !empty($item["cover"]) ? $item["cover"] : "http://intro.ps/uploads/logo/movie.png",
            "catid" => $item["category_id"],
            "icon_big" => !empty($item["cover"]) ? $item["cover"] : "http://intro.ps/uploads/logo/movie.png",
            "backdrop" => $backdrop,
            "genre" => $item["genre"] ?? "",
            "plot" => $item["plot"] ?? "",
            "cast" => $item["cast"] ?? "",
            "rating" => $item["rating"] ?? "0",
            "director" => $item["director"] ?? "",
            "releaseDate" => $item["releaseDate"] ?? "",
            "last_modified" => $item["last_modified"] ?? "",
            "view_order" => $item["num"] ?? 0,
            "views" => 0,
        ];
    }    
    $outputJson = json_encode($outputData);
    alloutput($outputJson);
}

function get_series_latest($uDNS, $uUsername, $uPassword,$uCatID) {
    $maincall = "/player_api.php?username=$uUsername&password=$uPassword&action=get_series&category_id=$uCatID";
    $live_link = $uDNS . $maincall;
    $live_req = call_non_api($live_link);
    if ($live_req === false) {
        return json_encode(['error' => 'Unable to fetch live streams.']);
    }
    $result = json_decode($live_req, true);
    if ($result === null) {
        return json_encode(['error' => 'Invalid JSON response.']);
    }
    $outputData = [];

    foreach ($result as $item) {
        // Asegurar que siempre haya una imagen de fondo para backdrop
        $backdrop = "";
        if (isset($item["backdrop_path"]) && is_array($item["backdrop_path"]) && !empty($item["backdrop_path"][0])) {
            $backdrop = $item["backdrop_path"][0];
        } else {
            $backdrop = !empty($item["cover"]) ? $item["cover"] : "http://intro.ps/uploads/logo/movie.png";
        }
          
        $outputData[] = ["id" => $item["series_id"],
            "title" => $item["name"],
            "icon" => !empty($item["cover"]) ? $item["cover"] : "http://intro.ps/uploads/logo/movie.png",
            "catid" => $item["category_id"],
            "icon_big" => !empty($item["cover"]) ? $item["cover"] : "http://intro.ps/uploads/logo/movie.png",
            "backdrop" => $backdrop,
            "genre" => $item["genre"] ?? "",
            "plot" => $item["plot"] ?? "",
            "cast" => $item["cast"] ?? "",
            "rating" => $item["rating"] ?? "0",
            "director" => $item["director"] ?? "",
            "releaseDate" => $item["releaseDate"] ?? "",
            "last_modified" => $item["last_modified"] ?? "",
            "view_order" => $item["num"] ?? 0,
            "views" => 0,
        ];
    }    
    $outputJson = json_encode($outputData);
    alloutput($outputJson);
}

function get_series_info($uDNS, $uUsername, $uPassword, $uStreamID) {
    $maincall = "/player_api.php?username=$uUsername&password=$uPassword&action=get_series_info&series_id=$uStreamID";
    $live_link = $uDNS . $maincall;
    $live_req = call_non_api($live_link);
    if ($live_req === false) {
        return json_encode(['error' => 'Unable to fetch live streams.']);
    }
    $result = json_decode($live_req, true);
    if ($result === null) {
        return json_encode(['error' => 'Invalid JSON response.']);
    }
    
    $data = $result;

    // Asegurar que siempre haya un backdrop disponible
    $backdrop = [];
    if (isset($data["info"]["backdrop_path"]) && !empty($data["info"]["backdrop_path"])) {
        // Si es un array, usarlo directamente
        if (is_array($data["info"]["backdrop_path"])) {
            $backdrop = $data["info"]["backdrop_path"];
        } 
        // Si es un string, convertirlo a array
        else {
            $backdrop = [$data["info"]["backdrop_path"]];
        }
    } 
    // Si no hay backdrop_path, usar cover como fallback
    else {
        $coverImage = !empty($data["info"]["cover"]) ? $data["info"]["cover"] : "http://intro.ps/uploads/logo/movie.png";
        $backdrop = [$coverImage];
    }

    $outputData = [
        "info" => [
            "id" => $data["info"]["category_id"] ?? 0,
            "title" => $data["info"]["name"] ?? "Unknown",
            "icon" => !empty($data["info"]["cover"]) ? $data["info"]["cover"] : "http://intro.ps/uploads/logo/movie.png",
            "catid" => $data["info"]["category_id"] ?? 0,
            "icon_big" => !empty($data["info"]["cover"]) ? $data["info"]["cover"] : "http://intro.ps/uploads/logo/movie.png",
            "backdrop" => $backdrop,
        	"genre" => !empty($data["info"]["genre"]) ? $data["info"]["genre"] : "",
            "plot" => $data["info"]["plot"] ?? "",
        	"cast" =>  !empty($data["info"]["cast"]) ? $data["info"]["cast"] : "",
            "rating" => $data["info"]["rating"] ?? "0",
            "director" => $data["info"]["director"] ?? "",
            "releaseDate" => $data["info"]["releaseDate"] ?? "",
            "last_modified" => $data["info"]["last_modified"] ?? "",
            "trailer" => !empty($data["info"]["youtube_trailer"]) ? $data["info"]["youtube_trailer"] : "",
            "likes" => 0,
            "dislikes" => 0,
        ],
        "seasons" => [],
    ];

    // Manejo de episodios
    if (isset($data["episodes"]) && is_array($data["episodes"])) {
        $groupedEpisodes = [];
        foreach ($data["episodes"] as $seasonNum => $episodes) {
            if (!is_array($episodes)) continue;
            
            foreach ($episodes as $episode) {
                if (!isset($groupedEpisodes[$seasonNum])) {
                    $groupedEpisodes[$seasonNum] = [];
                }
                
                // Asegurar que tengamos un extension para el container
                $container_extension = isset($episode["container_extension"]) ? $episode["container_extension"] : "mp4";
                
                $groupedEpisodes[$seasonNum][] = [
                    "episode_num" => $episode["episode_num"] ?? 0,
                    "episode_name" => $episode["title"] ?? "Unknown",
                    "stream_url" => "$uDNS/series/$uUsername/$uPassword/".($episode["id"] ?? 0).'.'.$container_extension,
                ];
            }
        }

        // Organizar los episodios en el formato de salida
        foreach ($groupedEpisodes as $seasonNum => $episodes) {
            $outputData["seasons"][] = [
                "season_num" => $seasonNum,
                "episodes" => $episodes,
            ];
        }
    }

    $outputJson = json_encode($outputData);
    alloutput($outputJson);
}

/////////////////////search_area///////////////////////

function get_search_movies($uDNS, $uUsername, $uPassword, $uSearch) {
    $maincall = "/player_api.php?username=$uUsername&password=$uPassword&action=get_vod_streams";
    $live_link = $uDNS . $maincall;
    $live_req = call_non_api($live_link);
    if ($live_req === false) {
        return json_encode(['error' => 'Unable to fetch live streams.']);
    }
    $result = json_decode($live_req, true);
    if ($result === null) {
        return json_encode(['error' => 'Invalid JSON response.']);
    }

    $searchTerm = $uSearch;

    $dataArray = $result;
    $results = array_filter($dataArray, function ($item) use ($searchTerm) {
        return isset($item['name']) && stripos($item['name'], $searchTerm) !== false;
    });

    $results_out = array_values($results);

    $outputData = [];

    foreach ($results_out as $item) {
        // Asegurar que siempre haya un backdrop
        $backdrop = !empty($item["stream_icon"]) ? $item["stream_icon"] : "http://intro.ps/uploads/logo/movie.png";
        
        $outputData[] = [
            "id" => $item["stream_id"],
            "stream_display_name" => $item["name"],
            "trailer" => "",
            "category_id" => $item["category_id"],
            "stream_icon" => !empty($item["stream_icon"]) ? $item["stream_icon"] : "http://intro.ps/uploads/logo/movie.png",
            "backdrop" => $backdrop,
            "view_order" => array_search($item, $results_out) + 1,
            "views" => 0,
            "plot" => "",
            "rating" => (string)($item["rating"] ?? "0"),
            "genre" => "",
            "cast" => "",
            "year" => isset($item["added"]) ? date("Y", $item["added"]) : "",
            "added" => $item["added"] ?? "",
            "stream_url" => "$uDNS/movie/$uUsername/$uPassword/{$item['stream_id']}.{$item['container_extension']}"
        ];
    }

    $outputJson = json_encode($outputData);
    alloutput($outputJson);
}

function get_search_series($uDNS, $uUsername, $uPassword, $uSearch) {
    $maincall = "/player_api.php?username=$uUsername&password=$uPassword&action=get_series";
    $live_link = $uDNS . $maincall;
    $live_req = call_non_api($live_link);
    if ($live_req === false) {
        return json_encode(['error' => 'Unable to fetch live streams.']);
    }
    $result = json_decode($live_req, true);
    if ($result === null) {
        return json_encode(['error' => 'Invalid JSON response.']);
    }

    $searchTerm = $uSearch;

    $dataArray = $result;
    $results = array_filter($dataArray, function ($item) use ($searchTerm) {
        return isset($item['name']) && stripos($item['name'], $searchTerm) !== false;
    });

    $results_out = array_values($results);

    $outputData = [];

    foreach ($results_out as $item) {
        // Asegurar que siempre haya una imagen de fondo para backdrop
        $backdrop = "";
        if (isset($item["backdrop_path"]) && is_array($item["backdrop_path"]) && !empty($item["backdrop_path"][0])) {
            $backdrop = $item["backdrop_path"][0];
        } else {
            $backdrop = !empty($item["cover"]) ? $item["cover"] : "http://intro.ps/uploads/logo/movie.png";
        }
        
        $outputData[] = [
            "id" => $item["series_id"],
            "title" => $item["name"],
            "icon" => !empty($item["cover"]) ? $item["cover"] : "http://intro.ps/uploads/logo/movie.png",
            "catid" => $item["category_id"],
            "icon_big" => !empty($item["cover"]) ? $item["cover"] : "http://intro.ps/uploads/logo/movie.png",
            "backdrop" => $backdrop,
            "genre" => $item["genre"] ?? "",
            "plot" => $item["plot"] ?? "",
            "cast" => $item["cast"] ?? "",
            "rating" => $item["rating"] ?? "0",
            "director" => $item["director"] ?? "",
            "releaseDate" => $item["releaseDate"] ?? "",
            "last_modified" => $item["last_modified"] ?? "",
            "view_order" => array_search($item, $results_out) + 1,
            "views" => 0,
        ];
    }    

    $outputJson = json_encode($outputData);
    alloutput($outputJson);
}

//////////////////////other_tab_cat///////////////////////
function get_movies_one_cat($uDNS, $uUsername, $uPassword, $uCatID) {
    $maincall = "/player_api.php?username=$uUsername&password=$uPassword&action=get_vod_categories";
    $live_link = $uDNS . $maincall;
    $live_req = call_non_api($live_link);
    if ($live_req === false) {
        return json_encode(['error' => 'Unable to fetch live streams.']);
    }
    $result = json_decode($live_req, true);
    if ($result === null) {
        return json_encode(['error' => 'Invalid JSON response.']);
    }

    $filterCategoryId = $uCatID;

    $filteredCategories = array_filter($result, function ($category) use ($filterCategoryId) {
        return isset($category['category_id']) && (string)$category['category_id'] === (string)$filterCategoryId;
    });

    $results_out = array_values($filteredCategories);

    $outputData = [];

    foreach ($results_out as $item) {
        $outputData[] = [
            "id" => $item["category_id"],
            "category_name" => $item["category_name"],
            "category_type" => "movie",
            "category_icon" => "http://intro.ps/uploads/logo/movie.png",
            "cat_order" => array_search($item, $result) + 1, 
            "isLocked" => false, 
            "stream_count" => array_search($item, $result) + 1, 
            "parent_id" => $item["parent_id"]
        ];
    }

    $outputJson = json_encode($outputData);
    alloutput($outputJson);
}

function get_series_cat_top($uDNS, $uUsername, $uPassword, $uCatID) {
    $maincall = "/player_api.php?username=$uUsername&password=$uPassword&action=get_series_categories";
    $live_link = $uDNS . $maincall;
    $live_req = call_non_api($live_link);
    if ($live_req === false) {
        return json_encode(['error' => 'Unable to fetch live streams.']);
    }
    $result = json_decode($live_req, true);
    if ($result === null) {
        return json_encode(['error' => 'Invalid JSON response.']);
    }

    $filterCategoryId = $uCatID;

    $filteredCategories = array_filter($result, function ($category) use ($filterCategoryId) {
        return isset($category['category_id']) && (string)$category['category_id'] === (string)$filterCategoryId;
    });

    $results_out = array_values($filteredCategories);

    $outputData = [];

    foreach ($results_out as $item) {
        $outputData[] = [
            "id" => $item["category_id"],
            "category_name" => $item["category_name"],
            "category_type" => "movie",
            "category_icon" => "http://intro.ps/uploads/logo/movie.png",
            "cat_order" => array_search($item, $result) + 1, 
            "isLocked" => false, 
            "stream_count" => array_search($item, $result) + 1, 
            "parent_id" => $item["parent_id"]
        ];
    }

    $outputJson = json_encode($outputData);
    alloutput($outputJson);
}

function get_movies_tow_cat($uDNS, $uUsername, $uPassword, $uCatID) {
    $maincall = "/player_api.php?username=$uUsername&password=$uPassword&action=get_vod_streams&category_id=$uCatID";
    $live_link = $uDNS . $maincall;
    $live_req = call_non_api($live_link);
    if ($live_req === false) {
        return json_encode(['error' => 'Unable to fetch live streams.']);
    }
    $result = json_decode($live_req, true);
    if ($result === null) {
        return json_encode(['error' => 'Invalid JSON response.']);
    }

    $outputData = [];

    foreach ($result as $item) {
        // Asegurar que siempre haya un backdrop
        $stream_icon = !empty($item["stream_icon"]) ? $item["stream_icon"] : "http://intro.ps/uploads/logo/movie.png";
        
        $outputData[] = [
            "id" => $item["stream_id"],
            "type" => $item["stream_type"],
            "title" => $item["name"],
            "catid" => $item["category_id"],
            "icon" => $stream_icon,
            "backdrop" => [$stream_icon], // Usamos array para evitar fallos
            "season" => 0,
            "season_id" => 0,
            "episode" => 0,
            "episode_id" => 0,
            "view_order" => "0",
            "views" => 0,
            "ratting" => 0,
            "stream" => ""
        ];
    }  
    
    $outputJson = json_encode($outputData);
    alloutput($outputJson);
}

function alloutput($output){
    echo mainfkr($output);
	//echo $output;
}

?>