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

$formId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
if ($formId <= 0) {
    die('Formulário inválido!');
}

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

$stmtTotals = $pdo->prepare('SELECT COUNT(*) AS total, SUM(CASE WHEN COALESCE(lida, 0) = 0 THEN 1 ELSE 0 END) AS nao_lidas FROM formulario_respostas WHERE formulario_id = :id');
$stmtTotals->execute(['id' => $formId]);
$totais = $stmtTotals->fetch(PDO::FETCH_ASSOC) ?: ['total' => 0, 'nao_lidas' => 0];

$stmtLido = $pdo->prepare('UPDATE formulario_respostas SET lida = 1 WHERE formulario_id = :id AND COALESCE(lida, 0) = 0');
$stmtLido->execute(['id' => $formId]);

$stmt = $pdo->prepare("SELECT id, label, tipo FROM formulario_campos WHERE formulario_id = :id AND COALESCE(tipo, '') <> 'warning' AND COALESCE(hidden, 0) = 0 ORDER BY id ASC");
$stmt->execute(['id' => $formId]);
$campos = $stmt->fetchAll(PDO::FETCH_ASSOC);

$isFichaAdmissao = (($formulario['nome'] ?? '') === 'FICHA DE IDENTIFICAÇÃO - ADMISSÃO');
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Respostas — <?= htmlspecialchars($formulario['nome'], ENT_QUOTES, 'UTF-8') ?></title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<link rel="icon" type="image/png" href="img/Logo.png">
<style>
  html,body{height:100%;overflow:hidden}
  .select-card{display:none;position:absolute;left:.85rem;top:.85rem;z-index:20;width:18px;height:18px;accent-color:#2563eb}
  .select-card.show{display:block}
  #app{height:100vh;display:flex;flex-direction:column}
  #mainShell{flex:1;min-height:0;display:flex;flex-direction:column}
  #respostasScroll{flex:1;min-height:0;overflow:auto;padding-right:.25rem}
  #respostasScroll::-webkit-scrollbar{width:10px}
  #respostasScroll::-webkit-scrollbar-thumb{background:#cbd5e1;border-radius:999px}
  .metric-pill{display:flex;align-items:center;justify-content:space-between;gap:.75rem;border:1px solid #e2e8f0;background:#fff;border-radius:1rem;padding:.75rem .9rem;min-width:0}
  .metric-pill strong{font-size:1.125rem;line-height:1;color:#0f172a}
  .compact-btn{border-radius:.9rem;padding:.65rem .9rem;font-size:.85rem;font-weight:600}
  .resposta-card{position:relative}
  .arquivos-container img{height:72px;width:100%;object-fit:cover;border-radius:.85rem;border:1px solid #e2e8f0}
  @media (max-width: 1024px){html,body{overflow:auto}#app{height:auto}#mainShell{display:block}#respostasScroll{overflow:visible;padding-right:0}}
</style>
</head>
<body class="bg-slate-100 text-slate-800">
<div id="app">
  <nav class="border-b border-slate-200 bg-white/95 backdrop-blur">
    <div class="mx-auto flex max-w-7xl flex-wrap items-center justify-between gap-3 px-4 py-3 sm:px-6">
      <div class="min-w-0">
        <div class="text-lg font-bold text-blue-700">Respostas</div>
        <div class="truncate text-sm text-slate-500"><?= htmlspecialchars($formulario['nome'], ENT_QUOTES, 'UTF-8') ?></div>
      </div>
      <div class="flex flex-wrap gap-2">
        <a href="formularios.php" class="compact-btn border border-slate-300 bg-white text-slate-700 hover:bg-slate-50">Voltar</a>
        <button type="button" onclick="copiarLinkFormulario()" class="compact-btn bg-slate-900 text-white hover:bg-slate-800">Copiar link</button>
      </div>
    </div>
  </nav>

  <div id="mainShell" class="mx-auto w-full max-w-7xl px-4 py-4 sm:px-6">
    <section class="mb-3 rounded-3xl border border-slate-200 bg-white p-3 shadow-sm">
      <div class="grid gap-3 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,1.3fr)] xl:items-center">
        <div class="min-w-0 rounded-2xl bg-gradient-to-r from-slate-900 via-blue-800 to-blue-600 px-4 py-3 text-white">
          <div class="mb-1 text-xs font-semibold uppercase tracking-wide text-blue-100">Painel rápido</div>
          <h1 class="truncate text-xl font-bold"><?= htmlspecialchars($formulario['nome'], ENT_QUOTES, 'UTF-8') ?></h1>
          <p class="mt-1 text-xs text-blue-100">Tudo no alto. A lista rola sozinha. A tela para de sofrer.</p>
        </div>

        <div class="grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
          <div class="metric-pill"><span class="text-xs text-slate-500">Total</span><strong><?= (int) ($totais['total'] ?? 0) ?></strong></div>
          <div class="metric-pill"><span class="text-xs text-slate-500">Filtrados</span><strong id="resultadosFiltradosLabel"><?= (int) ($totais['total'] ?? 0) ?></strong></div>
          <div class="metric-pill"><span class="text-xs text-slate-500">Não lidas</span><strong><?= (int) ($totais['nao_lidas'] ?? 0) ?></strong></div>
          <div class="metric-pill"><span class="text-xs text-slate-500">Campos</span><strong><?= count($campos) ?></strong></div>
        </div>
      </div>
    </section>

    <section class="mb-3 rounded-3xl border border-slate-200 bg-white p-3 shadow-sm">
      <div class="grid gap-2 xl:grid-cols-[180px_minmax(0,1fr)_150px_150px_auto]">
        <select id="campoFiltro" class="rounded-2xl border border-slate-300 px-3 py-2.5 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
          <option value="">Todos os campos</option>
          <?php foreach ($campos as $c): ?>
            <option value="<?= (int) $c['id'] ?>"><?= htmlspecialchars((string) $c['label'], ENT_QUOTES, 'UTF-8') ?></option>
          <?php endforeach; ?>
        </select>

        <input type="text" id="searchInput" placeholder="Buscar por nome, unidade, cargo..." class="rounded-2xl border border-slate-300 px-3 py-2.5 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
        <input type="date" id="dataInicio" class="rounded-2xl border border-slate-300 px-3 py-2.5 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
        <input type="date" id="dataFim" class="rounded-2xl border border-slate-300 px-3 py-2.5 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">

        <div class="flex flex-wrap gap-2 xl:justify-end">
          <button id="btnExportar" class="compact-btn bg-blue-600 text-white hover:bg-blue-700">Excel</button>
          <a href="importar_respostas.php?formId=<?= $formId ?>" class="compact-btn bg-emerald-600 text-white hover:bg-emerald-700">Importar</a>
          <button id="btnLimparFiltros" type="button" class="compact-btn border border-slate-300 bg-white text-slate-700 hover:bg-slate-50">Limpar</button>
        </div>
      </div>

      <div class="mt-2 flex flex-wrap items-center justify-between gap-2 border-t border-slate-100 pt-2">
        <div class="text-sm text-slate-500"><span id="statusResultados">Carregando respostas...</span></div>
        <button id="btnSelecionarModo" type="button" class="compact-btn border border-slate-300 bg-white text-slate-700 hover:bg-slate-50">Selecionar</button>
      </div>
    </section>

    <section class="min-h-0 flex-1 rounded-3xl border border-slate-200 bg-white p-3 shadow-sm">
      <div id="respostasScroll">
        <div id="respostasContainer"></div>
      </div>
      <div id="paginacaoContainer" class="mt-3 flex justify-center gap-2 border-t border-slate-100 pt-3"></div>
    </section>
  </div>
</div>

<div id="acoesEmMassa" class="fixed bottom-4 right-4 z-40 flex translate-y-3 items-center gap-2 opacity-0 transition duration-200 pointer-events-none">
  <div class="rounded-2xl border border-slate-200 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 shadow-sm"><span id="selectedCount">0</span> selecionada(s)</div>
  <button id="btnExcluirTodos" class="compact-btn bg-red-600 text-white shadow-sm hover:bg-red-700">Excluir</button>
  <?php if ($isFichaAdmissao): ?>
    <button id="btnGerarFichaTodos" class="compact-btn bg-emerald-600 text-white shadow-sm hover:bg-emerald-700">Ficha</button>
  <?php endif; ?>
  <button id="btnExportarImagens" class="compact-btn bg-indigo-600 text-white shadow-sm hover:bg-indigo-700">Imagens</button>
</div>

<script>
const respostasContainer = document.getElementById('respostasContainer');
const paginacaoContainer = document.getElementById('paginacaoContainer');
const searchInput = document.getElementById('searchInput');
const campoFiltro = document.getElementById('campoFiltro');
const dataInicio = document.getElementById('dataInicio');
const dataFim = document.getElementById('dataFim');
const statusResultados = document.getElementById('statusResultados');
const acoesContainer = document.getElementById('acoesEmMassa');
const btnExportar = document.getElementById('btnExportar');
const btnExcluirTodos = document.getElementById('btnExcluirTodos');
const btnGerarFichaTodos = document.getElementById('btnGerarFichaTodos');
const btnExportarImagens = document.getElementById('btnExportarImagens');
const btnSelecionarModo = document.getElementById('btnSelecionarModo');
const btnLimparFiltros = document.getElementById('btnLimparFiltros');
const selectedCount = document.getElementById('selectedCount');
const resultadosFiltradosLabel = document.getElementById('resultadosFiltradosLabel');
const formId = <?= $formId ?>;
let currentPage = 1;
let selectMode = false;

function debounce(fn, delay = 300) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

function copiarLinkFormulario() {
  const url = new URL(`formulario_view.php?id=${formId}`, window.location.href).href;
  navigator.clipboard.writeText(url).then(() => {
    alert('Link copiado com sucesso.');
  }).catch(() => {
    prompt('Copie o link abaixo:', url);
  });
}

function gerarPaginacao(totalPages, page) {
  let html = "<div class='inline-flex flex-wrap justify-center gap-2'>";
  const maxButtons = 7;
  let start = Math.max(1, page - Math.floor(maxButtons / 2));
  let end = Math.min(totalPages, start + maxButtons - 1);
  start = Math.max(1, end - maxButtons + 1);

  if (page > 1) html += `<button class="page-btn rounded-2xl bg-white px-3 py-2 text-sm font-semibold text-slate-700 shadow-sm hover:bg-slate-50" data-page="${page - 1}">«</button>`;
  for (let i = start; i <= end; i += 1) {
    const active = i === page ? 'bg-blue-600 text-white' : 'bg-white text-slate-700 hover:bg-slate-50';
    html += `<button class="page-btn rounded-2xl px-3 py-2 text-sm font-semibold shadow-sm ${active}" data-page="${i}">${i}</button>`;
  }
  if (page < totalPages) html += `<button class="page-btn rounded-2xl bg-white px-3 py-2 text-sm font-semibold text-slate-700 shadow-sm hover:bg-slate-50" data-page="${page + 1}">»</button>`;
  html += '</div>';
  return html;
}

function limparNomeArquivo(nome) {
  return nome.replace(/[^\w.\-]/g, '_');
}

function obterNomeArquivo(url, fallback = 'arquivo') {
  try {
    const semQuery = url.split('?')[0];
    const nome = semQuery.split('/').pop() || fallback;
    return limparNomeArquivo(nome);
  } catch {
    return fallback;
  }
}

function obterLinksDeImagem(card) {
  return Array.from(card.querySelectorAll('.arquivos-container a')).filter((link) => {
    if (link.querySelector('img')) return true;
    const href = link.getAttribute('href') || '';
    return /\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(href);
  });
}

function validarPeriodo() {
  if (dataInicio.value && dataFim.value && dataInicio.value > dataFim.value) {
    statusResultados.textContent = 'A data inicial não pode ser maior que a data final.';
    return false;
  }
  return true;
}

async function exportarImagensSelecionadas() {
  const selectedCards = document.querySelectorAll('.select-card:checked');
  if (!selectedCards.length) {
    alert('Selecione ao menos uma resposta.');
    return;
  }

  btnExportarImagens.disabled = true;
  const oldText = btnExportarImagens.textContent;
  btnExportarImagens.textContent = 'Gerando ZIP...';

  try {
    const zip = new JSZip();
    let totalArquivos = 0;

    for (const checkbox of selectedCards) {
      const card = checkbox.closest('.resposta-card');
      if (!card) continue;
      const links = obterLinksDeImagem(card);
      if (!links.length) continue;

      const pasta = zip.folder(`resposta_${checkbox.dataset.id}`);
      let contador = 1;

      for (const link of links) {
        try {
          const href = link.getAttribute('href');
          if (!href) continue;
          const url = new URL(href, window.location.origin).href;
          const response = await fetch(url);
          if (!response.ok) continue;
          const blob = await response.blob();
          if (!String(blob.type || '').startsWith('image/')) continue;

          let nome = obterNomeArquivo(url, `imagem_${contador}`);
          if (!/\.[a-z0-9]+$/i.test(nome)) {
            const ext = blob.type.split('/')[1] || 'jpg';
            nome += `.${ext}`;
          }
          pasta.file(nome, blob);
          contador += 1;
          totalArquivos += 1;
        } catch (error) {
          console.error(error);
        }
      }
    }

    if (!totalArquivos) {
      alert('Nenhuma imagem foi encontrada nas respostas selecionadas.');
      return;
    }

    const zipBlob = await zip.generateAsync({ type: 'blob' });
    saveAs(zipBlob, `imagens_formulario_${formId}.zip`);
  } finally {
    btnExportarImagens.disabled = false;
    btnExportarImagens.textContent = oldText;
  }
}

function atualizarAcoesEmMassa() {
  const selecionados = Array.from(document.querySelectorAll('.select-card:checked'));
  selectedCount.textContent = String(selecionados.length);
  acoesContainer.classList.toggle('opacity-0', selecionados.length === 0);
  acoesContainer.classList.toggle('translate-y-3', selecionados.length === 0);
  acoesContainer.classList.toggle('pointer-events-none', selecionados.length === 0);
}

function aplicarModoSelecao() {
  document.querySelectorAll('.select-card').forEach((checkbox) => {
    checkbox.classList.toggle('show', selectMode);
    if (!selectMode) checkbox.checked = false;
  });
  btnSelecionarModo.textContent = selectMode ? 'Ocultar seleção' : 'Selecionar';
  atualizarAcoesEmMassa();
}

function configurarCards() {
  document.querySelectorAll('.resposta-card').forEach((card) => {
    const checkbox = card.querySelector('.select-card');
    const toggleBtn = card.querySelector('.toggle-card');
    const detalhes = card.querySelector('.campos');
    const editarBtn = card.querySelector('[data-action="editar"]');
    const excluirBtn = card.querySelector('[data-action="excluir"]');
    const fichaBtn = card.querySelector('[data-action="ficha"]');

    if (checkbox) {
      checkbox.addEventListener('click', (event) => {
        event.stopPropagation();
        atualizarAcoesEmMassa();
      });
    }

    if (toggleBtn && detalhes) {
      toggleBtn.addEventListener('click', (event) => {
        event.stopPropagation();
        detalhes.classList.toggle('hidden');
        toggleBtn.textContent = detalhes.classList.contains('hidden') ? 'Detalhes' : 'Ocultar';
      });
    }

    if (editarBtn) {
      editarBtn.addEventListener('click', (event) => {
        event.stopPropagation();
        window.location = `editar_resposta.php?id=${card.dataset.id}`;
      });
    }

    if (excluirBtn) {
      excluirBtn.addEventListener('click', (event) => {
        event.stopPropagation();
        if (confirm('Excluir esta resposta?')) {
          enviarExclusao({ id: card.dataset.id });
        }
      });
    }

    if (fichaBtn) {
      fichaBtn.addEventListener('click', (event) => {
        event.stopPropagation();
        window.open(`gerar_ficha.php?id=${card.dataset.id}`, '_blank');
      });
    }

    card.addEventListener('click', (event) => {
      if (event.target.closest('button') || event.target.closest('.select-card') || event.target.closest('a') || event.target.closest('.campos')) return;
      if (!detalhes) return;
      detalhes.classList.toggle('hidden');
      if (toggleBtn) {
        toggleBtn.textContent = detalhes.classList.contains('hidden') ? 'Detalhes' : 'Ocultar';
      }
    });
  });

  aplicarModoSelecao();
}

async function carregarRespostas(page = 1) {
  if (!validarPeriodo()) {
    respostasContainer.innerHTML = "<div class='rounded-3xl border border-amber-200 bg-amber-50 p-6 text-center shadow-sm text-amber-700'>Corrija o período para continuar.</div>";
    paginacaoContainer.innerHTML = '';
    resultadosFiltradosLabel.textContent = '0';
    return;
  }

  currentPage = page;
  respostasContainer.innerHTML = "<div class='rounded-3xl border border-slate-200 bg-slate-50 p-6 text-center text-slate-500'>Carregando respostas...</div>";
  paginacaoContainer.innerHTML = '';
  statusResultados.textContent = 'Carregando respostas...';

  const params = new URLSearchParams({
    id: formId,
    page: currentPage,
    q: searchInput.value.trim(),
    campo: campoFiltro.value,
    dataInicio: dataInicio.value,
    dataFim: dataFim.value,
  });

  try {
    const response = await fetch(`buscar_respostas.php?${params.toString()}`);
    const data = await response.json().catch(() => ({}));
    if (!response.ok) {
      throw new Error(data.error || 'Falha na resposta do servidor');
    }
    respostasContainer.innerHTML = data.respostas || '';
    paginacaoContainer.innerHTML = gerarPaginacao(data.totalPages || 1, currentPage);
    resultadosFiltradosLabel.textContent = String(data.total || 0);
    statusResultados.textContent = `${data.total || 0} resposta(s)`;

    document.querySelectorAll('.page-btn').forEach((btn) => {
      btn.addEventListener('click', () => carregarRespostas(Number(btn.dataset.page)));
    });

    configurarCards();
    atualizarAcoesEmMassa();
  } catch (error) {
    const message = error instanceof Error && error.message ? error.message : 'Erro ao carregar respostas.';
    respostasContainer.innerHTML = `<div class='rounded-3xl border border-red-200 bg-red-50 p-6 text-center text-red-600'>${message}</div>`;
    paginacaoContainer.innerHTML = '';
    resultadosFiltradosLabel.textContent = '0';
    statusResultados.textContent = message;
  }
}

btnSelecionarModo.addEventListener('click', () => {
  selectMode = !selectMode;
  aplicarModoSelecao();
});

btnExcluirTodos.addEventListener('click', () => {
  const ids = Array.from(document.querySelectorAll('.select-card:checked')).map((cb) => cb.dataset.id);
  if (!ids.length) return;
  if (confirm('Excluir as respostas selecionadas?')) {
    enviarExclusao({ ids });
  }
});

if (btnGerarFichaTodos) {
  btnGerarFichaTodos.addEventListener('click', () => {
    const ids = Array.from(document.querySelectorAll('.select-card:checked')).map((cb) => cb.dataset.id);
    ids.forEach((id) => window.open(`gerar_ficha.php?id=${id}`, '_blank'));
  });
}

btnExportarImagens.addEventListener('click', exportarImagensSelecionadas);
btnExportar.addEventListener('click', () => {
  if (!validarPeriodo()) {
    alert('Corrija o período antes de exportar.');
    return;
  }

  const params = new URLSearchParams({
    id: formId,
    q: searchInput.value.trim(),
    campo: campoFiltro.value,
    dataInicio: dataInicio.value,
    dataFim: dataFim.value,
  });
  window.open(`exportar_respostas.php?${params.toString()}`, '_blank');
});

btnLimparFiltros.addEventListener('click', () => {
  searchInput.value = '';
  campoFiltro.value = '';
  dataInicio.value = '';
  dataFim.value = '';
  carregarRespostas(1);
});

function enviarExclusao(payload) {
  const form = document.createElement('form');
  form.method = 'post';
  form.action = 'deletar_resposta.php';

  Object.entries(payload).forEach(([key, value]) => {
    const input = document.createElement('input');
    input.type = 'hidden';
    input.name = key;
    input.value = Array.isArray(value) ? value.join(',') : String(value);
    form.appendChild(input);
  });

  document.body.appendChild(form);
  form.submit();
}

const carregarDebounced = debounce(() => carregarRespostas(1), 350);
searchInput.addEventListener('input', carregarDebounced);
campoFiltro.addEventListener('change', () => carregarRespostas(1));
dataInicio.addEventListener('change', () => carregarRespostas(1));
dataFim.addEventListener('change', () => carregarRespostas(1));

carregarRespostas(currentPage);
</script>
</body>
</html>
