<?php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors','1');
ini_set('log_errors','1');
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');

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

/* === Anti-cache forte (browser, proxy e CDN) === */
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
header('Surrogate-Control: no-store');
header('X-Accel-Expires: 0'); // Nginx (se houver)

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

require_once __DIR__.'/../inc/spin_lib.php';

// ✅ LOG DE INÍCIO
error_log("🔄 SPIN_ACK - Iniciando processamento ACK");

// aceita JSON ou form-urlencoded
$in = json_decode(file_get_contents('php://input'), true);
if (!is_array($in)) $in = $_POST;

$spinId = isset($in['id']) ? (int)$in['id'] : (isset($in['spin_id']) ? (int)$in['spin_id'] : 0);
$nonce  = (string)($in['nonce'] ?? '');
$hmac   = (string)($in['hmac']  ?? '');

error_log("🔄 SPIN_ACK - Dados recebidos: spinId={$spinId}, nonce={$nonce}, hmac=" . substr($hmac, 0, 8) . "...");

if(!$spinId || !$nonce || !$hmac){
  error_log("❌ SPIN_ACK - Parâmetros faltando: spinId={$spinId}, nonce={$nonce}, hmac=" . ($hmac ? 'presente' : 'ausente'));
  http_response_code(400);
  echo json_encode(['ok'=>false, 'message'=>'missing params']);
  exit;
}

// ✅ LOG ANTES DO PROCESSAMENTO
error_log("🔄 SPIN_ACK - Processando ACK para spinId: {$spinId}");

// spin_ack.php - Verificar se está funcionando
$result = ackSpin($pdo, $spinId, $nonce, $hmac);
error_log("🔄 SPIN_ACK - SpinID: {$spinId}, Success: " . ($result ? 'true' : 'false'));

// Log de confirmação
error_log("✅ SPIN_ACK - SpinID: {$spinId} - Success: " . ($result ? 'true' : 'false'));

echo json_encode(['ok'=>$result]);