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

function redirectPesquisas($query = array())
{
    $url = 'pesquisas.php';
    if (!empty($query)) {
        $url .= '?' . http_build_query($query);
    }
    header('Location: ' . $url);
    exit;
}

function currentPesquisaListQuery($source)
{
    $query = array();
    $busca = normalizeSearchTerm(isset($source['busca']) ? $source['busca'] : '');
    if ($busca !== '') {
        $query['busca'] = $busca;
    }
    return $query;
}

$feedback = array('type' => '', 'message' => '', 'open_modal' => false);
$modalNome = '';

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

    try {
        if ($action === 'criar') {
            $nome = truncateText(normalizeSearchTerm(isset($_POST['nome']) ? $_POST['nome'] : ''), 150);
            $modalNome = $nome;
            if ($nome === '') {
                throw new RuntimeException('Informe o nome da pesquisa.');
            }

            $stmt = $pdo->prepare('INSERT INTO pesquisas (nome) VALUES (:nome)');
            $stmt->execute(array('nome' => $nome));
            redirectPesquisas($returnQuery);
        }

        if ($action === 'delete') {
            $id = (int) ($_POST['id'] ?? 0);
            if ($id <= 0) {
                throw new RuntimeException('Pesquisa inválida para exclusão.');
            }

            $stmt = $pdo->prepare('SELECT id FROM pesquisas WHERE id = :id');
            $stmt->execute(array('id' => $id));
            if (!$stmt->fetchColumn()) {
                throw new RuntimeException('Pesquisa não encontrada.');
            }

            $pdo->beginTransaction();
            $stmt = $pdo->prepare('DELETE FROM pesquisa_respostas_campos WHERE resposta_id IN (SELECT id FROM pesquisa_respostas WHERE pesquisa_id = :id)');
            $stmt->execute(array('id' => $id));
            $stmt = $pdo->prepare('DELETE FROM pesquisa_respostas WHERE pesquisa_id = :id');
            $stmt->execute(array('id' => $id));
            $stmt = $pdo->prepare('DELETE FROM pesquisa_campos WHERE pesquisa_id = :id');
            $stmt->execute(array('id' => $id));
            $stmt = $pdo->prepare('DELETE FROM pesquisas WHERE id = :id');
            $stmt->execute(array('id' => $id));
            $pdo->commit();

            redirectPesquisas($returnQuery);
        }
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $feedback = array(
            'type' => 'error',
            'message' => $e->getMessage() !== '' ? $e->getMessage() : 'Não foi possível concluir a ação.',
            'open_modal' => $action === 'criar',
        );
    }
}

$busca = normalizeSearchTerm(isset($_GET['busca']) ? $_GET['busca'] : '');
$sql = 'SELECT p.id, p.nome, COUNT(DISTINCT pr.id) AS total_respostas, COUNT(DISTINCT pc.id) AS total_campos
        FROM pesquisas p
        LEFT JOIN pesquisa_respostas pr ON pr.pesquisa_id = p.id
        LEFT JOIN pesquisa_campos pc ON pc.pesquisa_id = p.id';
$params = array();
if ($busca !== '') {
    $sql .= ' WHERE p.nome LIKE :busca ESCAPE "\\"';
    $params['busca'] = '%' . escapeLike($busca) . '%';
}
$sql .= ' GROUP BY p.id, p.nome ORDER BY p.id DESC';
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$pesquisas = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: array();

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

<section class="mb-6 grid gap-4 lg:grid-cols-[1.35fr,.65fr]">
  <div class="rounded-3xl bg-gradient-to-r from-slate-900 via-blue-800 to-blue-600 p-8 text-white shadow-lg">
    <div class="mb-4 inline-flex rounded-full bg-white/15 px-3 py-1 text-xs font-semibold uppercase tracking-wide text-blue-50">Pesquisas</div>
    <h1 class="text-3xl font-bold leading-tight sm:text-4xl">Gerencie pesquisas sem bagunça.</h1>
    <p class="mt-3 max-w-2xl text-sm text-blue-50 sm:text-base">Crie, edite e acompanhe resultados em uma listagem limpa. Menos link solto, menos exclusão por URL acidental.</p>
  </div>

  <div class="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
    <div class="text-sm font-medium text-slate-500">Resumo</div>
    <div class="mt-4 grid gap-3 sm:grid-cols-2">
      <div class="rounded-2xl bg-slate-50 p-4">
        <div class="text-xs uppercase tracking-wide text-slate-500">Pesquisas</div>
        <div class="mt-2 text-3xl font-bold text-slate-900"><?= count($pesquisas) ?></div>
      </div>
      <div class="rounded-2xl bg-slate-50 p-4">
        <div class="text-xs uppercase tracking-wide text-slate-500">Resultados</div>
        <div class="mt-2 text-3xl font-bold text-slate-900"><?= array_sum(array_map(function ($item) { return (int) ($item['total_respostas'] ?? 0); }, $pesquisas)) ?></div>
      </div>
    </div>
    <button type="button" onclick="openPesquisaModal()" class="mt-4 w-full rounded-2xl bg-emerald-600 px-4 py-3 text-sm font-semibold text-white hover:bg-emerald-700">Criar pesquisa</button>
  </div>
</section>

<section class="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
  <div class="mb-4 flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
    <div>
      <h2 class="text-xl font-bold text-slate-900">Lista de pesquisas</h2>
      <p class="text-sm text-slate-500">Busque rápido e execute ações sem depender de links destrutivos.</p>
    </div>

    <form method="get" class="flex w-full max-w-xl gap-2">
      <input type="text" name="busca" value="<?= htmlspecialchars($busca, ENT_QUOTES, 'UTF-8') ?>" placeholder="Buscar por nome" 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-slate-900 px-4 py-3 text-sm font-semibold text-white hover:bg-slate-800">Buscar</button>
      <?php if ($busca !== ''): ?>
        <a href="pesquisas.php" class="rounded-2xl border border-slate-300 px-4 py-3 text-sm font-semibold text-slate-700 hover:bg-slate-50">Limpar</a>
      <?php endif; ?>
    </form>
  </div>

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

  <?php if (!$pesquisas): ?>
    <div class="rounded-2xl border border-dashed border-slate-300 bg-slate-50 p-10 text-center text-sm text-slate-500">Nenhuma pesquisa encontrada.</div>
  <?php else: ?>
    <div class="grid grid-cols-1 gap-4 xl:grid-cols-2">
      <?php foreach ($pesquisas as $p): ?>
        <article class="rounded-3xl border border-slate-200 p-5 shadow-sm">
          <div class="flex items-start justify-between gap-3">
            <div class="min-w-0">
              <h3 class="truncate text-lg font-semibold text-slate-900"><?= htmlspecialchars((string) $p['nome'], ENT_QUOTES, 'UTF-8') ?></h3>
              <div class="mt-3 flex flex-wrap gap-2 text-xs font-semibold">
                <span class="rounded-full bg-slate-100 px-3 py-1 text-slate-600"><?= (int) ($p['total_campos'] ?? 0) ?> campo(s)</span>
                <span class="rounded-full bg-blue-100 px-3 py-1 text-blue-700"><?= (int) ($p['total_respostas'] ?? 0) ?> resposta(s)</span>
              </div>
            </div>
          </div>

          <div class="mt-5 flex flex-wrap gap-2">
            <a href="pesquisa_view.php?id=<?= (int) $p['id'] ?>" class="rounded-2xl bg-sky-500 px-4 py-2 text-sm font-semibold text-white hover:bg-sky-600">Responder</a>
            <a href="pesquisa_resultados.php?id=<?= (int) $p['id'] ?>" class="rounded-2xl bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700">Resultados</a>
            <a href="pesquisa_edit.php?id=<?= (int) $p['id'] ?>" class="rounded-2xl bg-amber-400 px-4 py-2 text-sm font-semibold text-slate-900 hover:bg-amber-500">Editar</a>
            <form method="post" class="inline" onsubmit="return confirm('Excluir <?= htmlspecialchars(addslashes((string) $p['nome']), ENT_QUOTES, 'UTF-8') ?>?');">
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="id" value="<?= (int) $p['id'] ?>">
              <?php if ($busca !== ''): ?><input type="hidden" name="busca" value="<?= htmlspecialchars($busca, ENT_QUOTES, 'UTF-8') ?>"><?php endif; ?>
              <button type="submit" class="rounded-2xl bg-red-500 px-4 py-2 text-sm font-semibold text-white hover:bg-red-600">Excluir</button>
            </form>
          </div>
        </article>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</section>

<div id="pesquisaModal" class="<?= $feedback['open_modal'] ? 'flex' : 'hidden' ?> fixed inset-0 z-50 items-center justify-center bg-slate-950/50 p-4">
  <div class="w-full max-w-md rounded-3xl bg-white p-6 shadow-2xl">
    <div class="mb-4 flex items-start justify-between gap-3">
      <div>
        <h3 class="text-xl font-bold text-slate-900">Nova pesquisa</h3>
        <p class="text-sm text-slate-500">Crie a estrutura e depois edite os campos.</p>
      </div>
      <button type="button" onclick="closePesquisaModal()" class="rounded-2xl bg-slate-100 px-3 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-200">Fechar</button>
    </div>

    <form method="post" class="space-y-4">
      <input type="hidden" name="action" value="criar">
      <?php if ($busca !== ''): ?><input type="hidden" name="busca" value="<?= htmlspecialchars($busca, ENT_QUOTES, 'UTF-8') ?>"><?php endif; ?>
      <div>
        <label class="mb-2 block text-sm font-semibold text-slate-700">Nome da pesquisa</label>
        <input type="text" name="nome" maxlength="150" required value="<?= htmlspecialchars($modalNome, ENT_QUOTES, 'UTF-8') ?>" 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 class="flex justify-end gap-2">
        <button type="button" onclick="closePesquisaModal()" class="rounded-2xl border border-slate-300 px-4 py-3 text-sm font-semibold text-slate-700 hover:bg-slate-50">Cancelar</button>
        <button type="submit" class="rounded-2xl bg-emerald-600 px-4 py-3 text-sm font-semibold text-white hover:bg-emerald-700">Salvar</button>
      </div>
    </form>
  </div>
</div>

<script>
  const pesquisaModal = document.getElementById('pesquisaModal');
  function openPesquisaModal() {
    pesquisaModal.classList.remove('hidden');
    pesquisaModal.classList.add('flex');
  }
  function closePesquisaModal() {
    pesquisaModal.classList.add('hidden');
    pesquisaModal.classList.remove('flex');
  }
  pesquisaModal.addEventListener('click', (event) => {
    if (event.target === pesquisaModal) closePesquisaModal();
  });
  document.addEventListener('keydown', (event) => {
    if (event.key === 'Escape') closePesquisaModal();
  });
</script>

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