<?php
include "header.php";
include "db.php";

// Criar pesquisa
if (isset($_POST['criar'])) {
    $nome = $_POST['nome'];
    $stmt = $pdo->prepare("INSERT INTO pesquisas (nome) VALUES (:nome)");
    $stmt->execute(['nome' => $nome]);
    header("Location: pesquisas.php");
    exit;
}

// Excluir pesquisa
if (isset($_GET['delete'])) {
    $id = (int) $_GET['delete'];
    $pdo->query("DELETE FROM pesquisas WHERE id = $id");
    header("Location: pesquisas.php");
    exit;
}

// Buscar todas
$stmt = $pdo->query("SELECT * FROM pesquisas ORDER BY id DESC");
$pesquisas = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<button onclick="document.getElementById('modal').classList.remove('hidden')"
  class="mb-6 bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700">
  Criar Pesquisa
</button>

<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<?php foreach ($pesquisas as $p): ?>
  <div class="bg-white p-6 rounded-xl shadow flex flex-col gap-2">
    <h3 class="font-semibold text-lg"><?= htmlspecialchars($p['nome']) ?></h3>
    <div class="flex gap-2 mt-2">
    <a href="pesquisa_view.php?id=<?= $p['id'] ?>" class="px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600">Ver</a>      
    <a href="pesquisa_resultados.php?id=<?= $p['id'] ?>"
       class="px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-700">
       Resultados
    </a>
    <a href="pesquisa_edit.php?id=<?= $p['id'] ?>" class="px-3 py-1 bg-yellow-400 rounded hover:bg-yellow-500">Editar</a>
      <a href="?delete=<?= $p['id'] ?>"
         onclick="return confirm('Excluir <?= htmlspecialchars($p['nome']) ?>?')"
         class="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600">
         Excluir
      </a>
    </div>
  </div>
<?php endforeach; ?>
</div>

<!-- Modal -->
<div id="modal" class="hidden fixed inset-0 flex items-center justify-center bg-black/50">
  <div class="bg-white p-6 rounded-xl shadow-lg w-96">
    <h2 class="text-xl font-bold mb-4">Nova Pesquisa</h2>
    <form method="post" class="space-y-4">
      <input type="text" name="nome" placeholder="Nome da pesquisa" required
        class="w-full p-2 border rounded">
      <div class="flex justify-end gap-2">
        <button type="button" onclick="document.getElementById('modal').classList.add('hidden')"
          class="px-4 py-2 bg-gray-300 rounded">Cancelar</button>
        <button type="submit" name="criar"
          class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700">Salvar</button>
      </div>
    </form>
  </div>
</div>

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