<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/bootstrap.php';
api_common_headers('application/json; charset=utf-8');

function webview_config_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']??0),
            'title'=>trim((string)($row['title']??'Sports')) ?: 'Sports',
            'url'=>$url,
            'notes'=>(string)($row['notes']??''),
            'sort_order'=>(int)($row['sort_order']??0),
        ];
    }
    $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 {
    echo json_encode(webview_config_payload(), JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_INVALID_UTF8_SUBSTITUTE);
} catch(Throwable $e){
    api_log('webview_config_error',['exception'=>get_class($e),'message'=>$e->getMessage()]);
    http_response_code(500);
    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);
}
