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

header('Content-Type: application/json; charset=utf-8');

function jsonResponse(array $payload, int $statusCode = 200): void
{
    http_response_code($statusCode);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}

function lowerText(string $value): string
{
    return function_exists('mb_strtolower') ? mb_strtolower($value, 'UTF-8') : strtolower($value);
}

function h(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

function formatDisplayValue(string $value): string
{
    $value = trim($value);
    return $value === '' ? '<span class="text-slate-400">-</span>' : nl2br(h($value));
}

function isImageExtension(string $ext): bool
{
    return in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg'], true);
}

function pickDisplayName(array $dados, array $mapCampos): string
{
    $fallback = '';
    foreach ($dados as $dado) {
        $campoId = (int) ($dado['campo_id'] ?? 0);
        if (!isset($mapCampos[$campoId])) {
            continue;
        }

        $campoAtual = $mapCampos[$campoId];
        $tipoCampo = (string) ($campoAtual['tipo'] ?? 'text');
        $valorAtual = trim((string) ($dado['valor'] ?? ''));
        if ($valorAtual === '' || in_array($tipoCampo, ['image', 'file'], true)) {
            continue;
        }

        if ($fallback === '') {
            $fallback = $valorAtual;
        }

        $label = lowerText((string) ($campoAtual['label'] ?? ''));
        if (str_contains($label, 'nome completo') || $label === 'nome' || str_contains($label, 'colaborador')) {
            return $valorAtual;
        }
    }

    return $fallback;
}

$formId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$page = max(1, (int) ($_GET['page'] ?? 1));
$q = preg_replace('/\s+/u', ' ', trim((string) ($_GET['q'] ?? ''))) ?? '';
$campoFiltro = isset($_GET['campo']) && is_numeric($_GET['campo']) ? (int) $_GET['campo'] : 0;
$dataInicio = normalizeDateInput((string) ($_GET['dataInicio'] ?? ''));
$dataFim = normalizeDateInput((string) ($_GET['dataFim'] ?? ''));

if ($formId <= 0) {
    jsonResponse(['respostas' => '', 'totalPages' => 1, 'total' => 0, 'error' => 'Formulário inválido.'], 400);
}

if ((string) ($_GET['dataInicio'] ?? '') !== '' && $dataInicio === null) {
    jsonResponse(['respostas' => '', 'totalPages' => 1, 'total' => 0, 'error' => 'Data inicial inválida.'], 422);
}

if ((string) ($_GET['dataFim'] ?? '') !== '' && $dataFim === null) {
    jsonResponse(['respostas' => '', 'totalPages' => 1, 'total' => 0, 'error' => 'Data final inválida.'], 422);
}

if ($dataInicio !== null && $dataFim !== null && $dataInicio > $dataFim) {
    jsonResponse(['respostas' => '', 'totalPages' => 1, 'total' => 0, 'error' => 'A data inicial não pode ser maior que a data final.'], 422);
}

$limit = 6;
$offset = ($page - 1) * $limit;

$stmt = $pdo->prepare('SELECT nome, categoria FROM formularios WHERE id = :id');
$stmt->execute(['id' => $formId]);
$formulario = $stmt->fetch(PDO::FETCH_ASSOC);
$isOnboard = $formulario && ($formulario['categoria'] ?? '') === 'OnBoard';

$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);
$mapCampos = [];
foreach ($campos as $campo) {
    $mapCampos[(int) $campo['id']] = $campo;
}

if ($campoFiltro > 0 && !isset($mapCampos[$campoFiltro])) {
    $campoFiltro = 0;
}

$where = ' WHERE r.formulario_id = :fid ';
$params = ['fid' => $formId];

if ($dataInicio !== null) {
    $where .= ' AND r.created_at >= :dataInicio ';
    $params['dataInicio'] = $dataInicio . ' 00:00:00';
}
if ($dataFim !== null) {
    $where .= ' AND r.created_at <= :dataFim ';
    $params['dataFim'] = $dataFim . ' 23:59:59';
}
if ($q !== '') {
    if ($campoFiltro > 0) {
        $where .= " AND EXISTS (
            SELECT 1
            FROM formulario_respostas_campos rc
            INNER JOIN formulario_campos fc ON fc.id = rc.campo_id
            WHERE rc.resposta_id = r.id
              AND rc.campo_id = :campoFiltro
              AND COALESCE(fc.hidden, 0) = 0
              AND COALESCE(fc.tipo, '') <> 'warning'
              AND rc.valor LIKE :q ESCAPE '\\'
        ) ";
        $params['campoFiltro'] = $campoFiltro;
    } else {
        $where .= " AND EXISTS (
            SELECT 1
            FROM formulario_respostas_campos rc
            INNER JOIN formulario_campos fc ON fc.id = rc.campo_id
            WHERE rc.resposta_id = r.id
              AND COALESCE(fc.hidden, 0) = 0
              AND COALESCE(fc.tipo, '') <> 'warning'
              AND rc.valor LIKE :q ESCAPE '\\'
        ) ";
    }
    $params['q'] = '%' . escapeLike($q) . '%';
}

$stmt = $pdo->prepare("SELECT COUNT(*) FROM formulario_respostas r {$where}");
$stmt->execute($params);
$total = (int) $stmt->fetchColumn();
$totalPages = max(1, (int) ceil($total / $limit));

if ($page > $totalPages) {
    $page = $totalPages;
    $offset = ($page - 1) * $limit;
}

$stmt = $pdo->prepare("SELECT r.id, r.created_at FROM formulario_respostas r {$where} ORDER BY r.created_at DESC, r.id DESC LIMIT {$limit} OFFSET {$offset}");
$stmt->execute($params);
$respostas = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!$respostas) {
    jsonResponse([
        'respostas' => "<div class='rounded-3xl border border-dashed border-slate-300 bg-white p-10 text-center shadow-sm'><h3 class='text-xl font-bold text-slate-900'>Nenhuma resposta encontrada</h3><p class='mt-2 text-sm text-slate-500'>Tente mudar os filtros ou limpar a busca.</p></div>",
        'page' => $page,
        'totalPages' => $totalPages,
        'total' => 0,
    ]);
}

$respostaIds = array_map(static fn(array $row): int => (int) $row['id'], $respostas);
$placeholders = implode(',', array_fill(0, count($respostaIds), '?'));

$stmtCampos = $pdo->prepare(
    "SELECT rc.resposta_id, rc.campo_id, rc.valor, rc.correto
     FROM formulario_respostas_campos rc
     INNER JOIN formulario_campos fc ON fc.id = rc.campo_id
     WHERE rc.resposta_id IN ({$placeholders})
       AND COALESCE(fc.hidden, 0) = 0
       AND COALESCE(fc.tipo, '') <> 'warning'
     ORDER BY rc.id ASC"
);
$stmtCampos->execute($respostaIds);
$dadosBrutos = $stmtCampos->fetchAll(PDO::FETCH_ASSOC);

$dadosPorResposta = [];
foreach ($dadosBrutos as $linha) {
    $dadosPorResposta[(int) $linha['resposta_id']][] = $linha;
}

$html = '';
foreach ($respostas as $resposta) {
    $respostaId = (int) $resposta['id'];
    $dados = $dadosPorResposta[$respostaId] ?? [];
    $nomeExibicao = pickDisplayName($dados, $mapCampos);

    $arquivosHtml = '';
    $camposHtml = '';
    foreach ($dados as $dado) {
        $campoId = (int) ($dado['campo_id'] ?? 0);
        if (!isset($mapCampos[$campoId])) {
            continue;
        }

        $campo = $mapCampos[$campoId];
        $tipoCampo = (string) ($campo['tipo'] ?? 'text');
        $valorOriginal = trim((string) ($dado['valor'] ?? ''));

        if (in_array($tipoCampo, ['image', 'file'], true)) {
            if ($valorOriginal === '') {
                continue;
            }

            $filePath = h($valorOriginal);
            $fileName = h(storedFileDisplayName($valorOriginal));
            $ext = strtolower(pathinfo($valorOriginal, PATHINFO_EXTENSION));

            if (isImageExtension($ext)) {
                $preview = "<a href='{$filePath}' target='_blank' rel='noopener noreferrer'><img src='{$filePath}' alt='{$fileName}' class='h-24 w-full object-cover'></a>";
            } elseif ($ext === 'pdf') {
                $preview = "<a href='{$filePath}' target='_blank' rel='noopener noreferrer' class='flex h-24 w-full items-center justify-center bg-red-50 text-sm font-semibold text-red-600'>PDF</a>";
            } else {
                $preview = "<a href='{$filePath}' target='_blank' rel='noopener noreferrer' class='flex h-24 w-full items-center justify-center bg-slate-100 px-2 text-xs text-slate-700'>{$fileName}</a>";
            }

            $arquivosHtml .= "<div class='overflow-hidden rounded-2xl border border-slate-200 bg-white'>{$preview}<div class='flex gap-2 border-t border-slate-100 p-2'><a href='{$filePath}' target='_blank' rel='noopener noreferrer' class='flex-1 rounded-xl bg-blue-600 px-3 py-2 text-center text-xs font-semibold text-white hover:bg-blue-700'>Visualizar</a><a href='{$filePath}' download='{$fileName}' class='flex-1 rounded-xl bg-emerald-600 px-3 py-2 text-center text-xs font-semibold text-white hover:bg-emerald-700'>Baixar</a></div></div>";
            continue;
        }

        $status = '';
        if ($isOnboard && array_key_exists('correto', $dado) && $dado['correto'] !== null) {
            if ((string) $dado['correto'] === '1') {
                $status = " <span class='rounded-full bg-green-100 px-2 py-1 text-xs font-semibold text-green-700'>Certo</span>";
            } elseif ((string) $dado['correto'] === '0') {
                $status = " <span class='rounded-full bg-red-100 px-2 py-1 text-xs font-semibold text-red-700'>Errado</span>";
            }
        }

        $camposHtml .= '<li class="rounded-2xl bg-slate-50 px-4 py-3"><div class="text-xs font-semibold uppercase tracking-wide text-slate-500">' . h((string) $campo['label']) . '</div><div class="mt-1 text-sm leading-6 text-slate-800">' . formatDisplayValue($valorOriginal) . $status . '</div></li>';
    }

    if ($camposHtml === '') {
        $camposHtml = '<li class="rounded-2xl bg-slate-50 px-4 py-3 text-sm text-slate-500">Nenhum dado textual registrado nesta resposta.</li>';
    }

    $timestamp = strtotime((string) ($resposta['created_at'] ?? ''));
    $dataFormatada = $timestamp ? date('d/m/Y H:i', $timestamp) : '-';

    $html .= "<article class='resposta-card rounded-3xl border border-slate-200 bg-white p-5 shadow-sm transition hover:-translate-y-0.5 hover:shadow-md' data-id='{$respostaId}'><input type='checkbox' class='select-card absolute left-5 top-5 z-10 h-5 w-5 rounded border-slate-300 text-blue-600 focus:ring-blue-500'><div class='flex flex-wrap items-start justify-between gap-3'><div class='min-w-0'><div class='flex flex-wrap items-center gap-2'><h3 class='truncate text-base font-bold text-slate-900'>" . h($nomeExibicao !== '' ? $nomeExibicao : ('Resposta #' . $respostaId)) . "</h3><span class='rounded-full bg-slate-100 px-2.5 py-1 text-[11px] font-semibold text-slate-600'>#{$respostaId}</span></div><p class='mt-1 text-sm text-slate-500'>{$dataFormatada}</p></div><div class='flex flex-wrap gap-2'><button type='button' class='toggle-card rounded-2xl border border-slate-300 bg-white px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50'>Detalhes</button><button type='button' data-action='editar' class='rounded-2xl bg-amber-400 px-3 py-2 text-sm font-semibold text-slate-900 hover:bg-amber-500'>Editar</button>";

    if ($isOnboard) {
        $html .= "<a href='print_board.php?id={$respostaId}' target='_blank' rel='noopener noreferrer' class='rounded-2xl bg-purple-600 px-3 py-2 text-sm font-semibold text-white hover:bg-purple-700'>Relatório</a>";
    }

    if ($formulario && ($formulario['nome'] ?? '') === 'FICHA DE IDENTIFICAÇÃO - ADMISSÃO') {
        $html .= "<button type='button' data-action='ficha' class='rounded-2xl bg-emerald-600 px-3 py-2 text-sm font-semibold text-white hover:bg-emerald-700'>Ficha</button>";
    }

    $html .= "<button type='button' data-action='excluir' class='rounded-2xl bg-red-50 px-3 py-2 text-sm font-semibold text-red-600 hover:bg-red-100'>Excluir</button></div></div>";

    if ($arquivosHtml !== '') {
        $html .= "<div class='arquivos-container mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-3'>{$arquivosHtml}</div>";
    }

    $html .= "<div class='campos mt-4 hidden'><ul class='space-y-2'>{$camposHtml}</ul></div></article>";
}

jsonResponse([
    'respostas' => $html,
    'page' => $page,
    'totalPages' => $totalPages,
    'total' => $total,
]);
