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

$usuario_id = (int)($_SESSION['usuario']['id'] ?? 0);
$perfil = $_SESSION['usuario']['perfil'] ?? '';

// Se não for professor ou não estiver logado, redireciona para login
if (strtoupper(trim($perfil)) !== 'PROFESSOR' || $usuario_id <= 0) {
    header('Location: login.php');
    exit;
}

$mensagem = '';
$tipo_mensagem = '';
$ano_lectivo_atual = '2025/2026'; // Defina o ano letivo atual

// Inicializa $prazo_fechado com um valor padrão
$prazo_fechado = false;

// --- Início: Lógica de Salvamento/Atualização de Notas ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['aluno_id'])) {
    $post_disciplina_id = (int)($_POST['disciplina_id'] ?? 0);
    $post_turma_id = (int)($_POST['turma_id'] ?? 0);
    $post_trimestre = (int)($_POST['trimestre'] ?? 0);
    $alunos_ids_post = $_POST['aluno_id'];

    if ($post_disciplina_id > 0 && $post_turma_id > 0 && $post_trimestre > 0 && !empty($alunos_ids_post)) {
        try {
            $conn->begin_transaction();

            $stmt_insert_update = $conn->prepare("
                INSERT INTO notas (
                    aluno_id, turma_id, disciplina_id, ano_lectivo, trimestre,
                    mac, npp, npt, mt, mfd, neo, nee, mec, mf
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                    mac = VALUES(mac),
                    npp = VALUES(npp),
                    npt = VALUES(npt),
                    mt = VALUES(mt),
                    mfd = VALUES(mfd),
                    neo = VALUES(neo),
                    nee = VALUES(nee),
                    mec = VALUES(mec),
                    mf = VALUES(mf)
            ");

            if (!$stmt_insert_update) {
                throw new Exception("Erro na preparação da query de insert/update: " . $conn->error);
            }

            foreach ($alunos_ids_post as $aluno_id) {
                // Captura os valores MAC, NPP e NPT do trimestre atual
                $mac = floatval($_POST["mac_{$post_trimestre}_{$aluno_id}"] ?? 0);
                $npp = floatval($_POST["npp_{$post_trimestre}_{$aluno_id}"] ?? 0);
                $npt = floatval($_POST["npt_{$post_trimestre}_{$aluno_id}"] ?? 0);

                // Recalcula MT do trimestre atual no servidor para garantir integridade
                $mt_atual_value = ($mac + $npp + $npt) / 3;

                // Captura as notas finais (MFD, NEO, etc.) que são enviadas como hidden
                $mfd = floatval($_POST["mfd_{$aluno_id}"] ?? 0);
                $neo = floatval($_POST["neo_{$aluno_id}"] ?? 0);
                $nee = floatval($_POST["nee_{$aluno_id}"] ?? 0);
                $mec = floatval($_POST["mec_{$aluno_id}"] ?? 0);
                $mf = floatval($_POST["mf_{$aluno_id}"] ?? 0);

                $stmt_insert_update->bind_param(
                    "iiiisddddddddd",
                    $aluno_id,
                    $post_turma_id,
                    $post_disciplina_id,
                    $ano_lectivo_atual,
                    $post_trimestre,
                    $mac,
                    $npp,
                    $npt,
                    $mt_atual_value, // MT atual
                    $mfd,
                    $neo,
                    $nee,
                    $mec,
                    $mf
                );
                $stmt_insert_update->execute();
            }
            $stmt_insert_update->close();
            $conn->commit();
            $mensagem = "Notas salvas/atualizadas com sucesso! ✅";
            $tipo_mensagem = 'success';
        } catch (Exception $e) {
            $conn->rollback();
            $mensagem = "Erro ao salvar/atualizar notas: " . $e->getMessage() . " ❌";
            $tipo_mensagem = 'error';
        }

        // Redireciona de volta para a mesma página com os parâmetros GET
        header("Location: mini_pauta_trimestres.php?turma_id={$post_turma_id}&disciplina_id={$post_disciplina_id}&trimestre={$post_trimestre}&msg=".urlencode($mensagem)."&type=".urlencode($tipo_mensagem));
        exit;
    } else {
        $mensagem = "Dados insuficientes para salvar as notas. ⚠️";
        $tipo_mensagem = 'error';
    }
}

// Recupera mensagens da sessão após um redirecionamento
if (isset($_GET['msg']) && isset($_GET['type'])) {
    $mensagem = htmlspecialchars($_GET['msg']);
    $tipo_mensagem = htmlspecialchars($_GET['type']);
}

// Carregar nome do professor
$nome_professor = '';
$sqlNome = "SELECT nome FROM usuarios WHERE id = ? LIMIT 1";
$stmt = $conn->prepare($sqlNome);
if ($stmt) {
    $stmt->bind_param("i", $usuario_id);
    $stmt->execute();
    $resNome = $stmt->get_result();
    if ($resNome && $resNome->num_rows === 1) {
        $rowNome = $resNome->fetch_assoc();
        $nome_professor = $rowNome['nome'];
    }
    $stmt->close();
}

// Inicialização de variáveis para filtros
$turma_id = isset($_GET['turma_id']) ? (int)$_GET['turma_id'] : null;
$disciplina_id = isset($_GET['disciplina_id']) ? (int)$_GET['disciplina_id'] : null;
$trimestre_selecionado = isset($_GET['trimestre']) ? (int)$_GET['trimestre'] : null;

// Carregar turmas para o professor
$turmas = false;
$sqlTurmas = "
    SELECT DISTINCT t.id, CONCAT(t.classe, ' - ', t.nome, ' - ', t.curso, ' - ', t.turno) AS descricao
    FROM turmas t
    INNER JOIN atribuicoes a ON t.id = a.turma_id
    WHERE a.professor_id = ? AND a.ano_lectivo = ?
    ORDER BY t.classe, t.nome
";
$stmt = $conn->prepare($sqlTurmas);
if ($stmt) {
    $stmt->bind_param("is", $usuario_id, $ano_lectivo_atual);
    $stmt->execute();
    $turmas_res = $stmt->get_result();
    $turmas = $turmas_res->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
}

// Carregar disciplinas para o professor
$disciplinas_res = false;
$sqlDisciplinas = "
    SELECT DISTINCT d.id, d.nome
    FROM atribuicoes a
    INNER JOIN disciplinas d ON a.disciplina_id = d.id
    WHERE a.professor_id = ? AND a.ano_lectivo = ?
    ORDER BY d.nome
";
$stmt = $conn->prepare($sqlDisciplinas);
if ($stmt) {
    $stmt->bind_param("is", $usuario_id, $ano_lectivo_atual);
    $stmt->execute();
    $disciplinas_res = $stmt->get_result();
    $stmt->close();
}

// Obter o nome da disciplina selecionada
$nome_disciplina = '';
if ($disciplina_id) {
    $sqlNomeDisciplina = "SELECT nome FROM disciplinas WHERE id = ?";
    $stmt = $conn->prepare($sqlNomeDisciplina);
    if ($stmt) {
        $stmt->bind_param("i", $disciplina_id);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($res->num_rows > 0) {
            $row = $res->fetch_assoc();
            $nome_disciplina = $row['nome'];
        }
        $stmt->close();
    }
}

// Carregar alunos e notas se todos os filtros estiverem selecionados
$alunos = [];
$notas_por_aluno = [];
if ($turma_id && $disciplina_id && $trimestre_selecionado) {
    // === VERIFICAÇÃO DO FECHO DE PRAZO ===
    $sqlCheckFecho = "SELECT COUNT(*) FROM fecho_trimestre WHERE turma_id = ? AND disciplina_id = ? AND trimestre = ? AND ano_lectivo = ?";
    $stmtCheckFecho = $conn->prepare($sqlCheckFecho);
    $stmtCheckFecho->bind_param("iiis", $turma_id, $disciplina_id, $trimestre_selecionado, $ano_lectivo_atual);
    $stmtCheckFecho->execute();
    $count = $stmtCheckFecho->get_result()->fetch_row()[0];
    $stmtCheckFecho->close();
    $prazo_fechado = ($count > 0);
    // ===================================

    $sqlAlunos = "SELECT id, nome FROM alunos WHERE turma_id = ? ORDER BY nome";
    $stmtAlunos = $conn->prepare($sqlAlunos);
    $stmtAlunos->bind_param("i", $turma_id);
    $stmtAlunos->execute();
    $alunos_res = $stmtAlunos->get_result();
    $alunos_data = $alunos_res->fetch_all(MYSQLI_ASSOC);
    $stmtAlunos->close();

    $aluno_ids = array_column($alunos_data, 'id');
    if (!empty($aluno_ids)) {
        // Carrega as notas de TODOS os trimestres para a pauta
        $in_clause = str_repeat('?,', count($aluno_ids) - 1) . '?';
        $sqlNotas = "SELECT * FROM notas WHERE aluno_id IN ($in_clause) AND disciplina_id = ? AND turma_id = ? AND ano_lectivo = ?";
        
        $params_types = str_repeat('i', count(array_keys($aluno_ids))) . 'iis';
        $params = array_merge($aluno_ids, [$disciplina_id, $turma_id, $ano_lectivo_atual]);
        
        $stmtNotas = $conn->prepare($sqlNotas);
        $stmtNotas->bind_param($params_types, ...$params);
        $stmtNotas->execute();
        $notas_res = $stmtNotas->get_result();
        
        while ($nota = $notas_res->fetch_assoc()) {
            $notas_por_aluno[$nota['aluno_id']][$nota['trimestre']] = $nota;
        }
        $stmtNotas->close();
    }
    $alunos = $alunos_data;
}
?>

<!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">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body { font-family: 'Inter', sans-serif; }
        .nota-baixa { color: #ef4444; font-weight: bold; }
        
        @media print {
            @page { size: a4 portrait; }
            .no-print, .topo-form { display: none !important; }
            body { background-color: #ffffff !important; font-size: 10px !important; padding: 0 !important; margin: 0 !important; }
            header { text-align: center; margin-bottom: 10px; }
            header img { width: 80px; }
            h1, h2 { font-size: 12px; }
            .painel { box-shadow: none !important; border-radius: 0 !important; padding: 0 !important; overflow-x: visible !important; }
            table { width: 100% !important; min-width: 100% !important; font-size: 10px !important; table-layout: fixed; }
            th, td { padding: 2px !important; word-wrap: break-word; white-space: normal; overflow: hidden; text-overflow: ellipsis; }
            input[type="number"][readonly] { border: none !important; background-color: transparent !important; padding: 0 !important; }
            .print-flex { display: flex !important; justify-content: space-around !important; }
            .signatures-section { margin-top: 0 !important; }
            table input[type="number"] { width: auto !important; }
        }

        table, th, td { border: 1px solid #ccc; }
        .col-separator-th { border-right: 2px solid #666 !important; }
        .col-separator-td { border-right: 2px solid #666 !important; }
        table input[type="number"] { text-align: center; }
        table span[class$="_display"] { display: inline-block; width: 100%; text-align: center; }
        input[disabled] { background-color: #e2e8f0; cursor: not-allowed; }
        .alert-message { padding: 1rem; margin-bottom: 1rem; border-radius: 0.5rem; font-weight: bold; }
        .alert-message.success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert-message.error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
    </style>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const form = document.getElementById('notas-form');
            const nomeDisciplina = form ? form.getAttribute('data-disciplina-nome').toLowerCase() : '';
            const trimestreSelecionado = parseInt(document.getElementById('trimestre').value) || 1;

            function pintarNotas(linha) {
                const notasCampos = linha.querySelectorAll(
                    `input[name^="mac"][type="number"],
                     input[name^="npp"][type="number"],
                     input[name^="npt"][type="number"],
                     input[name^="neo"][type="number"],
                     input[name^="nee"][type="number"],
                     .mt_display, .mfd_display, .mf_display, .mec_display`
                );
                
                notasCampos.forEach(campo => {
                    let valorNota = parseFloat(campo.value || campo.textContent);
                    
                    if (!isNaN(valorNota)) {
                        if (valorNota < 10) {
                            campo.classList.add('nota-baixa');
                        } else {
                            campo.classList.remove('nota-baixa');
                        }
                    } else {
                        campo.classList.remove('nota-baixa');
                    }
                });
            }

            function calcularNotas(linha) {
                const alunoId = linha.getAttribute('data-aluno-id');

                // 1. Coleta e calcula MT do trimestre atual
                const macInput = linha.querySelector(`input[name="mac_${trimestreSelecionado}_${alunoId}"]`);
                const nppInput = linha.querySelector(`input[name="npp_${trimestreSelecionado}_${alunoId}"]`);
                const nptInput = linha.querySelector(`input[name="npt_${trimestreSelecionado}_${alunoId}"]`);
                
                const mac = parseFloat(macInput?.value) || 0;
                const npp = parseFloat(nppInput?.value) || 0;
                const npt = parseFloat(nptInput?.value) || 0;
                
                let mtAtual = (mac + npp + npt) / 3;
                
                // Exibe e salva o MT do trimestre atual
                linha.querySelector(`.mt${trimestreSelecionado}_display`).textContent = mtAtual.toFixed(2);
                linha.querySelector(`input[name="mt_${trimestreSelecionado}_${alunoId}"]`).value = mtAtual.toFixed(2);

                // 2. Coleta MTs de todos os trimestres (dos hidden inputs) para MFD
                const mt1 = parseFloat(linha.querySelector(`input[name="mt_1_${alunoId}"]`)?.value) || 0;
                const mt2 = parseFloat(linha.querySelector(`input[name="mt_2_${alunoId}"]`)?.value) || 0;
                const mt3 = parseFloat(linha.querySelector(`input[name="mt_3_${alunoId}"]`)?.value) || 0;
                
                let mfd_soma = 0;
                let mfd_count = 0;
                if (mt1 > 0) { mfd_soma += mt1; mfd_count++; }
                if (mt2 > 0) { mfd_soma += mt2; mfd_count++; }
                if (mt3 > 0) { mfd_soma += mt3; mfd_count++; }
                
                const mfd = mfd_count > 0 ? mfd_soma / mfd_count : 0;
                
                linha.querySelector('.mfd_display').textContent = mfd.toFixed(2);
                linha.querySelector(`input[name="mfd_${alunoId}"]`).value = mfd.toFixed(2);

                // 3. Calcula MEC e MF (só para o 3º trimestre)
                const neoInput = linha.querySelector(`input[name="neo_${alunoId}"]`);
                const neeInput = linha.querySelector(`input[name="nee_${alunoId}"]`);
                const neo = parseFloat(neoInput?.value) || 0;
                const nee = parseFloat(neeInput?.value) || 0;
                
                let mf = 0;
                let mec = 0;

                if (nee > 0 && neo > 0) {
                    mec = (neo + nee) / 2;
                    mf = (mfd * 0.6) + (mec * 0.4);
                } else if (nee > 0 && neo === 0) {
                    mec = nee;
                    mf = (mfd * 0.6) + (nee * 0.4);
                } else {
                    mec = 0;
                    mf = mfd;
                }
                
                linha.querySelector('.mec_display').textContent = mec.toFixed(2);
                linha.querySelector(`input[name="mec_${alunoId}"]`).value = mec.toFixed(2);
                linha.querySelector('.mf_display').textContent = Math.round(mf);
                linha.querySelector(`input[name="mf_${alunoId}"]`).value = Math.round(mf);
                
                pintarNotas(linha);
            }
            
            // Adiciona event listeners e calcula notas ao carregar a página
            document.querySelectorAll('tbody tr').forEach(linha => {
                linha.querySelectorAll('input[type="number"]').forEach(input => {
                    if (!input.disabled) {
                        input.addEventListener('input', () => {
                            let val = parseFloat(input.value);
                            if (!isNaN(val)) {
                                if (val > 20) { input.value = 20; }
                                else if (val < 0) { input.value = 0; }
                            } else {
                                input.value = '';
                            }
                            calcularNotas(linha);
                        });
                        input.addEventListener('change', () => {
                            let val = parseFloat(input.value);
                            if (!isNaN(val)) {
                                input.value = val.toFixed(2);
                            }
                        });
                    }
                });
                calcularNotas(linha);
            });
        });
    </script>
</head>
<body class="bg-gray-100 text-gray-800 p-4 sm:p-8">

<div class="no-print fixed top-4 right-4 z-50 flex space-x-2 flex-wrap justify-center sm:static sm:top-auto sm:right-auto sm:space-x-4">
    <button type="submit" form="notas-form" class="bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-2 px-4 rounded-lg shadow-lg transition-colors flex-1 sm:flex-none" <?= $prazo_fechado ? 'disabled' : '' ?>>Salvar</button>
    <button type="button" onclick="window.print()" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg shadow-lg transition-colors flex-1 sm:flex-none">Imprimir</button>
    <button type="button" onclick="window.location.href = 'painel_professor.php'" class="bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded-lg shadow-lg transition-colors flex-1 sm:flex-none">Voltar</button>
</div>

<div class="no-print absolute top-8 left-8 text-sm text-gray-600 font-medium hidden sm:block">
    MINI PAUTAS DO(A) PROFESSOR(A): <strong class="text-gray-900"><?= htmlspecialchars($nome_professor ?? '') ?></strong>
</div>

<div class="max-w-7xl mx-auto bg-white rounded-xl shadow-lg p-6 sm:p-10">
    <header class="text-center mb-4 sm:mb-8">
        <img src="insignia/insignia.png" alt="Insígnia" class="w-16 sm:w-24 mx-auto mb-2 sm:mb-4">
        <h1 class="text-sm sm:text-lg">REPÚBLICA DE ANGOLA</h1>
        <h2 class="text-sm sm:text-lg">GOVERNO PROVINCIAL DE BENGUELA</h2>
        <h2 class="text-sm sm:text-lg">GABINETE PROVINCIAL DA EDUCAÇÃO</h2>
        <h2 class="text-sm sm:text-lg">MAGISTÉRIO BG 0038 5 - DE OUTUBRO – CATUMBELA</h2>
        <h2 class="text-base sm:text-xl font-bold">MINI-PAUTA</h2>
    </header>

    <?php if (!empty($mensagem)): ?>
        <div class="alert-message <?= htmlspecialchars($tipo_mensagem) ?>">
            <?= $mensagem ?>
        </div>
    <?php endif; ?>

    <div class="topo-form mb-6 p-4 rounded-lg shadow-sm bg-gray-50 flex flex-wrap items-center justify-center space-y-4 md:space-y-0 md:space-x-4">
        <form method="GET" action="" class="w-full md:w-auto flex flex-wrap items-center justify-center space-y-4 md:space-y-0 md:space-x-4">
            <div class="flex flex-col space-y-1 w-full sm:w-auto">
                <label for="turma_id" class="font-medium text-gray-700">Turma:</label>
                <select name="turma_id" id="turma_id" class="form-select border-gray-300 rounded-lg shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50 w-full" onchange="this.form.submit()">
                    <option value="">- Selecione a Turma -</option>
                    <?php
                    if ($turmas) {
                        foreach ($turmas as $row) {
                            $selected = ($row['id'] == $turma_id) ? 'selected' : '';
                            echo "<option value=\"{$row['id']}\" {$selected}>" . htmlspecialchars($row['descricao']) . "</option>";
                        }
                    }
                    ?>
                </select>
            </div>
            
            <div class="flex flex-col space-y-1 w-full sm:w-auto">
                <label for="disciplina_id" class="font-medium text-gray-700">Disciplina:</label>
                <select name="disciplina_id" id="disciplina_id" class="form-select border-gray-300 rounded-lg shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50 w-full" onchange="this.form.submit()">
                    <option value="">- Selecione a Disciplina -</option>
                    <?php
                    if ($disciplinas_res) {
                        $disciplinas_res->data_seek(0);
                        while($row = $disciplinas_res->fetch_assoc()) {
                            $selected = ($row['id'] == $disciplina_id) ? 'selected' : '';
                            echo "<option value=\"{$row['id']}\" {$selected}>" . htmlspecialchars($row['nome']) . "</option>";
                        }
                    }
                    ?>
                </select>
            </div>
            
            <div class="flex flex-col space-y-1 w-full sm:w-auto">
                <label for="trimestre" class="font-medium text-gray-700">Trimestre:</label>
                <select name="trimestre" id="trimestre" class="form-select border-gray-300 rounded-lg shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50 w-full" onchange="this.form.submit()">
                    <option value="">- Selecione o Trimestre -</option>
                    <?php for($i=1; $i<=3; $i++): ?>
                        <option value="<?= $i ?>" <?= ($i == $trimestre_selecionado) ? 'selected' : '' ?>>
                            Trimestre <?= $i ?>
                        </option>
                    <?php endfor; ?>
                </select>
            </div>
            
            <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg shadow-md transition-colors mt-6 w-full sm:w-auto">carregar Mini Pauta</button>
        </form>
    </div>
    
    <?php if ($prazo_fechado): ?>
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
        <strong class="font-bold">Atenção!</strong>
        <span class="block sm:inline">O prazo para lançamento de notas para esta disciplina e trimestre foi fechado. As notas não podem mais ser alteradas.</span>
    </div>
    <?php endif; ?>

    <?php if (!empty($alunos) && $disciplina_id && $trimestre_selecionado): ?>
    <form id="notas-form" method="POST" action="mini_pauta_trimestres.php" data-disciplina-nome="<?= htmlspecialchars($nome_disciplina) ?>">
        <input type="hidden" name="disciplina_id" value="<?= htmlspecialchars($disciplina_id) ?>">
        <input type="hidden" name="turma_id" value="<?= htmlspecialchars($turma_id) ?>">
        <input type="hidden" name="trimestre" value="<?= htmlspecialchars($trimestre_selecionado) ?>">

        <p class="mb-4 text-center font-bold text-base sm:text-lg p-2 rounded-md bg-gray-100 shadow-inner">
            <span class="text-gray-700">Disciplina:</span> <span class="text-blue-800"><?= htmlspecialchars($nome_disciplina) ?></span>, 
            <span class="text-gray-700">Trimestre:</span> <span class="text-blue-800"><?= htmlspecialchars($trimestre_selecionado) ?></span>
        </p>

        <div class="overflow-x-auto rounded-lg shadow-md border border-gray-200">
            <table class="min-w-full text-xs sm:text-sm text-left text-gray-600">
                <thead class="text-xs text-gray-700 uppercase bg-blue-100">
                    <tr>
                        <th scope="col" class="py-2 px-1 sm:px-2 col-separator-th" rowspan="2">Nº</th>
                        <th scope="col" class="py-2 px-1 sm:px-2 col-separator-th nome-aluno-cell" rowspan="2">Nome</th>
                        <?php for($t=1; $t<=3; $t++): ?>
                            <th scope="col" class="py-2 px-1 text-center <?= ($t < 3) ? 'col-separator-th' : '' ?>" colspan="4">Trimestre <?= $t ?></th>
                        <?php endfor; ?>
                        <th scope="col" class="py-2 px-1 text-center col-separator-th" rowspan="2">MFD</th>
                        <th scope="col" class="py-2 px-1 text-center col-separator-th" rowspan="2">NEO</th>
                        <th scope="col" class="py-2 px-1 text-center col-separator-th" rowspan="2">NEE</th>
                        <th scope="col" class="py-2 px-1 text-center col-separator-th" rowspan="2">MEC</th>
                        <th scope="col" class="py-2 px-1 text-center" rowspan="2">MF</th>
                    </tr>
                    <tr>
                        <?php for($t=1; $t<=3; $t++): ?>
                            <th scope="col" class="py-2 px-1 text-center">MAC</th>
                            <th scope="col" class="py-2 px-1 text-center">NPP</th>
                            <th scope="col" class="py-2 px-1 text-center">NPT</th>
                            <th scope="col" class="py-2 px-1 text-center <?= ($t < 3) ? 'col-separator-td' : '' ?>">MT</th>
                        <?php endfor; ?>
                    </tr>
                </thead>
                <tbody>
                <?php $n=1; foreach($alunos as $aluno):
                    $aluno_id = $aluno['id'];
                    $mt_sum = 0;
                    $mt_count = 0;
                ?>
                <tr class="bg-white border-b hover:bg-gray-50" data-aluno-id="<?= htmlspecialchars($aluno_id) ?>">
                    <td class="py-2 px-1 col-separator-td"><?= $n++ ?></td>
                    <td class="py-2 px-1 whitespace-nowrap col-separator-td nome-aluno-cell">
                        <?= htmlspecialchars($aluno['nome']) ?>
                        <input type="hidden" name="aluno_id[]" value="<?= htmlspecialchars($aluno_id) ?>">
                    </td>
                    
                    <?php 
                    for ($t = 1; $t <= 3; $t++):
                        $notas = $notas_por_aluno[$aluno_id][$t] ?? [];
                        $disabled_mac_npp_npt = ($t != $trimestre_selecionado || $prazo_fechado) ? 'disabled' : '';
                        $disabled_neo_nee = ($t != 3 || $prazo_fechado) ? 'disabled' : '';
                        $is_disciplina_lingua = (stristr($nome_disciplina, 'portuguesa') || stristr($nome_disciplina, 'inglesa'));
                        $disabled_neo_nee_final = ($disabled_neo_nee || !$is_disciplina_lingua) ? 'disabled' : '';

                        // Soma as notas dos trimestres para o cálculo da MFD
                        if (isset($notas['mt']) && $notas['mt'] > 0) {
                            $mt_sum += $notas['mt'];
                            $mt_count++;
                        }
                    ?>
                    <td class="py-2 px-1">
                        <input type="number" name="mac_<?= $t ?>_<?= $aluno_id ?>" value="<?= htmlspecialchars($notas['mac'] ?? '') ?>" min="0" max="20" step="0.01" <?= $disabled_mac_npp_npt ?> class="w-12 sm:w-16 text-center p-1 sm:p-2 border border-gray-300 rounded-md focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50">
                    </td>
                    <td class="py-2 px-1">
                        <input type="number" name="npp_<?= $t ?>_<?= $aluno_id ?>" value="<?= htmlspecialchars($notas['npp'] ?? '') ?>" min="0" max="20" step="0.01" <?= $disabled_mac_npp_npt ?> class="w-12 sm:w-16 text-center p-1 sm:p-2 border border-gray-300 rounded-md focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50">
                    </td>
                    <td class="py-2 px-1">
                        <input type="number" name="npt_<?= $t ?>_<?= $aluno_id ?>" value="<?= htmlspecialchars($notas['npt'] ?? '') ?>" min="0" max="20" step="0.01" <?= $disabled_mac_npp_npt ?> class="w-12 sm:w-16 text-center p-1 sm:p-2 border border-gray-300 rounded-md focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50">
                    </td>
                    <td class="py-2 px-1 <?= ($t < 3) ? 'col-separator-td' : '' ?>">
                        <span class="mt<?= $t ?>_display"><?= htmlspecialchars(number_format($notas['mt'] ?? 0, 2)) ?></span>
                        <input type="hidden" name="mt_<?= $t ?>_<?= $aluno_id ?>" value="<?= htmlspecialchars($notas['mt'] ?? 0) ?>">
                    </td>
                    <?php endfor; ?>
                    
                    <?php
                    $mfd_value = ($mt_count > 0) ? $mt_sum / $mt_count : 0;
                    $neo_value = $notas_por_aluno[$aluno_id][3]['neo'] ?? 0;
                    $nee_value = $notas_por_aluno[$aluno_id][3]['nee'] ?? 0;
                    
                    $mec_value = 0;
                    $mf_value = 0;

                    if ($nee_value > 0 && $neo_value > 0) {
                        $mec_value = ($neo_value + $nee_value) / 2;
                        $mf_value = ($mfd_value * 0.6) + ($mec_value * 0.4);
                    } else if ($nee_value > 0 && $neo_value === 0) {
                        $mec_value = $nee_value;
                        $mf_value = ($mfd_value * 0.6) + ($nee_value * 0.4);
                    } else {
                        $mec_value = 0;
                        $mf_value = $mfd_value;
                    }
                    ?>

                    <td class="py-2 px-1 col-separator-td">
                        <span class="mfd_display"><?= htmlspecialchars(number_format($mfd_value, 2)) ?></span>
                        <input type="hidden" name="mfd_<?= $aluno_id ?>" value="<?= htmlspecialchars($mfd_value) ?>">
                    </td>
                    <td class="py-2 px-1 col-separator-td">
                        <input type="number" name="neo_<?= $aluno_id ?>" value="<?= htmlspecialchars($neo_value) ?>" min="0" max="20" step="0.01" <?= $disabled_neo_nee_final ?> class="w-12 sm:w-16 text-center p-1 sm:p-2 border border-gray-300 rounded-md focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50">
                    </td>
                    <td class="py-2 px-1 col-separator-td">
                        <input type="number" name="nee_<?= $aluno_id ?>" value="<?= htmlspecialchars($nee_value) ?>" min="0" max="20" step="0.01" <?= $disabled_neo_nee_final ?> class="w-12 sm:w-16 text-center p-1 sm:p-2 border border-gray-300 rounded-md focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50">
                    </td>
                    <td class="py-2 px-1 col-separator-td">
                        <span class="mec_display"><?= htmlspecialchars(number_format($mec_value, 2)) ?></span>
                        <input type="hidden" name="mec_<?= $aluno_id ?>" value="<?= htmlspecialchars($mec_value) ?>">
                    </td>
                    <td class="py-2 px-1">
                        <span class="mf_display"><?= htmlspecialchars(round($mf_value)) ?></span>
                        <input type="hidden" name="mf_<?= $aluno_id ?>" value="<?= htmlspecialchars(round($mf_value)) ?>">
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </form>
    <?php elseif ($turma_id && $disciplina_id && $trimestre_selecionado): ?>
        <p class="text-center text-lg text-gray-500 mt-8">Nenhum aluno encontrado para a turma selecionada.</p>
    <?php else: ?>
        <p class="text-center text-lg text-gray-500 mt-8">Selecione a Turma, a Disciplina e o Trimestre para começar.</p>
    <?php endif; ?>
</div>

<footer class="mt-8 text-center text-gray-500 text-sm">
    <p>&copy; MAGISTÉRIO. Todos os direitos reservados.</p>
</footer>

</body>
</html>