<?php
header('Content-Type: application/json; charset=utf-8');

function json_exit($arr, $code = 200) {
  http_response_code($code);
  echo json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  json_exit([
    "status" => "alertanao",
    "message" => "<p class='alertanao'>Método inválido.<span><i class='fas fa-times'></i></span></p>"
  ], 405);
}

session_name('adm_session');
session_start();

require_once '../../../includes/db.php';
require_once 'auth_ajax_adm.php';

// CSRF
if (
  empty($_POST['csrf_token']) ||
  empty($_SESSION['csrf_token_ticker_partidas']) ||
  !hash_equals($_SESSION['csrf_token_ticker_partidas'], $_POST['csrf_token'])
) {
  json_exit([
    "status" => "alertanao",
    "message" => "<p class='alertanao'>Falha de segurança (CSRF).<span><i class='fas fa-times'></i></span></p>"
  ], 400);
}

// ===== CAMPOS (AJUSTAR CONFORME TABELA)
$titulo = trim($_POST['titulo'] ?? '');

if ($titulo === '') {
  json_exit([
    "status" => "alertanao",
    "message" => "<p class='alertanao'>Título inválido.<span><i class='fas fa-times'></i></span></p>"
  ], 400);
}

try {
  $stmt = $pdo->prepare("
    UPDATE ticker_partidas
    SET titulo = :titulo
    WHERE id = 1
  ");
  $stmt->execute([
    ':titulo' => $titulo
  ]);

  $_SESSION['csrf_token_ticker_partidas'] = bin2hex(random_bytes(32));

  json_exit([
    "status"   => "alertasim",
    "message"  => "<p class='alertasim'>Ticker atualizado!<span><i class='fas fa-check'></i></span></p>",
    "new_csrf" => $_SESSION['csrf_token_ticker_partidas']
  ]);

} catch (Exception $e) {
  json_exit([
    "status" => "alertanao",
    "message" => "<p class='alertanao'>Erro: ".$e->getMessage()."<span><i class='fas fa-times'></i></span></p>"
  ], 500);
}
