<?php
session_start();
$config=json_decode(file_get_contents(__DIR__."/config.json"),true);

$dns=rtrim($_SESSION["xc_dns"] ?? ($config["dns"] ?? "")," /");
$user=$_SESSION["xc_user"] ?? ($config["xtream"]["username"] ?? "");
$pass=$_SESSION["xc_pass"] ?? ($config["xtream"]["password"] ?? "");

if(!$dns||!$user||!$pass){ header("Location: login.php"); exit; }

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

function hora_chile_epg($x){
    if(!$x) return "";
    $ts=strtotime($x." UTC");
    if(!$ts) $ts=strtotime($x);
    if(!$ts) return $x;
    $ts=$ts-(3*3600);
    return date("Y-m-d H:i", $ts);
}

function dec($x){
    $d=base64_decode($x,true);
    return $d ?: $x;
}
function epg($dns,$user,$pass,$id,$limit=4){
    $cache=__DIR__."/cache/epg/epg_".$id.".json";
    if(file_exists($cache) && time()-filemtime($cache)<600){
        $d=json_decode(file_get_contents($cache),true);
        return $d ?: [];
    }

    $url=$dns."/player_api.php?username=".urlencode($user)."&password=".urlencode($pass)."&action=get_short_epg&stream_id=".$id."&limit=".$limit;

    $ctx=stream_context_create([
        "http"=>[
            "timeout"=>2,
            "header"=>"User-Agent: Mozilla/5.0
Accept: */*
"
        ]
    ]);

    $json=@file_get_contents($url,false,$ctx);
    $data=json_decode($json,true);
    $list=$data["epg_listings"] ?? [];

    if(is_array($list)){
        file_put_contents($cache,json_encode($list,JSON_UNESCAPED_UNICODE));
        return $list;
    }

    return [];
}


function api_cached_tv($dns,$user,$pass,$action,$extra=""){
  @mkdir(__DIR__."/cache/manual",0775,true);
  @mkdir(__DIR__."/cache/manual/epg",0775,true);

  $key=md5($action."|".$extra);
  $is_epg = ($action==="get_short_epg");

  if($is_epg && preg_match('/stream_id=([0-9]+)/',$extra,$m)){
    $file=__DIR__."/cache/manual/epg/".$m[1].".json";
  } else {
    $file=__DIR__."/cache/manual/".$key.".json";
  }

  // EPG: nunca descargar al entrar. Solo leer si ya existe.
  if($is_epg){
    if(file_exists($file)){
      $d=json_decode(file_get_contents($file),true);
      return is_array($d)?$d:[];
    }
    return [];
  }

  // Listas/categorías: usar cache. Si no existe, descargar una vez.
  if(file_exists($file)){
    $d=json_decode(file_get_contents($file),true);
    if(is_array($d)) return $d;
  }

  $url=$dns."/player_api.php?username=".urlencode($user)."&password=".urlencode($pass)."&action=".$action.$extra;
  $ctx=stream_context_create(["http"=>["timeout"=>15,"header"=>"User-Agent: Mozilla/5.0\r\n"]]);
  $json=@file_get_contents($url,false,$ctx);
  $d=json_decode($json,true);
  if(!is_array($d)) $d=[];
  file_put_contents($file,json_encode($d,JSON_UNESCAPED_UNICODE));
  return $d;
}


$cat=$_GET["cat"] ?? "";
$stream=$_GET["stream"] ?? "";

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

if(!$stream && count($channels)>0) $stream=$channels[0]["stream_id"];

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

$selEpg = (isset($_GET["apk_tv"]) || !$selected) ? [] : epg($dns,$user,$pass,$selected["stream_id"],8);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PUNTOZ TV</title>
<style>
