<?php
 include 'conexao.php';
 session_start();

 $turma_id      = isset($_GET['turma_id']) ? (int)$_GET['turma_id'] : null;
 $disciplina_id = isset($_GET['disciplina_id']) ? (int)$_GET['disciplina_id'] : null;
 $trimestre     = isset($_GET['trimestre']) ? (int)$_GET['trimestre'] : null;

 // Verifica se perfil é da área pedagógica
 $perfil = strtoupper($_SESSION['usuario']['perfil'] ?? '');
 if (!in_array($perfil, ['SUBDIRECÇÃO PEDAGÓGICA', 'SECRETARIA PEDAGÓGICA'])) {
     header("Location: login.php");
     exit;
 }

 function getNotas($conn, $aluno_id, $disciplina_id, $trimestre) {
     $aluno_id      = (int)$aluno_id;
     $disciplina_id = (int)$disciplina_id;
     $trimestre     = (int)$trimestre;

     $sql = "SELECT * FROM notas
              WHERE aluno_id = $aluno_id
              AND disciplina_id = $disciplina_id
              AND trimestre = $trimestre";
     $result = $conn->query($sql);
     return $result ? $result->fetch_assoc() : null;
 }

 // Lista turmas do ano letivo
 $turmas = $conn->query("
      SELECT id, CONCAT(classe, ' - ', nome, ' - ', curso, ' - ', turno) AS descricao
      FROM turmas
      WHERE ano = '2025/2026'
      ORDER BY classe, nome
 ");

 // Lista disciplinas da turma selecionada via tabela atribuicoes
 $disciplinas = [];
 if ($turma_id) {
     $disciplinas = $conn->query("
          SELECT DISTINCT d.id, d.nome
          FROM atribuicoes a
          INNER JOIN disciplinas d ON a.disciplina_id = d.id
          WHERE a.turma_id = $turma_id
            AND a.ano_lectivo = '2025/2026'
          ORDER BY d.nome
     ");
 }

 // Lista alunos da turma
 $alunos = [];
 if ($turma_id) {
     $alunos = $conn->query("
          SELECT * FROM alunos
          WHERE turma_id = $turma_id
          ORDER BY nome
     ");
 }
?>
<!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <title>Mini Pauta Trimestres</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            font-family: 'Segoe UI', sans-serif;
            background-color: #e9ecef;
            padding: 20px;
            color: #343a40;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
        }

        header {
            text-align: center;
            margin-bottom: 25px;
            line-height: 1.4;
        }
        header img {
            width: 80px;
            height: auto;
            margin-bottom: 10px;
        }
        h1, h2 {
            margin: 0;
            font-weight: 600;
        }
        h2 {
            font-size: 1.1em;
            font-weight: 400;
        }

        .form-actions {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            align-items: flex-end;
            margin-bottom: 20px;
            gap: 10px;
        }

        form {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
        }

        select, button {
            padding: 10px 15px;
            border-radius: 5px;
            border: 1px solid #ced4da;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        button {
            background-color: #007bff;
            color: white;
            cursor: pointer;
            border: none;
        }
        button:hover {
            background-color: #0056b3;
        }
        
        #print-button {
            background-color: #6c757d;
        }
        #print-button:hover {
            background-color: #5a6268;
        }

        .table-responsive {
            overflow-x: auto;
        }

        table {
            border-collapse: collapse;
            width: 100%;
            min-width: 1200px;
            font-size: 13px;
        }

        th, td {
            border: 1px solid #dee2e6;
            padding: 8px;
            text-align: center;
        }
        
        th {
            background-color: #003366;
            color: white;
            font-weight: bold;
        }
        
        tbody tr:nth-child(even) {
            background-color: #f8f9fa;
        }

        tbody tr:hover {
            background-color: #e9ecef;
        }

        input[type="number"] {
            width: 50px;
            text-align: center;
            border: 1px solid #dee2e6;
            border-radius: 3px;
            transition: border-color 0.3s;
        }
        input[type="number"]:focus {
            border-color: #007bff;
            outline: none;
        }

        .vermelho {
            color: #dc3545;
            font-weight: bold;
        }
        
        .assinaturas {
            display: flex;
            justify-content: space-around;
            margin-top: 40px;
            text-align: center;
        }

        .assinaturas div {
            width: 45%;
        }

        .assinaturas strong {
            text-decoration: underline;
        }

        @media print {
            .form-actions, button {
                display: none;
            }
            body {
                background-color: white;
            }
            .container {
                box-shadow: none;
                padding: 0;
            }
            .assinaturas {
                page-break-before: always;
            }
            table {
                min-width: auto;
            }
        }
    </style>
  <script>
 document.addEventListener('DOMContentLoaded', () => {

     function pintarNotas(linha) {
         linha.querySelectorAll('input[type=number]').forEach(inp => {
             if (inp.value !== '' && parseFloat(inp.value) < 10) {
                 inp.classList.add('vermelho');
             } else {
                 inp.classList.remove('vermelho');
             }
         });
     }

     function calcularNotas(linha) {
         let av1 = parseFloat(linha.querySelector(`[name^="av1_"]`).value) || 0;
         let av2 = parseFloat(linha.querySelector(`[name^="av2_"]`).value) || 0;
         let av3 = parseFloat(linha.querySelector(`[name^="av3_"]`).value) || 0;
         let npt = parseFloat(linha.querySelector(`[name^="npt_"]`).value) || 0;
         
         // Fórmula para a Média Trimestral (MT)
         let mt = ((av1 + av2) / 2 * 0.4 + av3 * 0.1 + npt * 0.5).toFixed(1);

         let mtTd = linha.querySelector('.mt');
         if (mtTd) mtTd.textContent = mt;

         let mtInput = linha.querySelector(`[name^="mt<?= $trimestre ?>_"]`);
         if (mtInput) mtInput.value = mt;

         if (<?= $trimestre ?: 0 ?> === 3) {
             let mt1 = parseFloat(linha.querySelector(`[name^="mt1_"]`).value) || 0;
             let mt2 = parseFloat(linha.querySelector(`[name^="mt2_"]`).value) || 0;
             let mt3 = parseFloat(mt);
             let mfd = ((mt1 + mt2 + mt3) / 3).toFixed(1);
             let mfdTd = linha.querySelector('.mfd');
             if (mfdTd) mfdTd.textContent = mfd;
             let mfdInput = linha.querySelector(`[name^="mfd_"]`);
             if (mfdInput) mfdInput.value = mfd;

             let neo = parseFloat(linha.querySelector(`[name^="neo_"]`).value) || 0;
             let mf = ((parseFloat(mfd) + neo) / 2).toFixed(1);
             let mfTd = linha.querySelector('.mf');
             if (mfTd) mfTd.textContent = mf;
             let mfInput = linha.querySelector(`[name^="mf_"]`);
             if (mfInput) mfInput.value = mf;
         }

         pintarNotas(linha);
     }

     document.querySelectorAll('tbody tr').forEach(linha => {
         // Inicializa cálculo e pintura na carga
         calcularNotas(linha);

         // Adiciona o listener para recalcular e pintar ao digitar
         linha.querySelectorAll('input[type=number]').forEach(input => {
             input.addEventListener('input', () => calcularNotas(linha));
         });
     });

 });
 </script>


</head>
<body>
<div class="container">
    <header>
        <img src="insignia/insignia.png" alt="Insígnia da República de Angola">
        <h2>REPÚBLICA DE ANGOLA</h2>
        <h2>GOVERNO PROVINCIAL DE BENGUELA</h2>
        <h2>GABINETE PROVINCIAL DA EDUCAÇÃO</h2>
        <h1>COMPLEXO ESCOLAR BG0026 PADRE EMIL FRICK – CATUMBELA</h1>
        <h2>MINI-PAUTA</h2>
    </header>

    <div class="form-actions">
        <form method="GET">
            <select name="turma_id" id="turma_id" required>
                <option value="">Selecionar Turma</option>
                <?php while($t = $turmas->fetch_assoc()): ?>
                    <option value="<?= $t['id'] ?>" <?= $turma_id==$t['id'] ? 'selected' : '' ?>>
                        <?= $t['descricao'] ?>
                    </option>
                <?php endwhile; ?>
            </select>

            <select name="disciplina_id" id="disciplina_id" required>
                <option value="">Selecionar Disciplina</option>
                <?php if ($disciplinas && $disciplinas->num_rows > 0): ?>
                    <?php while($d = $disciplinas->fetch_assoc()): ?>
                        <option value="<?= $d['id'] ?>" <?= $disciplina_id==$d['id'] ? 'selected' : '' ?>>
                            <?= $d['nome'] ?>
                        </option>
                    <?php endwhile; ?>
                <?php endif; ?>
            </select>

            <select name="trimestre" required>
                <option value="">Selecionar Trimestre</option>
                <option value="1" <?= $trimestre==1 ? 'selected' : '' ?>>1º Trimestre</option>
                <option value="2" <?= $trimestre==2 ? 'selected' : '' ?>>2º Trimestre</option>
                <option value="3" <?= $trimestre==3 ? 'selected' : '' ?>>3º Trimestre</option>
            </select>
            <button type="submit">Ver</button>
        </form>
        <button id="print-button" onclick="window.print()">Imprimir</button>
    </div>

    <script>
        document.getElementById('turma_id').addEventListener('change', function() {
            let turmaId = this.value;
            let disciplinaSelect = document.getElementById('disciplina_id');
            disciplinaSelect.innerHTML = '<option value="">A carregar...</option>';

            if (turmaId) {
                fetch('get_disciplinas.php?turma_id=' + turmaId)
                    .then(response => response.text())
                    .then(data => {
                        disciplinaSelect.innerHTML = data;
                    });
            } else {
                disciplinaSelect.innerHTML = '<option value="">Selecionar Disciplina</option>';
            }
        });
    </script>

    <?php if ($alunos && $disciplina_id && $trimestre): ?>
    <div class="table-responsive">
        <form method="POST" action="salvar_notas.php">
            <input type="hidden" name="disciplina_id" value="<?= $disciplina_id ?>">
            <input type="hidden" name="turma_id" value="<?= $turma_id ?>">
            <input type="hidden" name="trimestre" value="<?= $trimestre ?>">

            <table>
                <thead>
                    <tr>
                        <th>Nº</th>
                        <th style="text-align: left;">Nome</th>
                        <?php for($i=1; $i<=3; $i++): ?>
                            <th>AV<?= $i ?></th>
                        <?php endfor; ?>
                        <th>NPT</th>
                        <th>MT<?= $trimestre ?></th>
                        <?php if ($trimestre == 3): ?>
                            <th>MFD</th><th>NEO</th><th>NEE</th><th>MEC</th><th>MF</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php $n=1; while($a = $alunos->fetch_assoc()):
                        $notas = getNotas($conn, $a['id'], $disciplina_id, $trimestre);
                    ?>
                    <tr oninput="calcularNotas(this)">
                        <td><?= $n++ ?></td>
                        <td style="text-align: left;">
                            <?= htmlspecialchars($a['nome']) ?>
                            <input type="hidden" name="aluno_id[]" value="<?= $a['id'] ?>">
                        </td>
                        <?php for($i=1; $i<=3; $i++): ?>
                            <td>
                                <input type="number" name="av<?= $i ?>_<?= $a['id'] ?>"
                                       value="<?= $notas['av'.($i)] ?? '' ?>"
                                       min="0" max="20" step="0.1">
                            </td>
                        <?php endfor; ?>
                        <td>
                            <input type="number" name="npt_<?= $a['id'] ?>"
                                       value="<?= $notas['npt'] ?? '' ?>"
                                       min="0" max="20" step="0.1">
                        </td>
                        <td>
                            <span class="mt"><?= $notas['mt'.$trimestre] ?? '' ?></span>
                            <input type="hidden" name="mt<?= $trimestre ?>_<?= $a['id'] ?>"
                                       value="<?= $notas['mt'.$trimestre] ?? '' ?>">
                        </td>
                        <?php if ($trimestre == 3): ?>
                            <td>
                                <span class="mfd"><?= $notas['mfd'] ?? '' ?></span>
                                <input type="hidden" name="mfd_<?= $a['id'] ?>" value="<?= $notas['mfd'] ?? '' ?>">
                            </td>
                            <td>
                                <input type="number" name="neo_<?= $a['id'] ?>"
                                       value="<?= $notas['neo'] ?? '' ?>" min="0" max="20" step="0.1">
                            </td>
                            <td>
                                <input type="number" name="nee_<?= $a['id'] ?>"
                                       value="<?= $notas['nee'] ?? '' ?>" min="0" max="20" step="0.1">
                            </td>
                            <td>
                                <input type="number" name="mec_<?= $a['id'] ?>"
                                       value="<?= $notas['mec'] ?? '' ?>" min="0" max="20" step="0.1">
                            </td>
                            <td>
                                <span class="mf"><?= $notas['mf'] ?? '' ?></span>
                                <input type="hidden" name="mf_<?= $a['id'] ?>" value="<?= $notas['mf'] ?? '' ?>">
                            </td>
                        <?php endif; ?>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
            <br>
            <button type="submit">Salvar Notas</button>
        </form>
    </div>
    <?php endif; ?>

    <div class="assinaturas">
        <div>
            <strong>O(A) PROFESSOR(A)</strong><br><br><br>
            <span>________________________________________</span><br>
            <small>CATUMBELA, AOS <?= date("d/m/Y"); ?></small>
        </div>
        <div>
            <strong>O(A) SUB-DIRECTOR(A) PEDAGÓGICO(A)</strong><br><br><br>
            <span>________________________________________</span><br>
            <small>Anacleto Domingos de Oliveira Cachiyenjo</small><br>
            <small>CATUMBELA, AOS <?= date("d/m/Y"); ?></small>
        </div>
    </div>
</div>
</body>
</html>