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

$pesquisaId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
if ($pesquisaId <= 0) {
    die('Pesquisa inválida!');
}

$stmt = $pdo->prepare('SELECT * FROM pesquisas WHERE id = :id');
$stmt->execute(['id' => $pesquisaId]);
$pesquisa = $stmt->fetch();
if (!$pesquisa) {
    die('Pesquisa não encontrada!');
}

$stmt = $pdo->prepare('SELECT * FROM pesquisa_campos WHERE pesquisa_id = :id ORDER BY id ASC');
$stmt->execute(['id' => $pesquisaId]);
$campos = $stmt->fetchAll();

$stmt = $pdo->prepare('SELECT * FROM pesquisa_respostas WHERE pesquisa_id = :id ORDER BY created_at DESC');
$stmt->execute(['id' => $pesquisaId]);
$respostas = $stmt->fetchAll();

$dadosCampos = [];
foreach ($campos as $c) {
    $dadosCampos[(int) $c['id']] = [
        'label' => $c['label'],
        'tipo' => $c['tipo'],
        'valores' => [],
    ];
}

foreach ($respostas as $r) {
    $stmt = $pdo->prepare('SELECT * FROM pesquisa_respostas_campos WHERE resposta_id = :rid');
    $stmt->execute(['rid' => $r['id']]);
    $camposRes = $stmt->fetchAll();

    foreach ($camposRes as $cr) {
        $campoId = (int) $cr['campo_id'];
        if (isset($dadosCampos[$campoId])) {
            $dadosCampos[$campoId]['valores'][] = $cr['valor'];
        }
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Resultados da Pesquisa</title>
<link rel="icon" type="image/png" href="img/Logo.png">
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="bg-gray-50 min-h-screen">
<nav class="bg-white shadow p-4 flex flex-wrap items-center justify-between gap-3">
    <h1 class="font-bold text-xl text-blue-600">Gestão</h1>
    <div class="flex flex-wrap items-center gap-4">
        <a href="home.php" class="hover:text-blue-600">Home</a>
        <a href="formularios.php" class="hover:text-blue-600">Formulários</a>
        <a href="pesquisas.php" class="hover:text-blue-600">Pesquisas</a>
        <a href="logout.php" class="text-red-500 hover:text-red-600">Sair</a>
    </div>
</nav>

<div class="max-w-6xl mx-auto py-10 px-4">
    <div class="flex items-center justify-between gap-4 flex-wrap mb-8">
        <h1 class="text-3xl font-bold text-gray-800">Resultados da Pesquisa: <?= htmlspecialchars($pesquisa['nome']) ?></h1>
        <a href="pesquisas.php" class="px-4 py-2 rounded border hover:bg-gray-50">Voltar</a>
    </div>

    <?php if (empty($respostas)): ?>
        <p class="text-gray-600 mb-6">Nenhuma resposta recebida ainda.</p>
    <?php endif; ?>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 w-full">
    <?php foreach ($dadosCampos as $campoId => $d): ?>
        <div class="bg-white p-6 rounded-2xl shadow-lg">
            <h2 class="font-semibold text-lg mb-4"><?= htmlspecialchars($d['label']) ?></h2>
            <?php if (in_array($d['tipo'], ['text', 'textarea', 'number', 'email'], true)): ?>
                <ul class="list-disc pl-5 text-gray-700 space-y-1">
                    <?php foreach ($d['valores'] as $v): ?>
                        <li><?= htmlspecialchars($v) ?></li>
                    <?php endforeach; ?>
                </ul>
            <?php elseif (in_array($d['tipo'], ['select', 'radio', 'checkbox'], true)): ?>
                <canvas id="chart-<?= $campoId ?>" class="w-full h-64"></canvas>
                <script>
                    (() => {
                        const ctx = document.getElementById('chart-<?= $campoId ?>').getContext('2d');
                        const valores = <?= json_encode($d['valores']) ?>;
                        const freq = {};
                        valores.forEach(v => { freq[v] = (freq[v] || 0) + 1; });
                        new Chart(ctx, {
                            type: 'bar',
                            data: {
                                labels: Object.keys(freq),
                                datasets: [{
                                    label: 'Respostas',
                                    data: Object.values(freq),
                                    backgroundColor: 'rgba(59, 130, 246, 0.6)',
                                    borderColor: 'rgba(59, 130, 246, 1)',
                                    borderWidth: 1
                                }]
                            },
                            options: {
                                responsive: true,
                                plugins: {
                                    legend: { display: false },
                                    title: { display: true, text: 'Distribuição de respostas' }
                                },
                                scales: { y: { beginAtZero: true, precision: 0 } }
                            }
                        });
                    })();
                </script>
            <?php else: ?>
                <p class="text-gray-500">Sem visualização específica para este tipo de campo.</p>
            <?php endif; ?>
        </div>
    <?php endforeach; ?>
    </div>
</div>
</body>
</html>
