<?php
require_once __DIR__ . '/../../_bootstrap.php';
require_once ROOT_PATH . '/includes/match_functions.php';
require_once ROOT_PATH . '/includes/viral_functions.php';
$u=afApiOuSessaoUsuario($pdo,'challenge');
if($_SERVER['REQUEST_METHOD']!=='POST')jsonResponse(['ok'=>false,'erro'=>'Método não permitido.'],405);
afValidarCsrfApi();
$d=requestJson();
try{
  $desafio=afCriarDesafioViral($pdo,(int)$u['id'],max(0,(int)($d['partida_id']??0)),sanitize((string)($d['template']??'neon')));
  jsonResponse(['ok'=>true,'desafio'=>[
    'id'=>(int)$desafio['id'],'token'=>$desafio['token'],'status'=>$desafio['status'],'alvo'=>(float)$desafio['alvo_pontuacao'],
    'url'=>SITE_URL.'/pages/desafio.php?t='.$desafio['token'],'expira_em'=>$desafio['expira_em']
  ]]);
}catch(Throwable $e){jsonResponse(['ok'=>false,'erro'=>$e->getMessage()],422);}
