<?php
declare(strict_types=1);require_once dirname(__DIR__).'/_app_guard.php';app_guard_validate();require_once dirname(__DIR__).'/_auth_common.php';
function rr_base():string{$https=(!empty($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=='off')||(($_SERVER['HTTP_X_FORWARDED_PROTO']??'')==='https');$origin=rtrim(($https?'https':'http').'://'.($_SERVER['HTTP_HOST']??'localhost'),'/');$script=(string)($_SERVER['SCRIPT_NAME']??'/api/app.php');$root=rtrim(str_replace('\\','/',dirname(dirname($script))),'/');return $origin.($root==='/'||$root==='.'?'':$root);}
function rr_url(string $path):string{return $path===''?'':rr_base().'/'.ltrim($path,'/');}
function rr_platform_aliases(string $p):array{$p=strtolower(trim($p));$map=['ps1'=>'playstation','playstation 1'=>'playstation','psx'=>'playstation','super nintendo'=>'snes','super-nintendo'=>'snes','mega drive'=>'mega-drive','megadrive'=>'mega-drive','sega genesis'=>'mega-drive','game boy advance'=>'gba','nintendo entertainment system'=>'nes','nintendo'=>'nes','sega master system'=>'master-system','nintendo 64'=>'n64','game boy color'=>'gbc','game boy'=>'gb'];return array_values(array_unique([$p,$map[$p]??$p]));}
try{$db=new PDO('sqlite:'.dirname(__DIR__).'/db.db',null,null,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);$db->exec("CREATE TABLE IF NOT EXISTS retro_roms(id INTEGER PRIMARY KEY AUTOINCREMENT,platform TEXT NOT NULL,platform_name TEXT NOT NULL,title TEXT NOT NULL,slug TEXT NOT NULL UNIQUE,rom_path TEXT NOT NULL,cover_path TEXT NOT NULL DEFAULT '',file_size INTEGER NOT NULL DEFAULT 0,enabled INTEGER NOT NULL DEFAULT 1,created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)");$slug=trim((string)($_GET['slug']??''));$id=(int)($_GET['id']??0);$where=['enabled=1'];$args=[];if($slug!==''){$where[]='slug=?';$args[]=$slug;}elseif($id>0){$where[]='id=?';$args[]=$id;}else{$platform=trim((string)($_GET['platform']??''));if($platform!==''){$aliases=rr_platform_aliases($platform);$where[]='LOWER(platform) IN ('.implode(',',array_fill(0,count($aliases),'?')).')';$args=array_merge($args,$aliases);}$search=trim((string)($_GET['search']??''));if($search!==''){$where[]='title LIKE ?';$args[]='%'.$search.'%';}}
 $sqlWhere=implode(' AND ',$where);if($slug!==''||$id>0){$st=$db->prepare('SELECT * FROM retro_roms WHERE '.$sqlWhere.' LIMIT 1');$st->execute($args);$r=$st->fetch();if(!$r){http_response_code(404);auth_json_out(['status'=>'error','message'=>'rom_not_found']);}auth_json_out(['status'=>'ok','data'=>['id'=>(string)$r['id'],'title'=>$r['title'],'slug'=>$r['slug'],'short_description'=>'ROM publicada pelo painel','description'=>'ROM publicada pelo painel','cover_image'=>rr_url($r['cover_path']),'platform'=>$r['platform_name'],'platform_slug'=>$r['platform'],'genre'=>'','release_year'=>'','developer'=>'Painel','file_size'=>number_format(((int)$r['file_size'])/1048576,2,'.','').' MB','download_count'=>'0','views_count'=>'0','rating'=>'0','version'=>'1.0','video_url'=>'','manual_url'=>'','created_at'=>$r['created_at'],'updated_at'=>$r['updated_at'],'download_url'=>rr_url($r['rom_path']),'play_url'=>rr_url($r['rom_path']),'source'=>'panel']]);}
 $page=max(1,(int)($_GET['page']??1));$limit=min(100,max(1,(int)($_GET['limit']??50)));$offset=($page-1)*$limit;$count=$db->prepare('SELECT COUNT(*) FROM retro_roms WHERE '.$sqlWhere);$count->execute($args);$total=(int)$count->fetchColumn();$st=$db->prepare('SELECT * FROM retro_roms WHERE '.$sqlWhere.' ORDER BY id DESC LIMIT '.$limit.' OFFSET '.$offset);$st->execute($args);$data=[];foreach($st as $r){$data[]=['id'=>'panel:'.$r['id'],'title'=>$r['title'],'slug'=>'panel__'.$r['slug'],'short_description'=>'ROM publicada pelo painel','cover_image'=>rr_url($r['cover_path']),'platform'=>$r['platform_name'],'platform_slug'=>$r['platform'],'genre'=>'','release_year'=>'','developer'=>'Painel','file_size'=>number_format(((int)$r['file_size'])/1048576,2,'.','').' MB','download_count'=>'0','views_count'=>'0','rating'=>'0','version'=>'1.0','video_url'=>'','created_at'=>$r['created_at'],'download_url'=>rr_url($r['rom_path']),'source'=>'panel'];}auth_json_out(['status'=>'ok','data'=>$data,'pagination'=>['page'=>$page,'limit'=>$limit,'total'=>$total,'has_next'=>$offset+$limit<$total],'server_ts'=>time()]);
}catch(Throwable $e){http_response_code(500);auth_json_out(['status'=>'error','message'=>'retro_roms_unavailable']);}
