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

$pdo = db();
$data = get_json_body();

$nome_evento = trim((string)($data['nome_evento'] ?? ''));
$data_evento = trim((string)($data['data_evento'] ?? ''));
$destino = trim((string)($data['destino'] ?? ''));
$endereco = trim((string)($data['endereco'] ?? ''));

if ($nome_evento === '' || $data_evento === '' || $destino === '') {
  json_response(['ok' => false, 'error' => 'Informe nome do evento, data e destino.'], 422);
}

// config padrão
$default = [
  'schema_version' => '1.0',
  'canvas' => ['width' => 1080, 'height' => 1920],
  'constraints' => [
    'nome_max_chars' => 26,
    'foto_formats' => ['jpg','jpeg','png'],
    'fundo_formats' => ['jpg','jpeg','png','bmp'],
  ],
  'layers' => [
    'background' => ['type' => 'gradient', 'gradient' => ['color_a' => '#0F172A', 'color_b' => '#2563EB', 'angle' => 90]],
    'title' => ['type' => 'text', 'text' => ['value' => $nome_evento, 'font_family' => 'Montserrat', 'font_size' => 72, 'font_weight' => 700, 'color' => '#FFFFFF', 'align' => 'center', 'x' => 540, 'y' => 180, 'rotate' => 0]],
    'photo_slot' => ['x' => 540, 'y' => 840, 'radius' => 340, 'border' => ['enabled' => true, 'color' => '#FFFFFF', 'width' => 10]],
    'name_bar' => ['x' => 120, 'y' => 1320, 'w' => 840, 'h' => 170, 'border_radius' => 18, 'fill' => ['color' => '#FFFFFF', 'opacity' => 0.92], 'stroke' => ['enabled' => false, 'color' => '#000000', 'width' => 2], 'shadow' => ['enabled' => false, 'blur' => 12, 'x' => 0, 'y' => 6, 'opacity' => 0.25]],
    'name_text' => ['font_family' => 'Montserrat', 'font_size' => 64, 'font_weight' => 800, 'color' => '#111111', 'align' => 'center', 'x' => 540, 'y' => 1435],
    'subtitle_text' => ['value' => 'Evento Oficial', 'font_family' => 'Montserrat', 'font_size' => 36, 'font_weight' => 600, 'color' => '#FFFFFF', 'align' => 'center', 'x' => 540, 'y' => 1530],
    'footer' => ['type' => 'text', 'align' => 'center', 'text' => ['value' => '', 'font_family' => 'Montserrat', 'font_size' => 28, 'font_weight' => 600, 'color' => '#FFFFFF', 'padding_x' => 80, 'y' => 1860]],
  ],
];

$token = bin2hex(random_bytes(8));
$cfg_json = json_encode($default, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

$st = $pdo->prepare('INSERT INTO eventos (token_publico, status, nome_evento, data_evento, destino, endereco, config_json, created_at, updated_at) VALUES (?,?,?,?,?,?,?,NOW(),NOW())');
$st->execute([$token, 'draft', $nome_evento, $data_evento, $destino, ($endereco !== '' ? $endereco : null), $cfg_json]);

$id = (int)$pdo->lastInsertId();
json_response(['ok' => true, 'id' => $id, 'token_publico' => $token, 'status' => 'draft']);
