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

$turmas = $conn->query("SELECT id, classe, nome, curso, turno, ano FROM turmas ORDER BY classe, nome")->fetch_all(MYSQLI_ASSOC);
$turma_id = $_GET['turma_id'] ?? null;
$alunos = [];
$turma_id = $_GET['turma_id'] ?? null;
$ano_letivo = $_GET['ano_letivo'] ?? null;
$alunos = [];

if ($turma_id && $ano_letivo) {
    $stmt = $conn->prepare("
        SELECT a.id, a.nome, a.genero, a.idade
        FROM matriculas m
        JOIN alunos a ON m.aluno_id = a.id
        WHERE m.turma_id = ? AND m.ano_letivo = ?
        ORDER BY a.nome
    ");
    $stmt->bind_param("is", $turma_id, $ano_letivo);
    $stmt->execute();
    $alunos = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['salvar_notas'])) {
    $aluno_id = $_POST['aluno_id'];
    $turma_id = $_POST['turma_id'];
    $ano_lectivo = $_POST['ano_lectivo'];
    $notas = $_POST['notas'];

    foreach ($notas as $disciplina_id => $mf) {
        $verifica = $conn->prepare("SELECT id FROM notas WHERE aluno_id=? AND disciplina_id=? AND turma_id=? AND ano_lectivo=?");
        $verifica->bind_param("iiis", $aluno_id, $disciplina_id, $turma_id, $ano_lectivo);
        $verifica->execute();
        $verifica->store_result();

        if ($verifica->num_rows > 0) {
            $stmt = $conn->prepare("UPDATE notas SET mf=? WHERE aluno_id=? AND disciplina_id=? AND turma_id=? AND ano_lectivo=?");
            $stmt->bind_param("diiis", $mf, $aluno_id, $disciplina_id, $turma_id, $ano_lectivo);
            $stmt->execute();
        } else {
            $stmt = $conn->prepare("INSERT INTO notas (aluno_id, disciplina_id, turma_id, ano_lectivo, mf) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("iiisd", $aluno_id, $disciplina_id, $turma_id, $ano_lectivo, $mf);
            $stmt->execute();
        }
    }

    $msg = "Notas finais salvas com sucesso!";
}
?>
<!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <title>Lançar Notas Finais</title>
    <style>
        * { box-sizing: border-box; }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background: #f0f0f0; }

        .sidebar {
            width: 220px;
            background: #0a1733;
            color: white;
            position: fixed;
            top: 0;
            bottom: 0;
            padding-top: 60px;
        }

        .sidebar a {
            display: block;
            padding: 15px 20px;
            color: white;
            text-decoration: none;
            border-bottom: 1px solid #1e2d4d;
        }

        .sidebar a:hover {
            background: #1b2a4f;
        }

        .topbar {
            height: 60px;
            background: #0044cc;
            color: white;
            padding: 15px 30px;
            position: fixed;
            left: 220px;
            right: 0;
            top: 0;
            display: flex;
            align-items: center;
            font-size: 18px;
            font-weight: bold;
        }

        .main {
            margin-left: 220px;
            margin-top: 60px;
            padding: 20px;
        }

        .content-box {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px #ccc;
        }

        select, input[type="text"], input[type="number"] {
            width: 100%;
            padding: 8px;
            margin: 8px 0;
            border-radius: 5px;
            border: 1px solid #ccc;
        }

        .aluno-link {
            background: #f0f8ff;
            padding: 10px;
            margin: 5px 0;
            display: block;
            text-decoration: none;
            color: #003366;
            border-radius: 5px;
            border: 1px solid #cce;
        }

        .aluno-link:hover {
            background: #ddeeff;
        }

        button {
            background: #0044cc;
            color: white;
            padding: 10px 18px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-top: 10px;
        }

        .msg {
            background: #dff0d8;
            color: #3c763d;
            padding: 10px;
            margin-bottom: 15px;
            border-radius: 5px;
        }

        h2, h3 {
            margin-top: 0;
        }
    </style>
</head>
<body>

<!-- Barra Lateral -->
<div class="sidebar">
    <a href="painel_subpedagogico.php">🏠 Início</a>
    <a href="cadastrar_aluno.php">👨‍🎓 Alunos</a>
    <a href="cadastrar_turma.php">🏫 Turmas</a>
    <a href="cadastrar_disciplina.php">📚 Disciplinas</a>
    <a href="cadastrar_nota.php">📝 Lançar Notas</a>
</div>

<!-- Barra Superior -->
<div class="topbar">
    Sistema SISMAG — Lançamento de Notas Finais
</div>

<!-- Conteúdo Principal -->
<div class="main">
    <div class="content-box">
        <h2>Selecionar Turma</h2>

        <?php if (isset($msg)) echo "<div class='msg'>$msg</div>"; ?>

       <form method="get">
    <label>Turma:</label>
    <select name="turma_id" required>
        <option value="">-- Escolha a Turma --</option>
        <?php foreach ($turmas as $t):
            $rotulo = "{$t['classe']} - {$t['nome']} - {$t['curso']} - {$t['turno']} - {$t['ano']}";
        ?>
            <option value="<?= $t['id'] ?>" <?= $turma_id == $t['id'] ? 'selected' : '' ?>><?= $rotulo ?></option>
        <?php endforeach; ?>
    </select>

    <label>Ano Lectivo:</label>
    <select name="ano_letivo" required>
        <option value="">-- Escolha o Ano --</option>
        <?php
        for ($ano = date('Y'); $ano >= 2020; $ano--) {
            $valor = $ano . "/" . ($ano + 1);
            echo "<option value='$valor'" . ($valor == $ano_letivo ? " selected" : "") . ">$valor</option>";
        }
        ?>
    </select>

    <button type="submit">Filtrar</button>
</form>

        <?php if ($turma_id && count($alunos) > 0): ?>
            <h3>Lista de Alunos</h3>
            <?php foreach ($alunos as $a): ?>
                <a class="aluno-link" href="?turma_id=<?= $turma_id ?>&aluno_id=<?= $a['id'] ?>"><?= $a['nome'] ?></a>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <!-- Painel de Notas -->
    <?php if (isset($_GET['aluno_id'])):
        $aluno_id = intval($_GET['aluno_id']);
        $aluno_nome = $conn->query("SELECT nome FROM alunos WHERE id = $aluno_id")->fetch_assoc()['nome'];
        $disciplinas = $conn->query("SELECT id, nome FROM disciplinas WHERE turma_id = $turma_id")->fetch_all(MYSQLI_ASSOC);
        $notas = [];
        $res = $conn->query("SELECT disciplina_id, mf FROM notas WHERE aluno_id = $aluno_id AND turma_id = $turma_id");
        while ($row = $res->fetch_assoc()) {
            $notas[$row['disciplina_id']] = $row['mf'];
        }
    ?>
        <div class="content-box" style="margin-top: 20px;">
            <h3>Notas Finais: <?= $aluno_nome ?></h3>
            <form method="post">
                <input type="hidden" name="aluno_id" value="<?= $aluno_id ?>">
                <input type="hidden" name="turma_id" value="<?= $turma_id ?>">

                <label>Ano Lectivo:</label>
                <input type="text" name="ano_lectivo" required placeholder="ex: 2024/2025">

                <?php foreach ($disciplinas as $disc): ?>
                    <label><?= $disc['nome'] ?> (MF):</label>
                    <input type="number" step="0.01" name="notas[<?= $disc['id'] ?>]" value="<?= $notas[$disc['id']] ?? '' ?>">
                <?php endforeach; ?>

                <button type="submit" name="salvar_notas">Salvar Notas</button>
            </form>
        </div>
    <?php endif; ?>
</div>

</body>
</html>
