<?php
require_once '../include/global.php';
date_default_timezone_set("PRC");
header("Content-Type:application/json;chartset=uft-8");
$id =isset($_GET['ch'])? $_GET['ch'] :(isset($_GET['id'])? $_GET['id'] : ''); 
$url_date =isset($_GET['date'])? $_GET['date'] :(isset($_GET['date'])? $_GET['date'] : ''); 
if(empty($id)){
   epgJsonOut(500,"频道名参数空!");
}else{
  $id=strtolower($id);
  $id=preg_replace('/\s+/', '', " $id ");
}
$id=str_replace("-", "", $id);
if(stripos($id, "cctv")!==false && stripos($id, "中数")===false){
  $id=getCCTVepgId($id); 
}
//获取CCTV epgid
function getCCTVepgId($string){
	if(strcasecmp($string, 'CCTV4欧洲') === 0 || strcasecmp($string, 'cctv4euo') === 0){
    return 'cctv4euo';
  }
  if(strcasecmp($string, 'CCTV4美洲') === 0|strcasecmp($string, 'cctv4ame') === 0){
    return 'cctv4ame';
  }
	$pattern = "/CCTV.*?\d+/i";
	if (preg_match($pattern, $string, $matches)) {  
		$retStr= $matches[0];
		//echo $retStr; exit;
		if(strpos($string,"+")!==false){
			$retStr.="+";
		}else if(stripos($string,"4k")!==false){
			$retStr.="k";
		}
		return $retStr;  
	} else {	 
		return false;  
	}
}

$directory = ''; // 把缓存目录设置为根目录

$targetFile = 'e.xml';
$e = $directory . $targetFile;

$result = Db::table('app_xml')->where('appid', 10000)->find();
$remoteFileUrl = $result['url']; 

// 如果是github的，就加上代理
if (strpos($remoteFileUrl, 'github') !== false) {
	$remoteFileUrl = $proxy . $remoteFileUrl;
}
	
$xmlFiles = glob($directory . '*.xml');

if (empty($xmlFiles) || (filemtime($xmlFiles[0]) < strtotime('today'))) {
    $fileContent = file_get_contents($remoteFileUrl);
    if ($fileContent !== false) {
		// 判断下载的文件是不是gz格式，是的话就先解压
        if (substr($remoteFileUrl, -3) === '.gz') {
            $gzFilePath = $directory . $targetFile . '.gz';
            file_put_contents($gzFilePath, $fileContent);
            
            $xmlContent = gzdecode(file_get_contents($gzFilePath));
            if ($xmlContent !== false) {
                file_put_contents($directory . $targetFile, $xmlContent);
                unlink($gzFilePath);
            } else {
                epgJsonOut(500, "解压失败");
            }
        } else {
            // 如果远程文件不是GZ格式，直接保存
            file_put_contents($directory . $targetFile, $fileContent);
        }
    } else {
        epgJsonOut(500, "下载远程文件失败");
    }
}

if (!empty($id))  { 
 $idMappingContent = file_get_contents('EPG_LOGO_CH.txt');
 $idMappings = [];
 $lines = explode("\n", $idMappingContent);
 foreach ($lines as $line) {
     $mapping = explode('#', $line, 2);
     if (count($mapping) == 2) {
         $channelId = trim($mapping[0]);
         $idsForChannel = array_map('trim', explode(',', $mapping[1]));
         if(!empty($idsForChannel)){
            $idsForChannel = array_map(function($item) {
              $item=trim(strtolower($item));
              return preg_replace('/\s+/', '', " $item ");
            }, $idsForChannel);
          }          
         $idMappings[$channelId] = $idsForChannel;
     }
 }
 $found = false; 

 foreach ($idMappings as $channelId => $mappedIds) {
     if (strcasecmp($id, $channelId) === 0 || in_array($id, $mappedIds)) {   
         $id = $channelId;
         $found = true; 
         break; 
     }
 }
 if (!$found) { 
  epgJsonOut(500,"频道不存在!",$id);     
 }

 if (file_exists($e)) { 
    $xml = simplexml_load_file($e);
    $xml = json_encode($xml);
    $xml = json_decode($xml, true);
    $arr = $channel = $epgdata = $result = array();
    $today = date('Ymd'); // 获取今天的日期，格式为YYYYMMDD
    
    foreach($xml['channel'] as $row) {
        $channel['data'][] = array('id' => $row['@attributes']['id'], 'name' => $row['display-name']);        
    }
    
    foreach($channel['data'] as $key => $value) {
        if ($value['name'] == $id) { 
            array_push($result, $value);
        }         
    }
    
    foreach($xml['programme'] as $row) {
        // 提取start日期部分，前8个字符表示YYYYMMDD
        $start_date = substr($row['@attributes']['start'], 0, 8);
        if ($start_date == $today) {            
            $epgdata[] = array('id' => $row['@attributes']['channel'], "start" => $row['@attributes']['start'], 'title' => $row['title'],"stop" => $row['@attributes']['stop'], "desc" => isset($row['@attributes']['desc'])?$row['@attributes']['desc']:'');
        }
    }
    
    if (!empty($epgdata) && !empty($result)) {      
      $name=$result[0]['name'];
      $tvid=$result[0]['id'];
      $date=date('Y-m-d');       
      $data=array();
      foreach($epgdata as $row) {
        if ($row['id'] == $result[0]['id']) {
          $start= preg_replace('{^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(.*?)$}u', '$4:$5', $row["start"]);
          $end=preg_replace('{^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(.*?)$}u', '$4:$5', $row["stop"]);           
          if($start != $end){
             $data[] = array(
                "start" => $start,
                "desc" => $row['desc'],
                "end" => $end,
                "title" => $row['title']
            );
          }
        }
      }
      if(empty($data)){
        epgJsonOut(500,'epg_data为空!',$name); 
      }
      epgJsonOut(200,'请求成功',$name,$tvid,$date,$data);        
    }else{
      if(empty($result)){
         epgJsonOut(500,"result空!");
      }else if(empty($epgdata)){
         epgJsonOut(500,"epgdata空!");
      }     
    }
}
  epgJsonOut(500,"请求失败!");
} else {
  epgJsonOut(500,"频道名参数空!");  
}
//统一输出接口
function epgJsonOut($code,$msg,$name=null,$tvid=null,$date=null,$data=null){
  $out_data = ["code" => $code, "msg" => $msg, "name" => $name,"tvid" =>$tvid , "date" => $date, "epg_data" => $data];
  if (empty($out_data['name'])){
    unset($out_data['name']);
  }
  if (empty($out_data['tvid'])){
    unset($out_data['tvid']);
  }
  if (empty($out_data['date'])){
    unset($out_data['date']);
  }
  if (empty($out_data['epg_data'])){
    unset($out_data['epg_data']);
  }
  echo json_encode($out_data, JSON_UNESCAPED_UNICODE);
  exit;
}
?>
