<?php
require_once __DIR__ . '/../../_bootstrap.php';
require_once ROOT_PATH . '/includes/match_functions.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') jsonResponse(['ok'=>false,'erro'=>'Método não permitido.'],405);
afValidarCsrfApi();
$u = afApiOuSessaoUsuario($pdo,'farm');
$d = requestJson();
$sessaoId = preg_replace('/[^a-f0-9]/', '', strtolower((string)($d['sessao_id'] ?? '')));
$safeToken = preg_replace('/[^a-f0-9]/', '', strtolower((string)($d['safe_token'] ?? '')));
if (strlen($sessaoId) !== 48) jsonResponse(['ok'=>false,'erro'=>'Sessão inválida.'],422);
try {
    $p = afCancelarPartida($pdo, (int)$u['id'], $sessaoId);
    afSafeCameraClose($pdo,(int)$u['id'],$sessaoId,$safeToken,'cancelled');
    jsonResponse(['ok'=>true,'partida'=>afPartidaPublica($p,$pdo),'redirect'=>SITE_URL.'/pages/farmar.php']);
} catch (Throwable $e) {
    jsonResponse(['ok'=>false,'erro'=>$e->getMessage()],422);
}
