<?php
declare(strict_types=1);
require_once dirname(__DIR__) . '/sonocamara-private/bootstrap.php';
$route=$_GET['route']??'dashboard';$pdo=db();
function admin_head(string $title):void{?><!doctype html><html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?=e($title)?></title><link rel="stylesheet" href="<?=e(base_url('assets/css/styles.css'))?>"><style>
/* Ajustes exclusivos del panel administrativo */
.admin-shell{
  width:min(1380px,calc(100% - 64px));
  margin:0 auto;
  padding:118px 0 72px;
}
.admin-shell .title{
  margin:0 0 26px;
  line-height:1.08;
}
.admin-tabs{
  display:flex;
  flex-wrap:wrap;
  gap:0;
  margin:0 0 24px;
}
.admin-tabs .btn{
  min-width:126px;
  text-align:center;
}
.admin-tabs .btn.is-active{
  background:var(--gold);
  color:var(--paper);
}
.admin-table-wrap{
  width:100%;
  overflow-x:auto;
  border:1px solid rgba(201,168,76,.16);
}
.admin-table{
  width:100%;
  min-width:840px;
  border-collapse:collapse;
}
.admin-table th,
.admin-table td{
  padding:16px 18px;
  text-align:left;
  vertical-align:top;
  border-bottom:1px solid rgba(201,168,76,.14);
}
.admin-table th{
  color:var(--gold-light);
  font-weight:500;
  letter-spacing:.04em;
}
.admin-table tr:last-child td{
  border-bottom:0;
}
.admin-table td:last-child{
  width:132px;
  text-align:right;
}
.admin-form{
  max-width:860px;
}
@media (max-width:700px){
  .admin-shell{
    width:min(100% - 28px,1380px);
    padding-top:102px;
  }
  .admin-shell .title{
    font-size:clamp(2rem,10vw,3.1rem);
  }
  .admin-tabs .btn{
    min-width:auto;
    flex:1 1 auto;
  }
}
</style></head><body><header class="radio-bar"><a class="brand" href="<?=e(base_url())?>">Sonocámara Radio</a><div><a class="btn" href="<?=e(base_url())?>">Ver web</a><?php if(is_admin()):?> <a class="btn" href="<?=e(admin_url('?route=logout'))?>">Salir</a><?php endif?></div></header><main class="admin-shell"><?php foreach(flashes() as $f):?><div class="notice"><?=e($f['message'])?></div><?php endforeach?><?php }
function admin_foot():void{?></main></body></html><?php }
if(!$pdo){admin_head('Configuración pendiente');?><h1 class="title">Base de datos pendiente</h1><p class="lead">Completa las credenciales privadas en <code>public_html/sonocamara-private/config.php</code> e importa <code>database/install.sql</code>.</p><?php admin_foot();exit;}
if($route==='setup'){ if(admin_exists()) redirect(admin_url('?route=login')); if($_SERVER['REQUEST_METHOD']==='POST'){try{verify_csrf($_POST['csrf']??null);if(!hash_equals((string)cfg('setup_token'),(string)($_POST['setup_token']??'')))throw new RuntimeException('Token de instalación incorrecto.');$pass=(string)($_POST['password']??'');if(strlen($pass)<12)throw new RuntimeException('Usa una contraseña de al menos 12 caracteres.');$st=$pdo->prepare('INSERT INTO admin_users(username,password_hash) VALUES(:u,:p)');$st->execute(['u'=>'sonocamara','p'=>password_hash($pass,PASSWORD_DEFAULT)]);flash('ok','Administrador creado.');redirect(admin_url('?route=login'));}catch(Throwable $e){flash('error',$e->getMessage());redirect(admin_url('?route=setup'));}} admin_head('Crear administrador');?><h1 class="title">Crear administrador inicial</h1><form class="admin-form" method="post"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><label>Token temporal<input required name="setup_token"></label><label>Nueva contraseña<input required type="password" name="password" minlength="12"></label><button class="btn gold">Crear usuario sonocamara</button></form><?php admin_foot();exit;}
if($route==='login'){ if(is_admin())redirect(admin_url()); if($_SERVER['REQUEST_METHOD']==='POST'){verify_csrf($_POST['csrf']??null);$st=$pdo->prepare('SELECT * FROM admin_users WHERE username=:u LIMIT 1');$st->execute(['u'=>trim((string)($_POST['username']??''))]);$u=$st->fetch();if($u&&password_verify((string)($_POST['password']??''),$u['password_hash'])){session_regenerate_id(true);$_SESSION['admin_user_id']=$u['id'];redirect(admin_url());}flash('error','Credenciales incorrectas.');redirect(admin_url('?route=login'));}admin_head('Acceso administrativo');?><h1 class="title">Administrar recuerdos</h1><?php if(!admin_exists()):?><p><a class="btn" href="<?=e(admin_url('?route=setup'))?>">Crear administrador inicial</a></p><?php endif?><form class="admin-form" method="post"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><label>Usuario<input name="username" value="sonocamara" required></label><label>Contraseña<input name="password" type="password" required></label><button class="btn gold">Ingresar</button></form><?php admin_foot();exit;}
if($route==='logout'){session_destroy();redirect(admin_url('?route=login'));}
require_admin();
if($route==='save'&&$_SERVER['REQUEST_METHOD']==='POST'){verify_csrf($_POST['csrf']??null);$id=(int)($_POST['id']??0);$action=$_POST['action']??'save';$name=trim((string)($_POST['public_name']??''));$message=trim((string)($_POST['message']??''));$video=valid_video_url($_POST['video_url']??null);if($name===''||mb_strlen($message)<20)throw new RuntimeException('Revisa el nombre y el contenido.');$pdo->prepare('UPDATE memories SET public_name=:n,message=:m,video_url=:v,updated_at=NOW() WHERE id=:id')->execute(['n'=>$name,'m'=>$message,'v'=>$video,'id'=>$id]);if($action==='approve')$pdo->prepare("UPDATE memories SET status='approved',approved_at=NOW(),deleted_at=NULL WHERE id=:id")->execute(['id'=>$id]);if($action==='delete')$pdo->prepare("UPDATE memories SET previous_status=IF(status='approved','approved','pending'),status='deleted',deleted_at=NOW() WHERE id=:id")->execute(['id'=>$id]);if($action==='restore')$pdo->prepare("UPDATE memories SET status=COALESCE(previous_status,'pending'),deleted_at=NULL WHERE id=:id")->execute(['id'=>$id]);flash('ok','Cambios guardados.');redirect(admin_url());}
if($route==='edit'){require_admin();$st=$pdo->prepare('SELECT * FROM memories WHERE id=:id');$st->execute(['id'=>(int)($_GET['id']??0)]);$m=$st->fetch();if(!$m)redirect(admin_url());admin_head('Editar recuerdo');?><h1 class="title">Revisar recuerdo</h1><form class="admin-form" method="post" action="<?=e(admin_url('?route=save'))?>"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="id" value="<?=(int)$m['id']?>"><p><strong>Autor original:</strong> <?=e($m['author_name'])?> · <?=e($m['author_email'])?></p><label>Nombre público<input name="public_name" value="<?=e($m['public_name'])?>" maxlength="90"></label><label>Recuerdo<textarea name="message" rows="10" maxlength="1500"><?=e($m['message'])?></textarea></label><label>URL YouTube/Vimeo<input name="video_url" value="<?=e($m['video_url'])?>"></label><?php if($m['avatar_path']):?><img class="avatar" src="<?=e($m['avatar_path'])?>"><?php endif?><?php if($m['image_thumb_path']):?><p><img style="max-width:320px" src="<?=e($m['image_thumb_path'])?>"></p><?php endif?><div style="display:flex;gap:8px;flex-wrap:wrap"><button class="btn" name="action" value="save">Guardar</button><?php if($m['status']!=='approved'):?><button class="btn gold" name="action" value="approve">Aprobar y publicar</button><?php endif?><?php if($m['status']!=='deleted'):?><button class="btn" name="action" value="delete">Eliminar</button><?php else:?><button class="btn" name="action" value="restore">Restaurar</button><?php endif?></div></form><?php admin_foot();exit;}
$status=in_array($_GET['status']??'pending',['pending','approved','deleted'],true)?$_GET['status']:'pending';$st=$pdo->prepare('SELECT * FROM memories WHERE status=:s ORDER BY created_at DESC');$st->execute(['s'=>$status]);$items=$st->fetchAll();admin_head('Panel Sonocámara');?><h1 class="title">Administrar recuerdos</h1><div class="admin-tabs"><a class="btn <?=$status==='pending'?'is-active':''?>" href="<?=e(admin_url('?status=pending'))?>">Pendientes</a><a class="btn <?=$status==='approved'?'is-active':''?>" href="<?=e(admin_url('?status=approved'))?>">Aprobados</a><a class="btn <?=$status==='deleted'?'is-active':''?>" href="<?=e(admin_url('?status=deleted'))?>">Eliminados</a></div><div class="admin-table-wrap"><table class="admin-table"><thead><tr><th>Fecha</th><th>Autor</th><th>Extracto</th><th></th></tr></thead><tbody><?php foreach($items as $m):?><tr><td><?=e(date('d/m/Y H:i',strtotime($m['created_at'])))?></td><td><?=e($m['public_name'])?></td><td><?=e(mb_strimwidth($m['message'],0,120,'…'))?></td><td><a class="btn" href="<?=e(admin_url('?route=edit&id='.(int)$m['id']))?>">Revisar</a></td></tr><?php endforeach?></tbody></table></div><?php if(!$items):?><p class="hint">No existen registros en este estado.</p><?php endif;admin_foot();
