<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'conexao.php'; 

// 1. LISTAR TURMAS PARA O FILTRO
$turmas = [];
$resTurmas = $conn->query("SELECT id, nome, classe, curso, turno FROM turmas ORDER BY curso, classe, nome");
while ($row = $resTurmas->fetch_assoc()) { $turmas[] = $row; }

$turma_id = isset($_GET['turma_id']) ? (int)$_GET['turma_id'] : 0;
$resultados = [];
$disciplinasGrafico = [];
$percentAproveitamentoGrafico = [];
$coresGrafico = [];
$ano_lectivo = '2025/2026'; 

if ($turma_id > 0) {
    // 2. PEGAR ALUNOS DA TURMA
    $alunosMatriculados = [];
    $sqlAlunos = "SELECT a.id, a.genero, a.transferido FROM alunos a 
                  JOIN matriculas m ON m.aluno_id = a.id WHERE m.turma_id = ?";
    $stmt = $conn->prepare($sqlAlunos);
    $stmt->bind_param("i", $turma_id);
    $stmt->execute();
    $resAlunos = $stmt->get_result();
    while ($a = $resAlunos->fetch_assoc()) { $alunosMatriculados[] = $a; }
    $totalAlunos = count($alunosMatriculados);

    // 3. PEGAR DISCIPLINAS DA TURMA SELECIONADA
    $sqlDisc = "SELECT d.id, d.nome 
                FROM disciplinas d
                INNER JOIN atribuicoes a 
                    ON a.disciplina_id = d.id 
                    AND a.turma_id = ?
                    AND a.ano_lectivo = ?
                ORDER BY d.nome";
    $stmtD = $conn->prepare($sqlDisc);
    $stmtD->bind_param("is", $turma_id, $ano_lectivo);
    $stmtD->execute();
    $resDisc = $stmtD->get_result();

    while ($disc = $resDisc->fetch_assoc()) {
        $disc_id = $disc['id'];
        $disc_nome = $disc['nome'];

        // 4. NOTAS DA DISCIPLINA
        $sqlNotas = "SELECT aluno_id, mac, npt FROM notas WHERE turma_id = ? AND disciplina_id = ?";
        $stmtN = $conn->prepare($sqlNotas);
        $stmtN->bind_param("ii", $turma_id, $disc_id);
        $stmtN->execute();
        $resN = $stmtN->get_result();
        
        $notas = [];
        while($n = $resN->fetch_assoc()){
            $notas[$n['aluno_id']] = (($n['mac'] ?? 0) + ($n['npt'] ?? 0)) / 2;
        }

        // CONTADORES
        $avaliados = $avM = $avF = $aprov = $apM = $apF = $reprov = $reM = $reF = $desist = 0;

        foreach ($alunosMatriculados as $aluno) {
            $idA = $aluno['id'];
            if (isset($notas[$idA])) {
                $avaliados++;
                if ($aluno['genero'] == 'Masculino') $avM++; else $avF++;

                if ($notas[$idA] >= 9.5) {
                    $aprov++;
                    if ($aluno['genero'] == 'Masculino') $apM++; else $apF++;
                } else {
                    $reprov++;
                    if ($aluno['genero'] == 'Masculino') $reM++; else $reF++;
                }
            } else {
                $desist++;
            }
        }

        $pAprov = $avaliados > 0 ? round(($aprov / $avaliados) * 100, 1) : 0;
        
        $resultados[] = [
            'disciplina' => $disc_nome, 'total' => $totalAlunos,
            'av' => $avaliados, 'avM' => $avM, 'avF' => $avF,
            'ap' => $aprov, 'apM' => $apM, 'apF' => $apF, 'pAp' => $pAprov,
            're' => $reprov, 'reM' => $reM, 'reF' => $reF, 'des' => $desist
        ];

        $disciplinasGrafico[] = $disc_nome;
        $percentAproveitamentoGrafico[] = $pAprov;
        $coresGrafico[] = ($pAprov < 50) ? 'rgba(231, 76, 60, 0.8)' : 'rgba(46, 204, 113, 0.8)';
    }
}
?>

<!DOCTYPE html>
<html lang="pt-pt">
<head>
    <meta charset="UTF-8">
    <title>Estatística de Turma</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        @media print { .no-print { display: none; } body { background: white; } }
        table { border-collapse: collapse; width: 100%; font-size: 11px; }
        th, td { border: 1px solid black; padding: 4px; text-align: center; }
        th { background: #f3f4f6; }
    </style>
</head>
<body style="font-family: Arial, sans-serif; background:#f0f4f8; padding:20px;">

<div style="max-width:1000px; margin:auto; background:#fff; padding:20px; border-radius:10px; box-shadow:0 5px 20px rgba(0,0,0,0.1)">

    <div class="no-print" style="margin-bottom:20px; padding:10px; background:#e8f0fe; border-radius:8px;">
        <form method="GET" style="display:flex; gap:10px; align-items:flex-end;">
            <div style="flex:1;">
                <label style="font-weight:bold;">Selecione a Turma:</label>
                <select name="turma_id" style="width:100%; padding:8px; border-radius:6px; border:1px solid #ccc;" onchange="this.form.submit()">
                    <option value="">-- Escolha --</option>
                    <?php foreach ($turmas as $t): ?>
                        <option value="<?= $t['id'] ?>" <?= $turma_id == $t['id'] ? 'selected' : '' ?>>
                            <?= "{$t['classe']}ª {$t['nome']} - {$t['curso']} ({$t['turno']})" ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="button" onclick="window.print()" style="background:#2ecc71; color:#fff; padding:10px 20px; border:none; border-radius:6px; font-weight:bold; cursor:pointer;">
                IMPRIMIR
            </button>
        </form>
    </div>

    <?php if ($turma_id > 0): ?>
        <div style="text-align:center; margin-bottom:20px;">
            <h2 style="margin:0; font-weight:bold;">REPÚBLICA DE ANGOLA</h2>
            <p style="margin:2px 0;">COMPLEXO ESCOLAR CATÓLICO Nº 0026 BLA - PADRE EMIL FRICK</p>
            <h3 style="margin:5px 0; background:#f0f0f0; padding:5px;">Estatística de Aproveitamento - Ano Lectivo <?= $ano_lectivo ?></h3>
        </div>

        <!-- Cards -->
        <div style="display:grid; grid-template-columns: repeat(auto-fit,minmax(200px,1fr)); gap:10px; margin-bottom:20px;" class="no-print">
            <?php foreach($resultados as $r): ?>
                <div style="padding:10px; border-left:5px solid <?= $r['pAp'] < 50 ? '#e74c3c' : '#2ecc71' ?>; background:#f9f9f9; border-radius:6px;">
                    <p style="margin:0; font-weight:bold; font-size:12px;"><?= $r['disciplina'] ?></p>
                    <p style="margin:5px 0; font-size:20px; font-weight:bold;"><?= $r['pAp'] ?>%</p>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Gráfico -->
        <div class="no-print" style="margin-bottom:30px;">
            <canvas id="graficoAproveitamento" height="100"></canvas>
        </div>

        <!-- Tabela -->
        <table>
            <thead>
                <tr>
                    <th rowspan="2">DISCIPLINA</th>
                    <th rowspan="2">TOTAL</th>
                    <th colspan="3">AVALIADOS</th>
                    <th colspan="4">APROVEITAMENTO</th>
                    <th colspan="3">NEGATIVAS</th>
                    <th rowspan="2">DES.</th>
                </tr>
                <tr>
                    <th>T</th><th>M</th><th>F</th>
                    <th>T</th><th>M</th><th>F</th><th>%</th>
                    <th>T</th><th>M</th><th>F</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($resultados as $r): ?>
                <tr>
                    <td style="text-align:left; font-weight:bold;"><?= $r['disciplina'] ?></td>
                    <td><?= $r['total'] ?></td>
                    <td><?= $r['av'] ?></td><td><?= $r['avM'] ?></td><td><?= $r['avF'] ?></td>
                    <td style="background:#dff0d8;"><?= $r['ap'] ?></td><td><?= $r['apM'] ?></td><td><?= $r['apF'] ?></td>
                    <td style="font-weight:bold; color:<?= $r['pAp'] < 50 ? '#e74c3c' : '#2ecc71' ?>;"><?= $r['pAp'] ?>%</td>
                    <td style="background:#f2dede;"><?= $r['re'] ?></td><td><?= $r['reM'] ?></td><td><?= $r['reF'] ?></td>
                    <td><?= $r['des'] ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <script>
            new Chart(document.getElementById('graficoAproveitamento'), {
                type: 'bar',
                data: {
                    labels: <?= json_encode($disciplinasGrafico) ?>,
                    datasets: [{
                        label: '% Aproveitamento por Disciplina',
                        data: <?= json_encode($percentAproveitamentoGrafico) ?>,
                        backgroundColor: <?= json_encode($coresGrafico) ?>
                    }]
                },
                options: { 
                    scales: { y: { beginAtZero: true, max: 100 } },
                    plugins: { legend: { display: false } }
                }
            });
        </script>

    <?php else: ?>
        <p style="text-align:center; color:#777; padding:50px 0;">Selecione uma turma acima para gerar o relatório.</p>
    <?php endif; ?>

</div>
</body>
</html>
