<?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);
$d = requestJson();
$sessaoId = preg_replace('/[^a-f0-9]/', '', strtolower((string)($d['sessao_id'] ?? '')));
$token = preg_replace('/[^a-f0-9]/', '', strtolower((string)($d['safe_token'] ?? '')));
if (strlen($sessaoId) !== 48) jsonResponse(['ok'=>false,'erro'=>'Sessão inválida.'],422);
try {
    $match=afBuscarPartidaPorSessao($pdo,(int)$u['id'],$sessaoId);if(!$match)throw new RuntimeException('Partida não encontrada.');
    $feature=!empty($match['controlled_event_id'])?'controlled_event_farm':'camera';
    afMinorPolicyApiAssert($pdo,$u,$feature,!empty($match['controlled_event_id'])?['controlled_event_id'=>(int)$match['controlled_event_id']]:[]);
    $state=afSafeCameraRecord($pdo,(int)$u['id'],$sessaoId,$token,$d);
    jsonResponse(['ok'=>true,'safe_camera'=>afSafeCameraApiState($state)]);
} catch (Throwable $e) { jsonResponse(['ok'=>false,'erro'=>$e->getMessage()],422); }
