<?php
require_once 'conexao.php';
session_start();


// === CSRF helper (multi-token, one-time use) ===
if (!isset($_SESSION['csrf_tokens']) || !is_array($_SESSION['csrf_tokens'])) {
    $_SESSION['csrf_tokens'] = [];
}
function csrf_gc($ttl = 7200) {
    $now = time();
    foreach ($_SESSION['csrf_tokens'] as $t => $ts) {
        if ($now - (int)$ts > $ttl) {
            unset($_SESSION['csrf_tokens'][$t]);
        }
    }
}
function csrf_issue($ttl = 7200) {
    csrf_gc($ttl);
    $token = bin2hex(random_bytes(32));
    $_SESSION['csrf_tokens'][$token] = time();
    return $token;
}
function csrf_validate($token, $ttl = 7200, $consume = true) {
    csrf_gc($ttl);
    if (!$token) return false;
    if (!isset($_SESSION['csrf_tokens'][$token])) return false;
    $age = time() - (int)$_SESSION['csrf_tokens'][$token];
    $ok = $age <= $ttl;
    // One-time use by default; if $consume is false, leave token for reuse until TTL
    if ($consume) {
        unset($_SESSION['csrf_tokens'][$token]);
    }
    return $ok && $age >= 0;
}
function csrf_header_token() {
    $headers = function_exists('getallheaders') ? getallheaders() : [];
    $token = $headers['X-CSRF-Token'] ?? $headers['X-Csrf-Token'] ?? ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? null);
    return $token;
}
// ================================================
header('Content-Type: application/json');

// Verificar CSRF token
$token = csrf_header_token();
if (!csrf_validate($token)) {
    die(json_encode(['status' => 'erro', 'mensagem' => 'Token CSRF inválido.']));
}

$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['id']) || !is_numeric($data['id'])) {
    die(json_encode(['status' => 'erro', 'mensagem' => 'ID inválido.']));
}

$id = (int) $data['id'];
$tenant_id = $_SESSION['tenant_id'] ?? null;

// Verificar permissão
$stmt = $conn->prepare("SELECT id FROM formularios WHERE id = ? AND tenant_id = ?");
$stmt->bind_param("ii", $id, $tenant_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    die(json_encode(['status' => 'erro', 'mensagem' => 'Formulário não encontrado.']));
}

// Excluir
$stmt = $conn->prepare("DELETE FROM formularios WHERE id = ? AND tenant_id = ?");
$stmt->bind_param("ii", $id, $tenant_id);

if ($stmt->execute()) {
    echo json_encode(['status' => 'sucesso', 'mensagem' => 'Formulário excluído.', 'csrf_token' => csrf_issue()]);
} else {
    echo json_encode(['status' => 'erro', 'mensagem' => 'Erro ao excluir.']);
}