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

if (!isset($_SESSION['usuario'])) {
    header("Location: login.php");
    exit();
}

$id_professor = $_SESSION['usuario']['id'];
$nome_professor = $_SESSION['usuario']['nome'] ?? 'Professor';

// Buscar disciplinas e turmas atribuídas ao professor
$atribuicoes = $conn->prepare("
    SELECT d.id AS disciplina_id, d.nome AS disciplina_nome,
           t.id AS turma_id, t.nome AS turma_nome
    FROM atribuicoes a
    INNER JOIN disciplinas d ON a.disciplina_id = d.id
    INNER JOIN turmas t ON a.turma_id = t.id
    WHERE a.professor_id = ?
");
$atribuicoes->bind_param("i", $id_professor);
$atribuicoes->execute();
$res = $atribuicoes->get_result();

$disciplinas = [];
$turmas = [];

while ($row = $res->fetch_assoc()) {
    $disciplinas[$row['disciplina_id']] = $row['disciplina_nome'];
    $turmas[$row['turma_id']] = $row['turma_nome'];
}

$disciplinas = array_unique($disciplinas);
$turmas = array_unique($turmas);

$mostrarTabela = false;
$alunos = [];
$turma_id = $disciplina_id = $trimestre = null;
$mensagem = '';

// Ao clicar em "Ver"
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ver'])) {
    $turma_id = intval($_POST['turma'] ?? 0);
    $disciplina_id = intval($_POST['disciplina'] ?? 0);
    $trimestre = $_POST['trimestre'] ?? '';

    if ($turma_id && $disciplina_id && $trimestre !== '') {
        $stmt = $conn->prepare("SELECT id, nome FROM alunos WHERE turma_id = ? ORDER BY nome ASC");
        $stmt->bind_param("i", $turma_id);
        $stmt->execute();
        $alunos = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $mostrarTabela = true;
    }
}

// Salvamento em massa das notas
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['salvar_todas'])) {
    $turma_id = intval($_POST['turma']);
    $disciplina_id = intval($_POST['disciplina']);
    $trimestre = $_POST['trimestre'];

    foreach ($_POST['mac'] as $aluno_id => $mac) {
        $mac = floatval($_POST['mac'][$aluno_id]);
        $npp = floatval($_POST['npp'][$aluno_id]);
        $npt = floatval($_POST['npt'][$aluno_id]);
        $mt = round(($mac + $npp + $npt) / 3, 1);
        $exame = isset($_POST['exame'][$aluno_id]) ? floatval($_POST['exame'][$aluno_id]) : null;

        $stmt = $conn->prepare("REPLACE INTO notas (aluno_id, disciplina_id, turma_id, trimestre, mac, npp, npt, mt, exame)
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("iiiidddds", $aluno_id, $disciplina_id, $turma_id, $trimestre,
                          $mac, $npp, $npt, $mt, $exame);
        $stmt->execute();
    }
    $mensagem = "Notas salvas com sucesso!";
}
?>

<!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <title>Lançar Notas</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="adminlte/plugins/fontawesome-free/css/all.min.css">
    <link rel="stylesheet" href="adminlte/dist/css/adminlte.min.css">
    <style>
        body { margin:0; font-family:'Segoe UI', sans-serif; background:#f4f6f9; }
        .sidebar {
            width:260px; background:#001f3f; color:white; position:fixed;
            top:0; left:0; bottom:0; padding-top:60px;
        }
        .sidebar .brand {
            text-align:center; font-size:22px; font-weight:bold;
            padding:15px 0; background:#002244;
        }
        .sidebar ul { list-style:none; padding:0; }
        .sidebar li {
            padding:15px 20px; border-left:4px solid transparent; cursor:pointer;
        }
        .sidebar li:hover {
            background:#0056b3; border-left:4px solid white;
        }
        .main-header {
            background:#003366; color:white; padding:20px;
            margin-left:260px; display:flex; justify-content:space-between;
            position:fixed; top:0; right:0; left:260px; z-index:1000; height:70px;
        }
        .content {
            margin-left:260px; padding:90px 30px 30px 30px;
        }
        form, table {
            background:white; padding:20px; border-radius:10px;
            box-shadow:0 0 10px rgba(0,0,0,0.1); margin-bottom:20px; width:100%;
        }
        .form-row {
            display:flex; gap:20px; flex-wrap:wrap;
        }
        .form-row > div {
            flex:1; min-width:200px;
        }
        label {
            display:block; font-weight:bold; margin-bottom:6px;
        }
        select, input {
            width:100%; padding:6px; border:1px solid #ccc;
            border-radius:6px; margin-bottom:10px;
        }
        button {
            padding:10px 20px; border:none; border-radius:6px;
            background:#28a745; color:white; font-weight:bold; cursor:pointer;
        }
        .mensagem {
            background:#d4edda; color:#155724; padding:10px;
            margin-bottom:15px; border-left:5px solid #155724;
        }
        th, td { text-align:center; padding:6px; border:1px solid #ccc; }
        th { background:#003366; color:#fff; }
    </style>
</head>
<body>

<aside class="sidebar">
    <div class="brand">SISMAG</div>
    <ul>
        <li onclick="location.href='painel_professor.php'"><i class="fas fa-home"></i> Início</li>
        <li onclick="location.href='cadastrar_nota_professor1.php'"><i class="fas fa-pen"></i> Lançar Notas</li>
    </ul>
</aside>

<div class="main-header">
    <div><strong>Painel do Professor</strong></div>
    <div><?= htmlspecialchars($nome_professor) ?></div>
</div>

<div class="content">

<?php if (!empty($mensagem)): ?>
    <div class="mensagem"><?= $mensagem ?></div>
<?php endif; ?>

<form method="post">
    <div class="form-row">
        <div>
            <label>Turma</label>
            <select name="turma" required>
                <option value="">-- Selecione --</option>
                <?php foreach ($turmas as $id => $nome): ?>
                    <option value="<?= $id ?>" <?= ($id == $turma_id ? 'selected' : '') ?>>
                        <?= htmlspecialchars($nome) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>Disciplina</label>
            <select name="disciplina" required>
                <option value="">-- Selecione --</option>
                <?php foreach ($disciplinas as $id => $nome): ?>
                    <option value="<?= $id ?>" <?= ($id == $disciplina_id ? 'selected' : '') ?>>
                        <?= htmlspecialchars($nome) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>Trimestre</label>
            <select name="trimestre" required>
                <option value="1" <?= ($trimestre == '1' ? 'selected' : '') ?>>I Trimestre</option>
                <option value="2" <?= ($trimestre == '2' ? 'selected' : '') ?>>II Trimestre</option>
                <option value="3" <?= ($trimestre == '3' ? 'selected' : '') ?>>III Trimestre</option>
            </select>
        </div>
    </div>
    <button type="submit" name="ver">Ver Alunos</button>
</form>

<?php if ($mostrarTabela): ?>
<form method="post">
    <input type="hidden" name="turma" value="<?= $turma_id ?>">
    <input type="hidden" name="disciplina" value="<?= $disciplina_id ?>">
    <input type="hidden" name="trimestre" value="<?= $trimestre ?>">

    <table>
        <thead>
            <tr>
                <th>Nº</th>
                <th>Nome do Aluno</th>
                <th>MAC</th>
                <th>NPP</th>
                <th>NPT</th>
                <th>MT</th>
                <?php if ($trimestre == 3): ?><th>EXAME</th><?php endif; ?>
            </tr>
        </thead>
        <tbody>
        <?php $n = 1;
        foreach ($alunos as $al): 
            $q = $conn->prepare("SELECT mac, npp, npt, mt, exame FROM notas WHERE aluno_id=? AND disciplina_id=? AND turma_id=? AND trimestre=?");
            $q->bind_param("iiii", $al['id'], $disciplina_id, $turma_id, $trimestre);
            $q->execute(); $ns = $q->get_result()->fetch_assoc();

            $mac   = isset($ns['mac']) ? $ns['mac'] : '';
            $npp   = isset($ns['npp']) ? $ns['npp'] : '';
            $npt   = isset($ns['npt']) ? $ns['npt'] : '';
            $mt    = isset($ns['mt'])  ? $ns['mt']  : '--';
            $exame = isset($ns['exame']) ? $ns['exame'] : '';
        ?>
        <tr>
            <td><?= $n++ ?></td>
            <td><?= htmlspecialchars($al['nome']) ?></td>
            <td><input type="number" name="mac[<?= $al['id'] ?>]" step="0.1" value="<?= $mac ?>"></td>
            <td><input type="number" name="npp[<?= $al['id'] ?>]" step="0.1" value="<?= $npp ?>"></td>
            <td><input type="number" name="npt[<?= $al['id'] ?>]" step="0.1" value="<?= $npt ?>"></td>
            <td><input type="text" readonly value="<?= $mt ?>"></td>
            <?php if ($trimestre == 3): ?>
                <td><input type="number" name="exame[<?= $al['id'] ?>]" step="0.1" value="<?= $exame ?>"></td>
            <?php endif; ?>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <button type="submit" name="salvar_todas">Salvar Todas Notas</button>
</form>
<?php endif; ?>
</div>
</body>
</html>
