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

$respostaId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
if ($respostaId <= 0) {
    die('ID inválido!');
}

$stmt = $pdo->prepare('SELECT * FROM formulario_respostas WHERE id = :id');
$stmt->execute(['id' => $respostaId]);
$resposta = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$resposta) {
    die('Resposta não encontrada!');
}

$formId = (int) $resposta['formulario_id'];

$stmt = $pdo->prepare('SELECT * FROM formulario_campos WHERE formulario_id = :form_id ORDER BY id ASC');
$stmt->execute(['form_id' => $formId]);
$campos = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

$stmt = $pdo->prepare('SELECT * FROM formulario_respostas_campos WHERE resposta_id = :resposta_id');
$stmt->execute(['resposta_id' => $respostaId]);
$valores = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

$valoresPorCampo = [];
foreach ($valores as $valor) {
    $valoresPorCampo[(int) $valor['campo_id']] = $valor['valor'];
}

$uploadDir = __DIR__ . '/uploads/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$erro = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $novosUploads = [];

    try {
        $pdo->beginTransaction();

        foreach ($campos as $campo) {
            if ((string) ($campo['tipo'] ?? '') === 'warning') {
                continue;
            }

            $campoId = (int) $campo['id'];
            $tipo = (string) ($campo['tipo'] ?? 'text');
            $valorAtualBanco = $valoresPorCampo[$campoId] ?? null;
            $novoValor = $valorAtualBanco;

            if (in_array($tipo, ['image', 'file'], true)) {
                if (isset($_FILES['campo_' . $campoId]) && (int) ($_FILES['campo_' . $campoId]['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_OK) {
                    $file = $_FILES['campo_' . $campoId];
                    $ext = strtolower((string) pathinfo((string) $file['name'], PATHINFO_EXTENSION));
                    $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'pdf', 'doc', 'docx'];

                    if (!in_array($ext, $allowed, true)) {
                        throw new RuntimeException('Arquivo inválido enviado no campo ' . ($campo['label'] ?? ('#' . $campoId)) . '.');
                    }

                    $safeName = preg_replace('/[^a-zA-Z0-9._-]/', '', (string) $file['name']) ?: ('arquivo.' . $ext);
                    $newName = uniqid('upload_', true) . '_' . $safeName;
                    $destino = $uploadDir . $newName;

                    if (!move_uploaded_file((string) $file['tmp_name'], $destino)) {
                        throw new RuntimeException('Falha ao salvar o arquivo do campo ' . ($campo['label'] ?? ('#' . $campoId)) . '.');
                    }

                    $novosUploads[] = $destino;
                    $novoValor = 'uploads/' . $newName;

                    if (!empty($valorAtualBanco)) {
                        $antigo = resolveStoredLocalFilePath((string) $valorAtualBanco, __DIR__);
                        if ($antigo !== null && is_file($antigo)) {
                            @unlink($antigo);
                        }
                    }
                }
            } else {
                $postValue = $_POST['campo_' . $campoId] ?? null;
                if (is_array($postValue)) {
                                        $items = array();
                    foreach ($postValue as $item) {
                        $item = trim((string) $item);
                        if ($item !== '') {
                            $items[] = $item;
                        }
                    }
                    $postValue = implode(', ', array_values($items));
                }
                $novoValor = trim((string) $postValue);
            }

            $stmtExists = $pdo->prepare('SELECT id FROM formulario_respostas_campos WHERE resposta_id = :resposta_id AND campo_id = :campo_id LIMIT 1');
            $stmtExists->execute([
                'resposta_id' => $respostaId,
                'campo_id' => $campoId,
            ]);
            $existingId = (int) ($stmtExists->fetchColumn() ?: 0);

            if ($existingId > 0) {
                $stmtUpdate = $pdo->prepare('UPDATE formulario_respostas_campos SET valor = :valor WHERE id = :id');
                $stmtUpdate->execute([
                    'valor' => $novoValor !== '' ? $novoValor : null,
                    'id' => $existingId,
                ]);
            } else {
                $stmtInsert = $pdo->prepare('INSERT INTO formulario_respostas_campos (resposta_id, campo_id, valor) VALUES (:resposta_id, :campo_id, :valor)');
                $stmtInsert->execute([
                    'resposta_id' => $respostaId,
                    'campo_id' => $campoId,
                    'valor' => $novoValor !== '' ? $novoValor : null,
                ]);
            }
        }

        $pdo->commit();
        header('Location: formulario_Resposta.php?id=' . $formId);
        exit;
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        foreach ($novosUploads as $filePath) {
            if (is_file($filePath)) {
                @unlink($filePath);
            }
        }
        $erro = 'Erro ao salvar a resposta.';
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Editar Resposta</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="icon" type="image/png" href="img/Logo.png">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/inputmask/5.0.8/inputmask.min.js"></script>
</head>
<body class="bg-gray-100 min-h-screen p-6">
    <div class="mx-auto max-w-4xl rounded-3xl bg-white p-6 shadow-xl">
        <div class="mb-6 flex items-center justify-between gap-3">
            <div>
                <h1 class="text-2xl font-bold text-slate-900">Editar resposta</h1>
                <p class="text-sm text-slate-500">Ajuste os dados e salve quando terminar.</p>
            </div>
            <a href="formulario_Resposta.php?id=<?= $formId ?>" class="rounded-2xl border border-slate-300 px-4 py-2 font-semibold text-slate-700 hover:bg-slate-50">Voltar</a>
        </div>

        <?php if ($erro !== ''): ?>
            <div class="mb-4 rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700"><?= htmlspecialchars($erro, ENT_QUOTES, 'UTF-8') ?></div>
        <?php endif; ?>

        <form method="post" enctype="multipart/form-data" class="space-y-4">
            <?php foreach ($campos as $campo): ?>
                <?php if (($campo['tipo'] ?? '') === 'warning') continue; ?>
                <?php
                    $campoId = (int) $campo['id'];
                    $tipo = (string) ($campo['tipo'] ?? 'text');
                    $valor = (string) ($valoresPorCampo[$campoId] ?? '');
                    $opcoes = splitOptions($campo['opcoes'] ?? null);
                    $selecionados = array_map('trim', $valor !== '' ? explode(',', $valor) : []);
                ?>
                <div class="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                    <label class="mb-2 block font-semibold text-slate-700"><?= htmlspecialchars((string) ($campo['label'] ?? 'Campo'), ENT_QUOTES, 'UTF-8') ?></label>

                    <?php if (in_array($tipo, ['text', 'email', 'date', 'cpf', 'cnpj', 'telefone', 'cep', 'rg', 'number'], true)): ?>
                        <input type="<?= $tipo === 'email' ? 'email' : ($tipo === 'date' ? 'date' : ($tipo === 'number' ? 'number' : 'text')) ?>" name="campo_<?= $campoId ?>" value="<?= htmlspecialchars($valor, ENT_QUOTES, 'UTF-8') ?>" class="w-full rounded-2xl border border-slate-300 p-3">
                    <?php elseif ($tipo === 'textarea'): ?>
                        <textarea name="campo_<?= $campoId ?>" rows="4" class="w-full rounded-2xl border border-slate-300 p-3"><?= htmlspecialchars($valor, ENT_QUOTES, 'UTF-8') ?></textarea>
                    <?php elseif ($tipo === 'select'): ?>
                        <select name="campo_<?= $campoId ?>" class="w-full rounded-2xl border border-slate-300 p-3">
                            <option value="">Selecione</option>
                            <?php foreach ($opcoes as $op): ?>
                                <option value="<?= htmlspecialchars($op, ENT_QUOTES, 'UTF-8') ?>" <?= $valor === $op ? 'selected' : '' ?>><?= htmlspecialchars($op, ENT_QUOTES, 'UTF-8') ?></option>
                            <?php endforeach; ?>
                        </select>
                    <?php elseif ($tipo === 'radio'): ?>
                        <div class="flex flex-wrap gap-3">
                            <?php foreach ($opcoes as $op): ?>
                                <label class="flex items-center gap-2"><input type="radio" name="campo_<?= $campoId ?>" value="<?= htmlspecialchars($op, ENT_QUOTES, 'UTF-8') ?>" <?= $valor === $op ? 'checked' : '' ?>> <span><?= htmlspecialchars($op, ENT_QUOTES, 'UTF-8') ?></span></label>
                            <?php endforeach; ?>
                        </div>
                    <?php elseif ($tipo === 'checkbox'): ?>
                        <div class="flex flex-wrap gap-3">
                            <?php foreach ($opcoes as $op): ?>
                                <label class="flex items-center gap-2"><input type="checkbox" name="campo_<?= $campoId ?>[]" value="<?= htmlspecialchars($op, ENT_QUOTES, 'UTF-8') ?>" <?= in_array($op, $selecionados, true) ? 'checked' : '' ?>> <span><?= htmlspecialchars($op, ENT_QUOTES, 'UTF-8') ?></span></label>
                            <?php endforeach; ?>
                        </div>
                    <?php elseif (in_array($tipo, ['image', 'file'], true)): ?>
                        <?php if ($valor !== ''): ?>
                            <div class="mb-2 text-sm text-slate-600">Atual: <a href="<?= htmlspecialchars($valor, ENT_QUOTES, 'UTF-8') ?>" target="_blank" class="text-blue-600 hover:underline"><?= htmlspecialchars(storedFileDisplayName($valor), ENT_QUOTES, 'UTF-8') ?></a></div>
                        <?php endif; ?>
                        <input type="file" name="campo_<?= $campoId ?>" class="w-full rounded-2xl border border-slate-300 p-3">
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>

            <div class="flex justify-end gap-2">
                <a href="formulario_Resposta.php?id=<?= $formId ?>" class="rounded-2xl border border-slate-300 px-4 py-3 font-semibold text-slate-700 hover:bg-slate-50">Cancelar</a>
                <button type="submit" class="rounded-2xl bg-blue-600 px-4 py-3 font-semibold text-white hover:bg-blue-700">Salvar</button>
            </div>
        </form>
    </div>
</body>
</html>
