<?php
date_default_timezone_set('Asia/Hong_Kong');
$race_id=isset($_GET['race_id'])?intval($_GET['race_id']):0;
$base=(isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=='off'?'https':'http').'://'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['SCRIPT_NAME']),'/\\').'/';
$files=array(
 'Main Analysis'=>'get_analysis_ajax.php',
 'Trend 3-Core'=>'get_analysis_trend_ajax.php',
 'Trend 4-Core'=>'get_analysis_trend_ajax_(4_person_select_version).php'
);
function h($s){return htmlspecialchars((string)$s,ENT_QUOTES,'UTF-8');}
function probe($url){
 $t=microtime(true);
 $ctx=stream_context_create(array('http'=>array('timeout'=>120,'ignore_errors'=>true)));
 $body=@file_get_contents($url,false,$ctx);
 $headers=isset($http_response_header)?$http_response_header:array();
 $code=0;
 foreach($headers as $x){if(preg_match('/HTTP\\/\\S+\\s+(\\d+)/',$x,$m))$code=intval($m[1]);}
 $json=json_decode((string)$body,true);
 return array('url'=>$url,'http_code'=>$code,'elapsed_ms'=>round((microtime(true)-$t)*1000,2),'bytes'=>strlen((string)$body),'json_valid'=>json_last_error()===JSON_ERROR_NONE,'json_error'=>json_last_error_msg(),'preview'=>substr((string)$body,0,1200),'row_count'=>is_array($json)?count($json):0);
}
$rows=array();
foreach($files as $name=>$file)$rows[$name]=probe($base.$file.'?race_id='.$race_id.'&_='.time());
?><!doctype html><html><head><meta charset="utf-8"><title>Analysis Engine Diagnostic</title>
<style>body{background:#07101c;color:#eef;font-family:Arial;padding:24px}.box{background:#0c1423;border:1px solid #345;border-radius:12px;padding:16px;margin:12px 0}.ok{color:#3fda8b}.bad{color:#ff718c}.gold{color:#ffc107}pre{white-space:pre-wrap;word-break:break-word;background:#050914;padding:12px;border-radius:8px}</style></head>
<body><h1>WinRacing Analysis Engine Diagnostic v4.3</h1>
<form>Race ID <input name="race_id" value="<?=h($race_id)?>"><button>Test</button></form>
<?php foreach($rows as $name=>$r):?><div class="box"><h2><?=h($name)?> — <span class="<?=$r['json_valid']?'ok':'bad'?>"><?=$r['json_valid']?'JSON OK':'JSON ERROR'?></span></h2>
<p>HTTP <?=h($r['http_code'])?>｜<?=h($r['elapsed_ms'])?> ms｜<?=h($r['bytes'])?> bytes｜Rows <?=h($r['row_count'])?></p>
<p class="gold"><?=h($r['url'])?></p><p>JSON: <?=h($r['json_error'])?></p><pre><?=h($r['preview'])?></pre></div><?php endforeach;?>
</body></html>