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

function redirectFormularioEdit($formularioId, $extra = array())
{
    $params = array_merge(array('id' => (int) $formularioId), $extra);
    header('Location: formulario_edit.php?' . http_build_query($params));
    exit;
}

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

$feedback = array('type' => '', 'message' => '');
$novo_label = '';
$novo_tipo = 'text';
$novo_opcoes = '';

$stmt = $pdo->prepare('SELECT * FROM formularios WHERE id = :id');
$stmt->execute(array('id' => $formulario_id));
$formulario = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$formulario) {
    die('Formulário não existe.');
}

$tipos = array(
    'text' => 'Texto',
    'textarea' => 'Área de Texto',
    'number' => 'Número',
    'email' => 'E-mail',
    'select' => 'Select',
    'checkbox' => 'Checkbox',
    'radio' => 'Radio',
    'file' => 'Arquivo',
    'image' => 'Imagem',
    'warning' => 'Aviso',
    'cpf' => 'CPF',
    'telefone' => 'Telefone',
    'cep' => 'CEP',
    'date' => 'Data',
    'rg' => 'RG',
    'cnpj' => 'CNPJ',
    'porcentagem' => 'Porcentagem',
);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string) ($_POST['action'] ?? ''));

    try {
        if ($action === 'atualizar_formulario') {
            $nome = truncateText(normalizeSearchTerm(isset($_POST['nome']) ? $_POST['nome'] : ''), 150);
            if ($nome === '') {
                throw new RuntimeException('Informe o nome do formulário.');
            }
            $stmt = $pdo->prepare('UPDATE formularios SET nome = :nome WHERE id = :id');
            $stmt->execute(array('nome' => $nome, 'id' => $formulario_id));
            redirectFormularioEdit($formulario_id, array('saved' => '1'));
        }

        if ($action === 'adicionar') {
            $label = truncateText(trim((string) ($_POST['label'] ?? '')), 150);
            $tipo = trim((string) ($_POST['tipo'] ?? 'text'));
            $opcoes = trim((string) ($_POST['opcoes'] ?? ''));
            $novo_label = $label;
            $novo_tipo = $tipo;
            $novo_opcoes = $opcoes;

            if ($label === '' || !isset($tipos[$tipo])) {
                throw new RuntimeException('Preencha os dados do novo campo corretamente.');
            }

            $stmt = $pdo->prepare('INSERT INTO formulario_campos (formulario_id, label, tipo, opcoes) VALUES (:fid, :label, :tipo, :opcoes)');
            $stmt->execute(array(
                'fid' => $formulario_id,
                'label' => $label,
                'tipo' => $tipo,
                'opcoes' => $opcoes !== '' ? $opcoes : null,
            ));
            redirectFormularioEdit($formulario_id, array('saved' => '1'));
        }

        if ($action === 'atualizar_campos') {
            $camposInput = isset($_POST['campo']) && is_array($_POST['campo']) ? $_POST['campo'] : array();
            $pdo->beginTransaction();
            foreach ($camposInput as $id => $data) {
                $id = (int) $id;
                $label = truncateText(trim((string) ($data['label'] ?? '')), 150);
                $tipo = trim((string) ($data['tipo'] ?? 'text'));
                $opcoes = trim((string) ($data['opcoes'] ?? ''));

                if ($id <= 0 || $label === '' || !isset($tipos[$tipo])) {
                    throw new RuntimeException('Há campos inválidos na atualização.');
                }

                $stmt = $pdo->prepare('UPDATE formulario_campos SET label = :label, tipo = :tipo, opcoes = :opcoes WHERE id = :id AND formulario_id = :fid');
                $stmt->execute(array(
                    'label' => $label,
                    'tipo' => $tipo,
                    'opcoes' => $opcoes !== '' ? $opcoes : null,
                    'id' => $id,
                    'fid' => $formulario_id,
                ));
            }
            $pdo->commit();
            redirectFormularioEdit($formulario_id, array('saved' => '1'));
        }
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $feedback = array('type' => 'error', 'message' => $e->getMessage() !== '' ? $e->getMessage() : 'Não foi possível salvar as alterações.');
    }
}

if (isset($_GET['saved']) && $_GET['saved'] === '1') {
    $feedback = array('type' => 'success', 'message' => 'Alterações salvas com sucesso.');
}

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

$pageTitle = 'Editar formulário | Motion Fit';
include 'header.php';
?>

<div class="mx-auto max-w-5xl py-2">
  <div class="mb-6 flex flex-wrap items-center justify-between gap-3">
    <div>
      <h1 class="text-2xl font-bold text-slate-900">Editar Formulário</h1>
      <p class="text-sm text-slate-500"><?= htmlspecialchars((string) $formulario['nome'], ENT_QUOTES, 'UTF-8') ?></p>
    </div>
    <div class="flex gap-2">
      <a href="formularios.php" class="rounded-2xl border border-slate-300 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50">Voltar</a>
      <a href="formulario_view.php?id=<?= $formulario_id ?>" target="_blank" class="rounded-2xl bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700">Abrir formulário</a>
    </div>
  </div>

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

  <form method="post" class="mb-6 rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
    <input type="hidden" name="action" value="atualizar_formulario">
    <label class="mb-2 block text-sm font-semibold text-slate-700">Nome do formulário</label>
    <div class="flex flex-col gap-3 sm:flex-row">
      <input type="text" name="nome" value="<?= htmlspecialchars((string) $formulario['nome'], ENT_QUOTES, 'UTF-8') ?>" maxlength="150" required class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
      <button type="submit" class="rounded-2xl bg-blue-600 px-4 py-3 text-sm font-semibold text-white hover:bg-blue-700">Atualizar nome</button>
    </div>
  </form>

  <form method="post" class="mb-6 rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
    <input type="hidden" name="action" value="atualizar_campos">
    <div class="mb-4 flex items-center justify-between gap-3">
      <h2 class="text-xl font-bold text-slate-900">Campos existentes</h2>
      <span class="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-600"><?= count($campos) ?> item(ns)</span>
    </div>

    <?php if (!$campos): ?>
      <div class="rounded-2xl border border-dashed border-slate-300 bg-slate-50 p-6 text-sm text-slate-500">Nenhum campo cadastrado ainda.</div>
    <?php else: ?>
      <div class="space-y-4">
        <?php foreach ($campos as $c): ?>
          <div class="rounded-2xl border border-slate-200 p-4">
            <div class="grid gap-3 xl:grid-cols-[minmax(0,1.3fr)_220px_minmax(0,1fr)_auto] xl:items-start">
              <input type="text" name="campo[<?= (int) $c['id'] ?>][label]" value="<?= htmlspecialchars((string) $c['label'], ENT_QUOTES, 'UTF-8') ?>" required class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
              <select name="campo[<?= (int) $c['id'] ?>][tipo]" required class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
                <?php foreach ($tipos as $k => $v): ?>
                  <option value="<?= htmlspecialchars($k, ENT_QUOTES, 'UTF-8') ?>" <?= $k === (string) $c['tipo'] ? 'selected' : '' ?>><?= htmlspecialchars($v, ENT_QUOTES, 'UTF-8') ?></option>
                <?php endforeach; ?>
              </select>
              <input type="text" name="campo[<?= (int) $c['id'] ?>][opcoes]" value="<?= htmlspecialchars((string) ($c['opcoes'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" placeholder="Opções separadas por vírgula" class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
              <div>
                <input type="hidden" name="delete_id[<?= (int) $c['id'] ?>]" value="<?= (int) $c['id'] ?>">
                <button type="submit" name="id" value="<?= (int) $c['id'] ?>" formaction="campo_delete.php" formmethod="post" formnovalidate onclick="return confirm('Excluir o campo <?= htmlspecialchars(addslashes((string) $c['label']), ENT_QUOTES, 'UTF-8') ?>?');" class="w-full rounded-2xl bg-red-50 px-4 py-3 text-sm font-semibold text-red-600 hover:bg-red-100">Excluir</button>
                <input type="hidden" name="fid" value="<?= $formulario_id ?>">
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
      <button type="submit" class="mt-4 rounded-2xl bg-emerald-600 px-4 py-3 text-sm font-semibold text-white hover:bg-emerald-700">Salvar alterações</button>
    <?php endif; ?>
  </form>

  <form method="post" class="mb-6 rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
    <input type="hidden" name="action" value="adicionar">
    <h2 class="mb-4 text-xl font-bold text-slate-900">Adicionar novo campo</h2>
    <div class="grid gap-3 md:grid-cols-2">
      <div class="md:col-span-2">
        <label class="mb-2 block text-sm font-semibold text-slate-700">Nome do campo</label>
        <input type="text" name="label" value="<?= htmlspecialchars($novo_label, ENT_QUOTES, 'UTF-8') ?>" maxlength="150" required class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
      </div>
      <div>
        <label class="mb-2 block text-sm font-semibold text-slate-700">Tipo</label>
        <select name="tipo" required class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
          <?php foreach ($tipos as $k => $v): ?>
            <option value="<?= htmlspecialchars($k, ENT_QUOTES, 'UTF-8') ?>" <?= $k === $novo_tipo ? 'selected' : '' ?>><?= htmlspecialchars($v, ENT_QUOTES, 'UTF-8') ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label class="mb-2 block text-sm font-semibold text-slate-700">Opções</label>
        <input type="text" name="opcoes" value="<?= htmlspecialchars($novo_opcoes, ENT_QUOTES, 'UTF-8') ?>" placeholder="Opções separadas por vírgula" class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
      </div>
    </div>
    <button type="submit" class="mt-4 rounded-2xl bg-blue-600 px-4 py-3 text-sm font-semibold text-white hover:bg-blue-700">Adicionar campo</button>
  </form>

  <div class="rounded-3xl border border-red-200 bg-white p-5 shadow-sm">
    <h2 class="text-xl font-bold text-slate-900">Zona de perigo</h2>
    <p class="mt-2 text-sm text-slate-500">Apaga o formulário, os campos, as respostas e os uploads vinculados.</p>
    <form method="post" action="formulario_delete.php" class="mt-4" onsubmit="return confirm('Excluir este formulário e tudo que está vinculado a ele?');">
      <input type="hidden" name="id" value="<?= $formulario_id ?>">
      <button type="submit" class="rounded-2xl bg-red-600 px-4 py-3 text-sm font-semibold text-white hover:bg-red-700">Excluir formulário</button>
    </form>
  </div>
</div>

<?php include 'footer.php'; ?>
