<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/bootstrap.php';

function sports_payload(): array {
    $rows=db()->query('SELECT id,title,url,notes,sort_order FROM webview_pages WHERE active=1 ORDER BY sort_order ASC,id ASC')->fetchAll();
    $pages=[];
    foreach($rows as $row){
        $url=trim((string)($row['url']??''));
        $scheme=strtolower((string)parse_url($url,PHP_URL_SCHEME));
        if($url==='' || filter_var($url,FILTER_VALIDATE_URL)===false || !in_array($scheme,['http','https'],true)) continue;
        $pages[]=['id'=>(int)$row['id'],'title'=>trim((string)$row['title'])?:'Sports','url'=>$url,'notes'=>(string)$row['notes'],'sort_order'=>(int)$row['sort_order']];
    }
    $first=$pages[0]??null;
    return ['success'=>true,'enabled'=>$first!==null,'title'=>$first['title']??'Sports','url'=>$first['url']??'','javascript'=>true,'allow_external'=>false,'user_agent'=>'','maintenance_message'=>$first===null?'Sports guide is not configured.':'','pages'=>$pages];
}

try {
    $payload=sports_payload();
    if(isset($_GET['config']) || isset($_GET['json'])){
        api_common_headers('application/json; charset=utf-8');
        echo json_encode($payload,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_INVALID_UTF8_SUBSTITUTE);
        exit;
    }
    $url=(string)($payload['url']??'');
    if($url===''){
        http_response_code(503);
        header('Content-Type: text/html; charset=utf-8');
        echo '<!doctype html><meta name="viewport" content="width=device-width"><title>Sports</title><style>body{margin:0;background:#071426;color:#fff;font:16px system-ui;display:grid;place-items:center;min-height:100vh}.box{padding:24px;text-align:center}</style><div class="box"><h2>Sports guide is not configured</h2></div>';
        exit;
    }
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Location: '.$url, true, 302);
    exit;
} catch(Throwable $e){
    api_log('sports_direct_error',['exception'=>get_class($e),'message'=>$e->getMessage()]);
    http_response_code(500);
    if(isset($_GET['config']) || isset($_GET['json'])){
        api_common_headers('application/json; charset=utf-8');
        echo json_encode(['success'=>false,'enabled'=>false,'title'=>'Sports','url'=>'','javascript'=>true,'allow_external'=>false,'user_agent'=>'','maintenance_message'=>'Sports guide configuration is temporarily unavailable.','pages'=>[]],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
    }else{
        header('Content-Type: text/plain; charset=utf-8');
        echo 'Sports guide is temporarily unavailable.';
    }
}
