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

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

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

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

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

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

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

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

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

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

        $label = lowerText(isset($campoAtual['label']) ? $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) (isset($_GET['page']) ? $_GET['page'] : 1));
$q = normalizeSearchTerm(isset($_GET['q']) ? $_GET['q'] : '');
$campoFiltro = (isset($_GET['campo']) && is_numeric($_GET['campo'])) ? (int) $_GET['campo'] : 0;
$dataInicioRaw = isset($_GET['dataInicio']) ? (string) $_GET['dataInicio'] : '';
$dataFimRaw = isset($_GET['dataFim']) ? (string) $_GET['dataFim'] : '';
$dataInicio = normalizeDateInput($dataInicioRaw);
$dataFim = normalizeDateInput($dataFimRaw);

if ($formId <= 0) {
    jsonResponse(array('respostas' => '', 'totalPages' => 1, 'total' => 0, 'error' => 'Formulário inválido.'), 400);
}
if ($dataInicioRaw !== '' && $dataInicio === null) {
    jsonResponse(array('respostas' => '', 'totalPages' => 1, 'total' => 0, 'error' => 'Data inicial inválida.'), 422);
}
if ($dataFimRaw !== '' && $dataFim === null) {
    jsonResponse(array('respostas' => '', 'totalPages' => 1, 'total' => 0, 'error' => 'Data final inválida.'), 422);
}
if ($dataInicio !== null && $dataFim !== null && $dataInicio > $dataFim) {
    jsonResponse(array('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(array('id' => $formId));
$formulario = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$formulario) {
    jsonResponse(array('respostas' => '', 'totalPages' => 1, 'total' => 0, 'error' => 'Formulário não encontrado.'), 404);
}
$isOnboard = (string) (isset($formulario['categoria']) ? $formulario['categoria'] : '') === 'OnBoard';
$hasPrintBoard = is_file(__DIR__ . '/print_board.php');

$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(array('id' => $formId));
$campos = $stmt->fetchAll(PDO::FETCH_ASSOC);
$mapCampos = array();
foreach ((array) $campos as $campo) {
    $mapCampos[(int) $campo['id']] = $campo;
}

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

$where = ' WHERE r.formulario_id = :fid ';
$params = array('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(array(
        '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();
foreach ($respostas as $row) {
    $respostaIds[] = (int) $row['id'];
}
$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 = array();
foreach ($dadosBrutos as $linha) {
    $dadosPorResposta[(int) $linha['resposta_id']][] = $linha;
}

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

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

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

        if (in_array($tipoCampo, array('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(isset($campo['label']) ? $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) (isset($resposta['created_at']) ? $resposta['created_at'] : ''));
    $dataFormatada = $timestamp ? date('d/m/Y H:i', $timestamp) : '-';

    $html .= "<article class='response-card resposta-card' data-id='{$respostaId}'>";
    $html .= "<input type='checkbox' data-id='{$respostaId}' class='response-checkbox select-card'>";
    $html .= "<div class='flex flex-wrap items-start justify-between gap-3'>";
    $html .= "<div class='min-w-0 flex-1'>";
    $html .= "<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>";
    $html .= "<p class='mt-1 text-sm text-slate-500'>{$dataFormatada}</p>";
    $html .= "</div>";
    $html .= "<div class='flex flex-wrap gap-2'>";
    $html .= "<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>";
    $html .= "<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 && $hasPrintBoard) {
        $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 && (isset($formulario['nome']) ? $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>";
    $html .= "</div></div>";

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

    $html .= "<div class='response-details detalhes-card is-hidden hidden mt-4'><ul class='grid gap-3 lg:grid-cols-2'>{$camposHtml}</ul></div>";
    $html .= "</article>";
}

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