<?php
include 'conexao.php';

// --- DADOS RECEBIDOS ---
$aluno_id = $_GET['aluno_id'] ?? '';
$turma_id = $_GET['turma_id'] ?? '';
$ano_lectivo = $_GET['ano_lectivo'] ?? '';
$classe = $_GET['classe'] ?? '';
$curso = $_GET['curso'] ?? '';

if (!$aluno_id || !$turma_id) {
    echo "<script>alert('Aluno ou Turma não definidos. Redirecionando...'); window.location.href='ver_turmas.php';</script>";
    exit;
}

$ano_lectivo = $ano_lectivo ?: date('Y') . '/' . (date('Y') + 1);
$classe = $classe ?: 'Desconhecida';
$curso = $curso ?: 'Desconhecido';

// PROCESSAR FORMULÁRIO
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['disciplina'])) {
    $disciplinas = $_POST['disciplina'];
    $mt1s = $_POST['mt1'];
    $mt2s = $_POST['mt2'];
    $mt3s = $_POST['mt3'];
    $exames = $_POST['exame'];
    
    // NOTA: Os campos MFD e MF não serão usados do POST; eles serão CALCULADOS no servidor.

    $stmt = $conn->prepare("INSERT INTO notas_termos_anteriores 
        (aluno_id, turma_id, disciplina, ano_lectivo, classe, curso, mt1, mt2, mt3, mfd, exame, mf)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE 
        ano_lectivo=VALUES(ano_lectivo),
        classe=VALUES(classe),
        curso=VALUES(curso),
        mt1=VALUES(mt1),
        mt2=VALUES(mt2),
        mt3=VALUES(mt3),
        mfd=VALUES(mfd),
        exame=VALUES(exame),
        mf=VALUES(mf)");

    for ($i = 0; $i < count($disciplinas); $i++) {
        // Sanitiza e converte notas para float
        $mt1 = (float)($mt1s[$i] ?? 0);
        $mt2 = (float)($mt2s[$i] ?? 0);
        $mt3 = (float)($mt3s[$i] ?? 0);
        $exame = (float)($exames[$i] ?? 0);
        
        // --- CÁLCULO MFD E MF NO SERVIDOR ---
        $mfd_calc = ($mt1 + $mt2 + $mt3) / 3;
        $mfd = number_format($mfd_calc, 2, '.', ''); // MFD com 2 casas decimais
        $mf = round($mfd_calc); // MF arredondada

        $stmt->bind_param(
            "iisssssddddd",
            $aluno_id,
            $turma_id,
            $disciplinas[$i],
            $ano_lectivo,
            $classe,
            $curso,
            $mt1,
            $mt2,
            $mt3,
            $mfd, // Valor calculado
            $exame,
            $mf   // Valor calculado
        );
        $stmt->execute();
    }

    echo "<script>alert('Notas salvas com sucesso!');</script>";
}

// Buscar disciplinas
$disciplinas = [];
$res = $conn->query("SELECT nome FROM disciplinas_anteriores WHERE turma_id = $turma_id");
while ($d = $res->fetch_assoc()) $disciplinas[] = $d['nome'];

// Buscar nome do aluno
$alunoNome = '';
$res = $conn->query("SELECT nome FROM alunos WHERE id = $aluno_id LIMIT 1");
if ($res && $row = $res->fetch_assoc()) $alunoNome = $row['nome'];

// Buscar notas existentes
$notasExistentes = [];
$res = $conn->query("SELECT * FROM notas_termos_anteriores WHERE aluno_id = $aluno_id AND turma_id = $turma_id");
while ($row = $res->fetch_assoc()) {
    $notasExistentes[$row['disciplina']] = $row;
}
?>

<!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
  <title>Lançamento de Notas - Termos Anteriores</title>
  <style>
    body {
        margin: 0;
        font-family: Arial, sans-serif;
        background: #f4f6f9;
    }
    .top-bar {
        background: #0056b3;
        color: white;
        padding: 15px;
        font-size: 18px;
    }
    .sidebar {
        width: 220px;
        background: #1c1c1c;
        height: 100vh;
        float: left;
        padding-top: 20px;
    }
    .sidebar a {
        display: block;
        color: white;
        padding: 10px 20px;
        text-decoration: none;
    }
    .sidebar a:hover {
        background: #333;
    }
    .content {
        margin-left: 220px;
        padding: 20px;
    }
    .box {
        background: white;
        padding: 20px;
        border-radius: 6px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    }
    table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 15px;
        font-size: 14px;
    }
    th, td {
        border: 1px solid #ccc;
        padding: 6px;
        text-align: center;
    }
    input[type=number], input[type=text] {
        width: 100%;
        padding: 6px;
        box-sizing: border-box;
        border: 1px solid #ccc;
        border-radius: 4px;
    }
    button {
        padding: 10px 20px;
        margin-top: 15px;
        background: #0056b3;
        color: white;
        border: none;
        border-radius: 4px;
    }
    button:hover {
        background: #004494;
    }
    .info {
        margin-bottom: 10px;
    }
  </style>
</head>
<body>

<div class="top-bar">SISMAG - Lançar Notas de Termos Anteriores</div>

<div class="sidebar">
    <a href="painel.php">🏠 Início</a>
    <a href="ver_alunos_anteriores.php">👨‍🎓 Ver Alunos</a>
    <a href="cadastrar_disciplina_anterior.php">📚 Disciplinas</a>
</div>

<div class="content">
  <form method="POST">
    <div class="box">
      <h2>Notas do Aluno</h2>
      <p class="info"><strong>Aluno:</strong> <?= htmlspecialchars($alunoNome) ?></p>
      <p class="info"><strong>Turma:</strong> <?= htmlspecialchars($classe . " - " . $curso) ?></p>
      <p class="info"><strong>Ano Lectivo:</strong> <?= htmlspecialchars($ano_lectivo) ?></p>

      <table>
        <thead>
          <tr>
            <th>Disciplina</th>
            <th>MT1</th>
            <th>MT2</th>
            <th>MT3</th>
            <th>MFD</th>
            <th>Exame</th>
            <th>MF</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($disciplinas as $disciplina):
              $nota = $notasExistentes[$disciplina] ?? [];
          ?>
          <tr>
            <td>
              <input type="hidden" name="disciplina[]" value="<?= $disciplina ?>">
              <?= htmlspecialchars($disciplina) ?>
            </td>
            <td><input type="number" name="mt1[]" step="0.01" value="<?= $nota['mt1'] ?? '' ?>" oninput="calcular(this)"></td>
            <td><input type="number" name="mt2[]" step="0.01" value="<?= $nota['mt2'] ?? '' ?>" oninput="calcular(this)"></td>
            <td><input type="number" name="mt3[]" step="0.01" value="<?= $nota['mt3'] ?? '' ?>" oninput="calcular(this)"></td>
            <td><input type="text" name="mfd[]" readonly value="<?= $nota['mfd'] ?? '' ?>"></td>
            <td><input type="number" name="exame[]" step="0.01" value="<?= $nota['exame'] ?? '' ?>"></td>
            <td><input type="text" name="mf[]" readonly value="<?= $nota['mf'] ?? '' ?>"></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>

      <button type="submit">💾 Salvar Termo</button>
      <button type="button" onclick="window.print()">🖨️ Imprimir</button>
    </div>
  </form>
</div>

<script>
function calcular(input) {
  const row = input.closest('tr');
  const mt1 = parseFloat(row.querySelector('input[name="mt1[]"]').value) || 0;
  const mt2 = parseFloat(row.querySelector('input[name="mt2[]"]').value) || 0;
  const mt3 = parseFloat(row.querySelector('input[name="mt3[]"]').value) || 0;
  
  const mfd_calc = (mt1 + mt2 + mt3) / 3;
  const mfd = mfd_calc.toFixed(2);
  const mf = Math.round(mfd_calc); // Arredonda a média para MF
  
  row.querySelector('input[name="mfd[]"]').value = mfd;
  row.querySelector('input[name="mf[]"]').value = mf;
}
</script>

</body>
</html>