<?php
if(!isset($_GET["epg_refresh"])) $_GET["epg_refresh"]="1";
session_start();
date_default_timezone_set("America/Santiago");

$dns  = $_SESSION["dns"]  ?? "http://puntoz.live:2082";
$user = $_SESSION["user"] ?? "admintoc";
$pass = $_SESSION["pass"] ?? "pyk12345";

function api_xtream($dns,$user,$pass,$action,$extra=""){
    $url = rtrim($dns,"/")."/player_api.php?username=".urlencode($user)."&password=".urlencode($pass)."&action=".$action.$extra;
    $json = @file_get_contents($url);
    $data = json_decode($json,true);
    return is_array($data) ? $data : [];
}


function epg_titles($dns,$user,$pass,$sid){
    if(!$sid) return ["No information","No information","","","",""];

    $e = api_xtream($dns,$user,$pass,"get_short_epg","&stream_id=".$sid."&limit=6");
    $list = $e["epg_listings"] ?? $e["epg_list"] ?? [];

    if(!$list || !is_array($list)) return ["No information","No information","","","",""];

    $nowTs = time();
    $actual = $list[0] ?? [];
    $siguiente = $list[1] ?? [];

    foreach($list as $i=>$it){
        $st = intval($it["start_timestamp"] ?? 0);
        $en = intval($it["stop_timestamp"] ?? $it["end_timestamp"] ?? 0);

        if($st > 0 && $en > $st && $nowTs >= $st && $nowTs < $en){
            $actual = $it;
            $siguiente = $list[$i+1] ?? [];
            break;
        }
    }

    $decode = function($v){
        $v = trim((string)$v);
        if($v === "") return "No information";

        $d = base64_decode($v,true);
        if($d !== false && trim($d) !== "") return trim($d);

        return $v;
    };

    $nowTitle = $epgNow ?? "Sin información";
    $nextTitle = $epgNext ?? "Sin información";

    $nowStart = (string)intval($actual["start_timestamp"] ?? 0);
    $nowEnd = (string)intval($actual["stop_timestamp"] ?? $actual["end_timestamp"] ?? 0);

    $nextStart = (string)intval($siguiente["start_timestamp"] ?? 0);
    $nextEnd = (string)intval($siguiente["stop_timestamp"] ?? $siguiente["end_timestamp"] ?? 0);

    $thirdTitle = $decode($list[2]["title"] ?? "No information");
$fourthTitle = $decode($list[3]["title"] ?? "No information");
return [$nowTitle,$nextTitle,$nowStart,$nowEnd,$nextStart,$nextEnd,$thirdTitle,$fourthTitle];
}


function epg_grid_titles($dns,$user,$pass,$sid){
    $r = epg_titles($dns,$user,$pass,$sid);
    return [
        $r[0] ?? "No information",
        $r[1] ?? "No information",
        $r[6] ?? "No information",
        $r[7] ?? "No information"
    ];
}


function epg_programs_36h($dns,$user,$pass,$sid){
    if(!$sid) return [];
    $e = api_xtream($dns,$user,$pass,"get_short_epg","&stream_id=".$sid."&limit=160");
    $list = $e["epg_listings"] ?? $e["epg_list"] ?? [];
    if(!$list || !is_array($list)) return [];

    $decode = function($v){
        $v = trim((string)$v);
        if($v === "") return "Sin información";
        $d = base64_decode($v,true);
        if($d !== false && trim($d)!=="") return trim($d);
        return $v;
    };

    $now = time();
    $max = $now + 36*3600;
    $out = [];

    foreach($list as $it){
        $st = intval($it["start_timestamp"] ?? 0);
        $en = intval($it["stop_timestamp"] ?? $it["end_timestamp"] ?? 0);
        if($st<=0 || $en<=$st) continue;
        if($en<$now || $st>$max) continue;
        $out[] = [
            "title"=>$decode($it["title"] ?? "Sin información"),
            "start"=>$st,
            "end"=>$en
        ];
    }
    return $out;
}

function pz_hora36($ts){
    return $ts>0 ? date("H:i",$ts) : "";
}


if(isset($_GET["ajax_epg"]) && $_GET["ajax_epg"] === "1"){
    header("Content-Type: application/json; charset=utf-8");

    $sid = $_GET["stream_id"] ?? "";
    $programs = epg_programs_36h($dns,$user,$pass,$sid);

    $out = [
        "now"=>"Programacion en Actualizacion",
        "next"=>"Programacion en Actualizacion",
        "start"=>0,
        "end"=>0,
        "next_start"=>0,
        "next_end"=>0
    ];

    if($programs && is_array($programs)){
        $now = time();
        $idx = 0;

        foreach($programs as $i=>$pr){
            if($now >= intval($pr["start"]) && $now < intval($pr["end"])){
                $idx = $i;
                break;
            }
        }

        $a = $programs[$idx] ?? [];
        $n = $programs[$idx + 1] ?? [];

        $out["now"] = $a["title"] ?? $out["now"];
        $out["start"] = intval($a["start"] ?? 0);
        $out["end"] = intval($a["end"] ?? 0);

        $out["next"] = $n["title"] ?? $out["next"];
        $out["next_start"] = intval($n["start"] ?? 0);
        $out["next_end"] = intval($n["end"] ?? 0);
    }

    echo json_encode($out, JSON_UNESCAPED_UNICODE);
    exit;
}

$cats = api_xtream($dns,$user,$pass,"get_live_categories");
$cat  = $_GET["cat"] ?? "";
$stream = $_GET["stream"] ?? "";

if(!$cat && count($cats)){
    $cat = $cats[0]["category_id"] ?? "";
}

$channels = api_xtream($dns,$user,$pass,"get_live_streams", $cat ? "&category_id=".urlencode($cat) : "");

$selected = null;
foreach($channels as $c){
    if((string)($c["stream_id"] ?? "") === (string)$stream){
        $selected = $c;
        break;
    }
}
if(!$selected && count($channels)){
    $selected = $channels[0];
    $stream = $selected["stream_id"] ?? "";
}

$keepEpg = isset($_GET["epg_refresh"]) ? "&epg_refresh=".urlencode($_GET["epg_refresh"]) : "";

$playUrl = $selected ? rtrim($dns,"/")."/live/".$user."/".$pass."/".$selected["stream_id"].".m3u8" : "";

$epgNow = "Sin información";
$epgNext = "Sin información";
$topStartTs = 0;
$topEndTs = 0;
$topNextStartTs = 0;
$topNextEndTs = 0;

if($selected){
    $epg = api_xtream(
        $dns,
        $user,
        $pass,
        "get_short_epg",
        "&stream_id=".$selected["stream_id"]."&limit=6"
    );

    $topList = $epg["epg_listings"] ?? $epg["epg_list"] ?? [];

    $decodeTop = function($v){
        $v = trim((string)$v);
        $d = base64_decode($v, true);
        return ($d !== false && trim($d) !== "") ? trim($d) : $v;
    };

    $getTsTop = function($it, $keys){
        foreach($keys as $k){
            if(isset($it[$k]) && $it[$k] !== ""){
                if(is_numeric($it[$k])) return intval($it[$k]);
                $t = strtotime($it[$k]);
                if($t) return intval($t);
            }
        }
        return 0;
    };

    if(!empty($topList[0])){
        $epgNow = $decodeTop($topList[0]["title"] ?? "Sin información");
        $topStartTs = $getTsTop($topList[0], ["start_timestamp","start","start_time"]);
        $topEndTs = $getTsTop($topList[0], ["stop_timestamp","end_timestamp","end","stop","end_time"]);
