<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

function fetch_url_with_curl($url, $host_override = '', $ip_override = '') {
    if(!function_exists('curl_init')) return ['content'=>false,'http_code'=>0,'error'=>'curl 없음'];
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
    curl_setopt($ch,CURLOPT_TIMEOUT,10);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,true);
    if($host_override) curl_setopt($ch,CURLOPT_HTTPHEADER,["Host: $host_override"]);
    if($ip_override){
        $scheme=parse_url($url,PHP_URL_SCHEME)?:'http';
        $port=($scheme==='https')?443:80;
        curl_setopt($ch,CURLOPT_RESOLVE,["$host_override:$port:$ip_override"]);
    }
    $content=curl_exec($ch);
    $err=curl_error($ch);
    $info=curl_getinfo($ch);
    curl_close($ch);
    if(!$content||$err) $info['http_code']=0;
    return ['content'=>$content,'http_code'=>$info['http_code']??0,'error'=>$err?:null];
}

$results=[];
if(isset($_POST['playlist_url'])){
    $playlist_url=trim($_POST['playlist_url']);
    $ip_text=trim($_POST['ip_override']??'');
    $ip_list=$ip_text===''?['']:array_filter(array_map('trim',preg_split('/[\r\n,;]+/',$ip_text)));

    $parsed=@parse_url($playlist_url);
    if(!$parsed||!isset($parsed['host'])){
        $results[]=['ip'=>'(invalid)','playlist'=>['http_code'=>0,'error'=>'URL 오류']];
    }else{
        $host=$parsed['host'];
        $scheme=$parsed['scheme']??'https';
        $path=$parsed['path']??'/';
        $base_path=rtrim(substr($path,0,strrpos($path,'/')?:0),'/')?:'';
        foreach($ip_list as $ip_override){
            $res=['ip'=>$ip_override?:'(default DNS)','playlist'=>null,'chunklist'=>null,'chunklist_url'=>null,'ts'=>[],'ll_hls'=>null,'m4v'=>[]];

            // Playlist
            $p=fetch_url_with_curl($playlist_url,$host,$ip_override?:'');
            $res['playlist']=$p;
            if(!$p['content']){$results[]=$res; continue;}

            // Chunklist
            $lines=array_filter(array_map('trim',preg_split('/\r?\n/',$p['content'])),fn($l)=>$l!==''&&$l[0]!=='#');
            $chunklist_rel=null;
            foreach($lines as $l){if(strtolower(substr($l,-5))==='.m3u8'||stripos($l,'chunklist')!==false){$chunklist_rel=$l;break;}}
            if(!$chunklist_rel){$res['chunklist']=['error'=>'chunklist 없음'];$results[]=$res;continue;}
            $chunklist_url=strpos($chunklist_rel,'http')===0?$chunklist_rel:$scheme.'://'.$host.($base_path?$base_path.'/':'').$chunklist_rel;
            $res['chunklist_url']=$chunklist_url;
            $c=fetch_url_with_curl($chunklist_url,$host,$ip_override?:'');
            $res['chunklist']=$c;
            if(!$c['content']){$results[]=$res;continue;}

            // TS
            $clines=array_filter(array_map('trim',preg_split('/\r?\n/',$c['content'])),fn($l)=>$l!==''&&$l[0]!=='#');
            foreach($clines as $ln){if(strtolower(substr($ln,-3))==='.ts') $res['ts'][]=(strpos($ln,'http')===0)?$ln:rtrim(dirname($chunklist_url),'/').'/'.$ln;}

            // LL-HLS
            if(preg_match('/LAST-MSN\s*=\s*(\d+)/i',$c['content'],$m)){
                $last_msn=$m[1];
                $ll_url=$chunklist_url."?_HLS_msn={$last_msn}&_HLS_part=1";
                $res['ll_hls']=['url'=>$ll_url];
                $ll=fetch_url_with_curl($ll_url,$host,$ip_override?:'');
                $res['ll_hls']['http_code']=$ll['http_code'];
                $res['ll_hls']['content']=$ll['content'];
                if($ll['content']){
                    $ll_lines=array_filter(array_map('trim',preg_split('/\r?\n/',$ll['content'])),fn($l)=>$l!==''&&$l[0]!=='#');
                    foreach($ll_lines as $ln){if(preg_match('/\.(m4v|m4a|mp4)$/i',$ln)) $res['m4v'][]=(strpos($ln,'http')===0)?$ln:rtrim(dirname($ll_url),'/').'/'.$ln;}
                }
            }
            $results[]=$res;
        }
    }
}
?>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Stream Check</title>
<style>
body{font-family:system-ui,Arial;padding:16px}
textarea{width:100%;height:120px}
table{border-collapse:collapse;width:100%;margin-top:12px}
th,td{border:1px solid #ccc;padding:8px;text-align:left}
.status-ok{color:green;font-weight:bold}
.status-bad{color:red;font-weight:bold}
.box{border:1px solid #ddd;padding:10px;margin:10px 0;border-radius:6px}
pre{background:#f6f8fa;padding:8px;border-radius:6px;overflow:auto}
</style>
</head>
<body>
<h2>Media Stream Check</h2>
<form method="post">
URL:<br>
<input type="text" name="playlist_url" size="80" value="<?php echo isset($_POST['playlist_url'])?htmlspecialchars($_POST['playlist_url']):''; ?>"><br><br>
IP 리스트:<br>
<textarea name="ip_override"><?php echo isset($_POST['ip_override'])?htmlspecialchars($_POST['ip_override']):''; ?></textarea><br>
<button type="submit">실행</button>
</form>

<?php if(!empty($results)): ?>
<h3>요약</h3>
<table>
<thead><tr><th>IP</th><th>Playlist</th><th>Chunklist</th><th>HLS/LL-HLS</th><th>Check</th></tr></thead>
<tbody>
<?php foreach($results as $r):
    $pl_code=$r['playlist']['http_code']??0;
    $cl_code=$r['chunklist']['http_code']??0;
    $is_ok=($pl_code===200&&$cl_code===200);
    $type=!empty($r['ll_hls'])?'LL-HLS':'HLS';
?>
<tr>
<td><?php echo htmlspecialchars($r['ip']); ?></td>
<td><?php echo $pl_code?:'-'; ?></td>
<td><?php echo $cl_code?:'-'; ?></td>
<td><?php echo htmlspecialchars($type); ?></td>
<td><?php echo $is_ok?'<span class="status-ok">O</span>':'<span class="status-bad">X</span>'; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

<h3>상세</h3>
<?php foreach($results as $r): ?>
<div class="box">
<details>
<summary><strong>IP: <?php echo htmlspecialchars($r['ip']); ?></strong></summary>
<div style="margin-top:8px">
<strong>Playlist HTTP:</strong> <?php echo $r['playlist']['http_code']??0; ?> <?php if($r['playlist']['error']) echo "({$r['playlist']['error']})"; ?><br>
<?php if($r['playlist']['content']): ?><details><summary>Playlist 내용</summary><pre><?php echo htmlspecialchars(substr($r['playlist']['content'],0,8000)); ?></pre></details><?php endif; ?>

<strong>Chunklist URL:</strong> <?php echo htmlspecialchars($r['chunklist_url']??'-'); ?><br>
<strong>Chunklist HTTP:</strong> <?php echo $r['chunklist']['http_code']??0; ?> <?php if($r['chunklist']['error']) echo "({$r['chunklist']['error']})"; ?><br>
<?php if($r['chunklist']['content']): ?><details><summary>Chunklist 내용</summary><pre><?php echo htmlspecialchars(substr($r['chunklist']['content'],0,8000)); ?></pre></details><?php endif; ?>

<?php if(!empty($r['ts'])): ?>
<strong>TS 파일:</strong>
<ul><?php foreach($r['ts'] as $t) echo '<li>'.htmlspecialchars($t).'</li>'; ?></ul>
<?php endif; ?>

<?php if(!empty($r['ll_hls'])): ?>
<strong>LL-HLS URL:</strong> <?php echo htmlspecialchars($r['ll_hls']['url']); ?><br>
<strong>LL-HLS HTTP:</strong> <?php echo htmlspecialchars($r['ll_hls']['http_code']??0); ?><br>
<?php if(!empty($r['ll_hls']['content'])): ?><details><summary>LL-HLS 내용</summary><pre><?php echo htmlspecialchars(substr($r['ll_hls']['content'],0,8000)); ?></pre></details><?php endif; ?>
<?php if(!empty($r['m4v'])): ?>
<strong>m4v/mp4 파일:</strong>
<ul><?php foreach($r['m4v'] as $m) echo '<li>'.htmlspecialchars($m).'</li>'; ?></ul>
<?php endif; ?>
<?php endif; ?>

</div>
</details>
</div>
<?php endforeach; ?>
<?php endif; ?>
</body>
</html>
