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

$pesquisa_id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
if ($pesquisa_id <= 0) {
    die('Pesquisa não encontrada.');
}

$stmt = $pdo->prepare('SELECT * FROM pesquisas WHERE id = :id');
$stmt->execute(array('id' => $pesquisa_id));
$pesquisa = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$pesquisa) {
    die('Pesquisa não existe.');
}

$tipos = array(
    'text' => 'Texto',
    'textarea' => 'Área de Texto',
    'number' => 'Número',
    'email' => 'E-mail',
    'select' => 'Select (lista)',
    'checkbox' => 'Checkbox',
    'radio' => 'Radio',
);

$feedback = array('type' => '', 'message' => '');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string) ($_POST['action'] ?? ''));
    try {
        if ($action === 'adicionar') {
            $label = truncateText(trim((string) ($_POST['label'] ?? '')), 150);
            $tipo = trim((string) ($_POST['tipo'] ?? 'text'));
            $opcoes = trim((string) ($_POST['opcoes'] ?? ''));

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

            $stmt = $pdo->prepare('INSERT INTO pesquisa_campos (pesquisa_id, label, tipo, opcoes) VALUES (:pid, :label, :tipo, :opcoes)');
            $stmt->execute(array(
                'pid' => $pesquisa_id,
                'label' => $label,
                'tipo' => $tipo,
                'opcoes' => $opcoes !== '' ? $opcoes : null,
            ));
            header('Location: pesquisa_edit.php?id=' . $pesquisa_id . '&saved=1');
            exit;
        }
    } catch (Throwable $e) {
        $feedback = array('type' => 'error', 'message' => $e->getMessage() !== '' ? $e->getMessage() : 'Não foi possível salvar o campo.');
    }
}

if (isset($_GET['saved']) && $_GET['saved'] === '1') {
    $feedback = array('type' => 'success', 'message' => 'Campo adicionado com sucesso.');
}

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

$pageTitle = 'Editar pesquisa | Motion Fit';
include 'header.php';
?>

<div class="mx-auto max-w-4xl 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 Pesquisa</h1>
      <p class="text-sm text-slate-500"><?= htmlspecialchars((string) $pesquisa['nome'], ENT_QUOTES, 'UTF-8') ?></p>
    </div>
    <div class="flex gap-2">
      <a href="pesquisas.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="pesquisa_view.php?id=<?= $pesquisa_id ?>" target="_blank" class="rounded-2xl bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700">Abrir pesquisa</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="adicionar">
    <h2 class="mb-4 text-xl font-bold text-slate-900">Adicionar 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" 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') ?>"><?= 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" 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-emerald-600 px-4 py-3 text-sm font-semibold text-white hover:bg-emerald-700">Adicionar campo</button>
  </form>

  <section class="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
    <div class="mb-4 flex items-center justify-between gap-3">
      <h2 class="text-xl font-bold text-slate-900">Campos adicionados</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 criado ainda.</div>
    <?php else: ?>
      <div class="space-y-3">
        <?php foreach ($campos as $c): ?>
          <div class="flex flex-col justify-between gap-3 rounded-2xl border border-slate-200 p-4 sm:flex-row sm:items-center">
            <div>
              <div class="font-semibold text-slate-900"><?= htmlspecialchars((string) $c['label'], ENT_QUOTES, 'UTF-8') ?></div>
              <div class="mt-1 text-sm text-slate-500">Tipo: <?= htmlspecialchars((string) $c['tipo'], ENT_QUOTES, 'UTF-8') ?></div>
              <?php if (!empty($c['opcoes'])): ?>
                <div class="mt-1 text-xs text-slate-500">Opções: <?= htmlspecialchars((string) $c['opcoes'], ENT_QUOTES, 'UTF-8') ?></div>
              <?php endif; ?>
            </div>
            <form method="post" action="pesquisa_campo_delete.php" onsubmit="return confirm('Excluir o campo <?= htmlspecialchars(addslashes((string) $c['label']), ENT_QUOTES, 'UTF-8') ?>?');">
              <input type="hidden" name="id" value="<?= (int) $c['id'] ?>">
              <input type="hidden" name="pid" value="<?= $pesquisa_id ?>">
              <button type="submit" class="rounded-2xl bg-red-50 px-4 py-2 text-sm font-semibold text-red-600 hover:bg-red-100">Excluir</button>
            </form>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </section>
</div>

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