<?php
require_once __DIR__ . '/../config/bootstrap.php';
require_method('GET');

$pdo = db();
$token = get_str('token','');
if ($token === '') json_response(['ok'=>false,'error'=>'Token ausente.'], 422);

$st = $pdo->prepare("SELECT * FROM eventos WHERE token_publico=? AND status='published' LIMIT 1");
$st->execute([$token]);
$ev = $st->fetch();
if (!$ev) json_response(['ok'=>false,'error'=>'Evento não encontrado ou não publicado.'], 404);

$cfg = json_decode($ev['config_json'], true);
if (!is_array($cfg)) $cfg = [];

function collect_asset_ids($arr, &$ids){
  if (is_array($arr)) {
    foreach($arr as $k=>$v){
      if ($k === 'asset_id' && (is_int($v) || ctype_digit((string)$v))) {
        $n = (int)$v;
        if ($n > 0) $ids[$n] = true;
      } else {
        collect_asset_ids($v, $ids);
      }
    }
  }
}

$ids = [];
collect_asset_ids($cfg, $ids);
$assets_map = [];
if ($ids) {
  $in = implode(',', array_fill(0, count($ids), '?'));
  $st2 = $pdo->prepare('SELECT id, arquivo FROM assets WHERE id IN ('. $in .')');
  $st2->execute(array_keys($ids));
  while($row = $st2->fetch()){
    // Ajusta para subpasta (evita 404 no cliente)
    $assets_map[(string)$row['id']] = build_url_path((string)$row['arquivo']);
  }
}

json_response([
  'ok' => true,
  'event' => [
    'id' => (int)$ev['id'],
    'nome_evento' => $ev['nome_evento'],
    'data_evento' => $ev['data_evento'],
    'destino' => $ev['destino'],
    'endereco' => $ev['endereco'],
  ],
  'config' => $cfg,
  'assets' => $assets_map,
]);
