<?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 AND COALESCE(hidden, 0) = 0 AND COALESCE(tipo, '') <> 'warning' 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 = [];
    $arquivosAntigosParaExcluir = [];

    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)) {
                $file = isset($_FILES['campo_' . $campoId]) && is_array($_FILES['campo_' . $campoId]) ? $_FILES['campo_' . $campoId] : null;
                $hasUpload = is_array($file) && (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE);

                if ($hasUpload) {
                    $uploadMeta = validateUploadedFileForField($file, $tipo, ($campo['label'] ?? ('#' . $campoId)), 10 * 1024 * 1024);
                    $newName = uniqid('upload_', true) . '_' . $uploadMeta['safe_name'];
                    $destino = $uploadDir . $newName;

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

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

                    if (!empty($valorAtualBanco)) {
                        $arquivosAntigosParaExcluir[] = (string) $valorAtualBanco;
                    }
                } elseif ((int) ($campo['required'] ?? 0) === 1 && trim((string) $valorAtualBanco) === '') {
                    throw new RuntimeException('Envie o arquivo do campo ' . ($campo['label'] ?? ('#' . $campoId)) . '.');
                }
            } else {
                $postValue = $_POST['campo_' . $campoId] ?? null;
                if (is_array($postValue)) {
                    $items = normalizePostedArrayValues($postValue);
                    $opcoesValidas = splitOptions($campo['opcoes'] ?? null);
                    foreach ($items as $item) {
                        if ($opcoesValidas !== [] && !in_array($item, $opcoesValidas, true)) {
                            throw new RuntimeException('Opção inválida no campo ' . ($campo['label'] ?? ('#' . $campoId)) . '.');
                        }
                    }
                    $postValue = implode(', ', $items);
                } else {
                    $postValue = trim((string) $postValue);
                    $opcoesValidas = splitOptions($campo['opcoes'] ?? null);
                    if ($postValue !== '' && in_array($tipo, ['select', 'radio'], true) && $opcoesValidas !== [] && !in_array($postValue, $opcoesValidas, true)) {
                        throw new RuntimeException('Opção inválida no campo ' . ($campo['label'] ?? ('#' . $campoId)) . '.');
                    }
                }
                $novoValor = trim((string) $postValue);

                if ((int) ($campo['required'] ?? 0) === 1 && $novoValor === '') {
                    throw new RuntimeException('Preencha o campo ' . ($campo['label'] ?? ('#' . $campoId)) . '.');
                }

                if ($novoValor !== '') {
                    if ($tipo === 'email' && filter_var($novoValor, FILTER_VALIDATE_EMAIL) === false) {
                        throw new RuntimeException('E-mail inválido no campo ' . ($campo['label'] ?? ('#' . $campoId)) . '.');
                    }
                    if ($tipo === 'cpf' && !isValidCpf($novoValor)) {
                        throw new RuntimeException('CPF inválido no campo ' . ($campo['label'] ?? ('#' . $campoId)) . '.');
                    }
                    if ($tipo === 'cnpj' && !isValidCnpj($novoValor)) {
                        throw new RuntimeException('CNPJ inválido no campo ' . ($campo['label'] ?? ('#' . $campoId)) . '.');
                    }
                    if ($tipo === 'date') {
                        $normalizedDate = normalizeSubmittedDate($novoValor);
                        if ($normalizedDate === null) {
                            throw new RuntimeException('Data inválida no campo ' . ($campo['label'] ?? ('#' . $campoId)) . '.');
                        }
                        $novoValor = $normalizedDate;
                    }
                    if ($tipo === 'porcentagem') {
                        $numeric = str_replace(',', '.', $novoValor);
                        if (!is_numeric($numeric) || (float) $numeric < 0 || (float) $numeric > 100) {
                            throw new RuntimeException('Porcentagem inválida no campo ' . ($campo['label'] ?? ('#' . $campoId)) . '.');
                        }
                        $novoValor = (string) $numeric;
                    }
                    if ($tipo === 'number') {
                        $numeric = str_replace(',', '.', $novoValor);
                        if (!is_numeric($numeric)) {
                            throw new RuntimeException('Número inválido no campo ' . ($campo['label'] ?? ('#' . $campoId)) . '.');
                        }
                        $novoValor = (string) $numeric;
                    }
                }
            }

            $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();
        deleteStoredFiles($arquivosAntigosParaExcluir, __DIR__);
        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 = $e->getMessage() !== '' ? $e->getMessage() : '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', 'porcentagem'], true)): ?>
                        <input type="<?= $tipo === 'email' ? 'email' : ($tipo === 'date' ? 'date' : ($tipo === 'number' || $tipo === 'porcentagem' ? 'number' : 'text')) ?>" <?= $tipo === 'porcentagem' ? 'min="0" max="100" step="0.01"' : '' ?> 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 ?>" accept="<?= htmlspecialchars(getFileInputAccept($tipo), ENT_QUOTES, 'UTF-8') ?>" 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>
