<?php
include 'auth.php';
include 'db.php';

$formularioId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
if ($formularioId <= 0) {
    die('Formulário não especificado.');
}

try {
    $pdo->beginTransaction();

    $stmtArquivos = $pdo->prepare(
        "SELECT frc.valor
         FROM formulario_respostas_campos frc
         INNER JOIN formulario_campos fc ON fc.id = frc.campo_id
         WHERE fc.formulario_id = :fid
           AND fc.tipo IN ('file', 'image')
           AND frc.valor IS NOT NULL
           AND frc.valor <> ''"
    );
    $stmtArquivos->execute(['fid' => $formularioId]);
    $arquivos = $stmtArquivos->fetchAll(PDO::FETCH_COLUMN);

    $stmt = $pdo->prepare('DELETE FROM formulario_respostas_campos WHERE campo_id IN (SELECT id FROM formulario_campos WHERE formulario_id = :fid)');
    $stmt->execute(['fid' => $formularioId]);

    $stmt = $pdo->prepare('DELETE FROM formulario_respostas WHERE formulario_id = :fid');
    $stmt->execute(['fid' => $formularioId]);

    $stmt = $pdo->prepare('DELETE FROM formulario_campos WHERE formulario_id = :fid');
    $stmt->execute(['fid' => $formularioId]);

    $stmt = $pdo->prepare('DELETE FROM formularios WHERE id = :fid');
    $stmt->execute(['fid' => $formularioId]);

    $pdo->commit();

    foreach ($arquivos as $arquivo) {
        $arquivo = ltrim((string) $arquivo, '/');
        $filePath = __DIR__ . '/' . $arquivo;
        if (is_file($filePath)) {
            @unlink($filePath);
        }
    }
} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    die('Erro ao excluir formulário.');
}

header('Location: formularios.php');
exit;
