<?php
require_once dirname(__DIR__) . '/includes/auth.php';
$dbPath=dirname(__DIR__).'/api/db.db';$alert='';$alertType='success';
function emu_h($v){return htmlspecialchars((string)$v,ENT_QUOTES,'UTF-8');}
function emu_slug($v){$v=iconv('UTF-8','ASCII//TRANSLIT//IGNORE',(string)$v)?:$v;$v=strtolower(preg_replace('/[^a-zA-Z0-9]+/','-',$v)??'');return trim($v,'-')?:'rom';}
function emu_schema(PDO $db):void{$db->exec("CREATE TABLE IF NOT EXISTS app_config (id INTEGER PRIMARY KEY, updated_at DATETIME)");$cols=[];foreach($db->query('PRAGMA table_info(app_config)') as $r)$cols[]=(string)$r['name'];if(!in_array('emuladores_enabled',$cols,true))$db->exec('ALTER TABLE app_config ADD COLUMN emuladores_enabled INTEGER NOT NULL DEFAULT 1');if(!in_array('emuladores_block_message',$cols,true))$db->exec("ALTER TABLE app_config ADD COLUMN emuladores_block_message TEXT NOT NULL DEFAULT 'Área Jogos Retro bloqueada pelo painel.'");$db->exec('INSERT OR IGNORE INTO app_config(id) VALUES(1)');$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)");}
$platforms=['psp'=>'PSP','playstation'=>'PlayStation / PS1','snes'=>'Super Nintendo / SNES','mega-drive'=>'Mega Drive','gba'=>'Game Boy Advance','nes'=>'Nintendo / NES','master-system'=>'Master System','n64'=>'Nintendo 64'];
try{$db=new PDO('sqlite:'.$dbPath,null,null,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);emu_schema($db);
 if(($_SERVER['REQUEST_METHOD']??'')==='POST'&&isset($_POST['save_emuladores_status'])){$enabled=isset($_POST['emuladores_enabled'])?1:0;$msg=trim((string)($_POST['emuladores_block_message']??''))?:'Área Jogos Retro bloqueada pelo painel.';$db->prepare('UPDATE app_config SET emuladores_enabled=?,emuladores_block_message=?,updated_at=datetime("now") WHERE id=1')->execute([$enabled,$msg]);$alert='Status dos emuladores salvo.';}
 if(($_SERVER['REQUEST_METHOD']??'')==='POST'&&isset($_POST['upload_rom'])){$platform=(string)($_POST['platform']??'');$title=trim((string)($_POST['title']??''));if(!isset($platforms[$platform])||$title==='')throw new RuntimeException('Informe o emulador e o nome da ROM.');if(empty($_FILES['rom_file']['tmp_name'])||!is_uploaded_file($_FILES['rom_file']['tmp_name']))throw new RuntimeException('Selecione o arquivo da ROM.');$romExt=strtolower(pathinfo((string)$_FILES['rom_file']['name'],PATHINFO_EXTENSION));$allowed=['zip','7z','sfc','smc','nes','gba','gb','gbc','sms','iso','bin','cue','pbp','chd','rom','z64','n64','v64','cso'];if(!in_array($romExt,$allowed,true))throw new RuntimeException('Formato de ROM não permitido.');$slug=emu_slug($title).'-'.substr(bin2hex(random_bytes(5)),0,8);$romDir=dirname(__DIR__).'/storage/roms/'.$platform;$coverDir=dirname(__DIR__).'/storage/rom-covers';@mkdir($romDir,0775,true);@mkdir($coverDir,0775,true);$romRel='storage/roms/'.$platform.'/'.$slug.'.'.$romExt;$romAbs=dirname(__DIR__).'/'.$romRel;if(!@move_uploaded_file($_FILES['rom_file']['tmp_name'],$romAbs))throw new RuntimeException('Falha ao salvar a ROM.');@chmod($romAbs,0644);$coverRel='';if(!empty($_FILES['cover_file']['tmp_name'])&&is_uploaded_file($_FILES['cover_file']['tmp_name'])){$mime=(string)($_FILES['cover_file']['type']??'');$ext=strtolower(pathinfo((string)$_FILES['cover_file']['name'],PATHINFO_EXTENSION));if(!in_array($ext,['jpg','jpeg','png','webp'],true)||strpos($mime,'image/')!==0){@unlink($romAbs);throw new RuntimeException('A capa deve ser JPG, PNG ou WEBP.');}$coverRel='storage/rom-covers/'.$slug.'.'.$ext;$coverAbs=dirname(__DIR__).'/'.$coverRel;if(!@move_uploaded_file($_FILES['cover_file']['tmp_name'],$coverAbs)){@unlink($romAbs);throw new RuntimeException('Falha ao salvar a capa.');}@chmod($coverAbs,0644);} $db->prepare('INSERT INTO retro_roms(platform,platform_name,title,slug,rom_path,cover_path,file_size) VALUES(?,?,?,?,?,?,?)')->execute([$platform,$platforms[$platform],$title,$slug,$romRel,$coverRel,(int)filesize($romAbs)]);$alert='ROM enviada ao servidor local e publicada nos aplicativos.';}
 if(isset($_POST['delete_rom'])){$id=(int)$_POST['delete_rom'];$row=$db->prepare('SELECT rom_path,cover_path FROM retro_roms WHERE id=?');$row->execute([$id]);$r=$row->fetch();if($r){foreach(['rom_path','cover_path'] as $k){$rel=(string)($r[$k]??'');if($rel!=='')@unlink(dirname(__DIR__).'/'.ltrim($rel,'/'));}$db->prepare('DELETE FROM retro_roms WHERE id=?')->execute([$id]);$alert='ROM removida.';}}
 $cfg=$db->query('SELECT emuladores_enabled,emuladores_block_message FROM app_config WHERE id=1')->fetch()?:[];$roms=$db->query('SELECT * FROM retro_roms ORDER BY id DESC')->fetchAll();
}catch(Throwable $e){$cfg=['emuladores_enabled'=>1,'emuladores_block_message'=>'Área Jogos Retro bloqueada pelo painel.'];$roms=[];$alert=$e->getMessage()?:'Erro ao carregar emuladores.';$alertType='danger';}
require_once __DIR__ . '/../includes/header.php';?>
<div class="emu-wrap"><?php if($alert):?><div class="alert alert-<?=$alertType?>"><?=emu_h($alert)?></div><?php endif;?>
<div class="card emu-card"><div class="emu-head"><h5><i class="bi bi-shield-lock-fill"></i> Controle do menu Jogos Retro</h5></div><div class="card-body"><form method="post" class="row g-3"><input type="hidden" name="save_emuladores_status" value="1"><div class="col-md-4"><div class="form-check form-switch mt-4"><input class="form-check-input" type="checkbox" name="emuladores_enabled" id="emuOn" <?=((int)($cfg['emuladores_enabled']??1)===1)?'checked':''?>><label class="form-check-label fw-bold" for="emuOn">Ativar Jogos Retro</label></div></div><div class="col-md-6"><label class="form-label fw-bold">Mensagem quando bloqueado</label><input class="form-control" name="emuladores_block_message" value="<?=emu_h($cfg['emuladores_block_message']??'')?>"></div><div class="col-md-2 d-flex align-items-end"><button class="btn btn-success w-100">Salvar</button></div></form></div></div>
<div class="card emu-card"><div class="emu-head"><h5><i class="bi bi-hdd-network-fill"></i> ROMs</h5><span class="badge bg-success">Painel local</span></div><form method="post" enctype="multipart/form-data" class="row g-3"><input type="hidden" name="upload_rom" value="1"><div class="col-md-4"><label class="form-label fw-bold">Emulador</label><select class="form-select" name="platform" required><?php foreach($platforms as $key=>$label):?><option value="<?=emu_h($key)?>"><?=emu_h($label)?></option><?php endforeach;?></select></div><div class="col-md-4"><label class="form-label fw-bold">Nome da ROM</label><input class="form-control" name="title" required maxlength="100" placeholder="Ex: Top Gear"></div><div class="col-md-4"><label class="form-label fw-bold">Foto/Capa</label><input class="form-control" type="file" name="cover_file" accept="image/jpeg,image/png,image/webp"></div><div class="col-md-9"><label class="form-label fw-bold">Arquivo da ROM</label><input class="form-control" type="file" name="rom_file" required></div><div class="col-md-3 d-flex align-items-end"><button class="btn btn-primary w-100"><i class="bi bi-cloud-arrow-up-fill"></i> Publicar ROM</button></div></form></div></div>
<div class="card emu-card"><div class="emu-head"><h5><i class="bi bi-list-ul"></i> ROMs publicadas</h5><span class="badge bg-primary"><?=count($roms)?> ROMs</span></div><div class="card-body p-0"><div class="table-responsive"><table class="table align-middle mb-0"><thead><tr><th>Capa</th><th>Nome</th><th>Emulador</th><th>Tamanho</th><th>Data</th><th></th></tr></thead><tbody><?php if(!$roms):?><tr><td colspan="6" class="text-center py-4 text-muted">Nenhuma ROM publicada.</td></tr><?php endif;?><?php foreach($roms as $r):?><tr><td><?php if($r['cover_path']):?><img class="rom-cover" src="<?=emu_h(rtrim($BASE_URL,'/').'/'.ltrim((string)$r['cover_path'],'/'))?>"><?php else:?><div class="rom-cover d-flex align-items-center justify-content-center"><i class="bi bi-controller"></i></div><?php endif;?></td><td class="fw-bold"><?=emu_h($r['title'])?></td><td><?=emu_h($r['platform_name'])?></td><td><?=number_format(((int)$r['file_size'])/1048576,2,',','.')?> MB</td><td><?=emu_h($r['created_at'])?></td><td><form method="post" data-confirm-submit="Apagar esta ROM?"><button class="btn btn-sm btn-danger" name="delete_rom" value="<?=(int)$r['id']?>"><i class="bi bi-trash"></i></button></form></td></tr><?php endforeach;?></tbody></table></div></div></div></div>
<?php require_once __DIR__ . '/../includes/footer.php';?>
