<?php
// Os dados já estão disponíveis através do controller, extraídos do banco de dados.
// O controller deve garantir que o array $dados contenha as chaves:
// 'totalEleitores', 'porSexo', 'porBairro', 'porTipo', 'porDemanda'
?>
<!DOCTYPE html>
<html lang="pt-br">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Relatório de Eleitores</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap"
        rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root {
            --primary-color: #0B1F3A;
            --secondary-color: #102B54;
            --accent-color: #3B82F6;
        }

        .navbar-custom {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
        }

        .page-title {
            font-size: 1.75rem;
            font-weight: 800;
            color: #1e293b;
        }

        .page-subtitle {
            font-size: 0.95rem;
            color: #64748b;
        }

        body {
            font-family: 'Inter', sans-serif;
            background-color: #f8fafc;
            color: #334155;
            line-height: 1.6;
        }

        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 16px;
            padding: 1.75rem;
            border: none;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
            height: 100%;
            color: white;
        }

        .stat-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 10px 20px -5px rgba(0, 0, 0, 0.07);
        }

        .stat-icon {
            width: 3.5rem;
            height: 3.5rem;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            color: white;
            background: rgba(255, 255, 255, 0.2);
            backdrop-filter: blur(10px);
        }

        .stat-content .stat-label {
            font-size: 0.875rem;
            font-weight: 600;
            color: rgba(255, 255, 255, 0.9);
            margin-bottom: 0.5rem;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }

        .stat-content .stat-number {
            font-size: 2.25rem;
            font-weight: 800;
            color: white;
            line-height: 1;
        }

        .card-container {
            background-color: #ffffff;
            border-radius: 16px;
            padding: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
            margin-bottom: 2rem;
            border: 1px solid #e2e8f0;
        }

        .card-title {
            font-size: 1.25rem;
            font-weight: 700;
            color: #334155;
            margin-bottom: 1.5rem;
        }

        .btn-primary {
            font-weight: 600;
            border-radius: 8px;
        }

        .btn-secondary {
            background-color: #f1f5f9;
            border-color: #f1f5f9;
            color: #475569;
            font-weight: 600;
            border-radius: 8px;
        }

        .btn-secondary:hover {
            background-color: #e2e8f0;
            border-color: #e2e8f0;
            color: #334155;
        }

        @media print {
            .no-print {
                display: none !important;
            }

            body {
                background-color: #fff !important;
            }

            .stat-card,
            .card-container {
                box-shadow: none !important;
                border: 1px solid #ddd !important;
                break-inside: avoid;
            }

            .navbar-custom {
                display: none !important;
            }

            .container-fluid {
                padding: 0 !important;
            }

            .card-container {
                margin-bottom: 1rem !important;
            }
        }
    </style>
</head>

<body>
    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark navbar-custom">
        <div class="container-fluid">
            <span class="navbar-brand">
                <i class="bi bi-bar-chart-fill me-2"></i>
                Relatórios & Estatísticas
            </span>
            <div class="d-flex align-items-center text-white">
                <span class="me-3">Olá, <?= htmlspecialchars($_SESSION['nome'] ?? 'Usuário') ?></span>
                <a href="<?= BASE_URL ?>/src/views/relatorios/index.php?action=porUsuario"
                    class="btn btn-outline-light btn-sm me-2">
                    <i class="bi bi-person-lines-fill"></i> Por Usuário
                </a>
                <a href="<?= BASE_URL ?>/src/views/relatorios/index.php?action=liderancas"
                    class="btn btn-outline-light btn-sm me-2">
                    <i class="bi bi-people-fill"></i> Listar Lideranças
                </a>
                <a href="<?= BASE_URL ?>/src/views/eleitores/lista.php/" class="btn btn-outline-light btn-sm">
                    <i class="bi bi-backspace"></i>Volta
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid py-4">
        <div class="container">

            <?php if (isset($erro)): ?>
                <div class="alert alert-danger"><?= htmlspecialchars($erro) ?></div>
            <?php else: ?>

                <section class="row row-cols-1 row-cols-md-2 row-cols-xl-4 g-4 mb-5">
                    <div class="col">
                        <div class="stat-card">
                            <div class="d-flex align-items-center">
                                <div class="stat-icon icon-users me-3"><i class="fas fa-users"></i></div>
                                <div class="stat-content">
                                    <h6 class="stat-label">Total de Eleitores</h6>
                                    <div class="stat-number">
                                        <?= isset($dados['totalEleitores']) ? number_format($dados['totalEleitores']) : 0 ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div class="stat-card">
                            <div class="d-flex align-items-center">
                                <div class="stat-icon icon-map me-3"><i class="fas fa-map-marker-alt"></i></div>
                                <div class="stat-content">
                                    <h6 class="stat-label">Bairros Atendidos</h6>
                                    <div class="stat-number">
                                        <?= isset($dados['porBairro']) ? count($dados['porBairro']) : 0 ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div class="stat-card">
                            <div class="d-flex align-items-center">
                                <div class="stat-icon icon-tags me-3"><i class="fas fa-tags"></i></div>
                                <div class="stat-content">
                                    <h6 class="stat-label">Tipos de Eleitor</h6>
                                    <div class="stat-number"><?= isset($dados['porTipo']) ? count($dados['porTipo']) : 0 ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div class="stat-card">
                            <div class="d-flex align-items-center">
                                <div class="stat-icon icon-gender me-3"><i class="fas fa-venus-mars"></i></div>
                                <div class="stat-content">
                                    <h6 class="stat-label">Gêneros</h6>
                                    <div class="stat-number"><?= isset($dados['porSexo']) ? count($dados['porSexo']) : 0 ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </section>

                <section class="row">
                    <div class="col-12">
                        <?php if (!empty($dados['porDemandaEleitores'])): ?>
                            <div class="card-container">
                                <h5 class="card-title">Demandas dos Eleitores</h5>
                                <div style="height: 350px;">
                                    <canvas id="demandaEleitoresChart"></canvas>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($dados['porDemanda'])): ?>
                            <div class="card-container">
                                <h5 class="card-title">Distribuição por Demanda</h5>
                                <div style="height: 350px;">
                                    <canvas id="demandaChart"></canvas>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($dados['porBairro'])): ?>
                            <div class="card-container">
                                <h5 class="card-title">Eleitores por Bairro</h5>
                                <div style="height: 350px;">
                                    <canvas id="bairroChart"></canvas>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($dados['porSexo'])): ?>
                            <div class="card-container">
                                <h5 class="card-title">Distribuição por Gênero</h5>
                                <div style="height: 350px;">
                                    <canvas id="sexoChart"></canvas>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($dados['porTipo'])): ?>
                            <div class="card-container">
                                <h5 class="card-title">Distribuição por Tipo de Eleitor</h5>
                                <div style="height: 350px;">
                                    <canvas id="tipoChart"></canvas>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </section>
            <?php endif; ?>
            </main>

            <script>
                const CHART_COLORS = [
                    '#3b82f6', '#94a3b8', '#22c55e', '#f97316', '#8b5cf6', '#db2777', '#f59e0b', '#14b8a6'
                ];

                Chart.defaults.font.family = "'Plus Jakarta Sans', sans-serif";
                Chart.defaults.plugins.legend.position = 'bottom';
                Chart.defaults.responsive = true;
                Chart.defaults.maintainAspectRatio = false;

                <?php if (!empty($dados['porBairro'])): ?>
                        (() => {
                            const dataValues = <?= json_encode(array_values($dados['porBairro'])) ?>;
                            const maxValue = Math.max(...dataValues);
                            const suggestedMax = Math.max(5, Math.ceil((maxValue * 1.2) / 5) * 5);

                            new Chart(document.getElementById('bairroChart'), {
                                type: 'bar',
                                data: {
                                    labels: <?= json_encode(array_keys($dados['porBairro'])) ?>,
                                    datasets: [{
                                        label: 'Eleitores',
                                        data: dataValues,
                                        backgroundColor: 'rgba(59, 130, 246, 0.75)',
                                        borderColor: '#3b82f6',
                                        borderWidth: 2,
                                        borderRadius: 6,
                                    }]
                                },
                                options: {
                                    scales: {
                                        y: {
                                            beginAtZero: true,
                                            suggestedMax: suggestedMax,
                                            ticks: { precision: 0 }
                                        },
                                    },
                                    plugins: {
                                        legend: { display: false }
                                    }
                                }
                            });
                        })();
                <?php endif; ?>

                <?php if (!empty($dados['porSexo'])): ?>
                    new Chart(document.getElementById('sexoChart'), {
                        type: 'doughnut',
                        data: {
                            labels: <?= json_encode(array_keys($dados['porSexo'])) ?>,
                            datasets: [{
                                data: <?= json_encode(array_values($dados['porSexo'])) ?>,
                                backgroundColor: CHART_COLORS,
                                borderColor: '#ffffff',
                                borderWidth: 4,
                                hoverOffset: 10
                            }]
                        },
                        options: {
                            cutout: '70%',
                        }
                    });
                <?php endif; ?>

                <?php if (!empty($dados['porTipo'])): ?>
                    new Chart(document.getElementById('tipoChart'), {
                        type: 'pie',
                        data: {
                            labels: <?= json_encode(array_keys($dados['porTipo'])) ?>,
                            datasets: [{
                                data: <?= json_encode(array_values($dados['porTipo'])) ?>,
                                backgroundColor: CHART_COLORS,
                                borderColor: '#ffffff',
                                borderWidth: 4,
                                hoverOffset: 10
                            }]
                        },
                        options: {
                            plugins: {
                                legend: {
                                    position: 'right',
                                }
                            }
                        }
                    });
                <?php endif; ?>

                <?php if (!empty($dados['porDemandaEleitores'])): ?>
                    new Chart(document.getElementById('demandaEleitoresChart'), {
                        type: 'pie',
                        data: {
                            labels: <?= json_encode(array_keys($dados['porDemandaEleitores'])) ?>,
                            datasets: [{
                                data: <?= json_encode(array_values($dados['porDemandaEleitores'])) ?>,
                                backgroundColor: CHART_COLORS,
                                borderColor: '#ffffff',
                                borderWidth: 4,
                                hoverOffset: 10
                            }]
                        },
                        options: {
                            plugins: {
                                legend: {
                                    position: 'right',
                                }
                            }
                        }
                    });
                <?php endif; ?>

                <?php if (!empty($dados['porDemanda'])): ?>
                    new Chart(document.getElementById('demandaChart'), {
                        type: 'pie',
                        data: {
                            labels: <?= json_encode(array_keys($dados['porDemanda'])) ?>,
                            datasets: [{
                                data: <?= json_encode(array_values($dados['porDemanda'])) ?>,
                                backgroundColor: CHART_COLORS.slice().reverse(),
                                borderColor: '#ffffff',
                                borderWidth: 4,
                                hoverOffset: 10
                            }]
                        },
                        options: {
                            plugins: {
                                legend: {
                                    position: 'right',
                                }
                            }
                        }
                    });
                <?php endif; ?>
            </script>
        </div>
    </div>
</body>

</html>