<?php  
include 'conexao.php';

// --- PROCESSAMENTO DO FORMULÁRIO ---
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['disciplina'])) {
 

$ano_lectivo = $_GET['ano_lectivo'] ?? '';
$turma_id = $_GET['turma_id'] ?? '';
$classe = $_GET['classe'] ?? '';
$curso = $_GET['curso'] ?? '';
$aluno_id = $_GET['aluno_id'] ?? '';






    $disciplinas = $_POST['disciplina'];
    $mt1s = $_POST['mt1'];
    $mt2s = $_POST['mt2'];
    $mt3s = $_POST['mt3'];
    $mfds = $_POST['mfd'];
    $exames = $_POST['exame'];
    $mfs = $_POST['mf'];

    $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++) {
        $stmt->bind_param(
            "iisssssddddd",
            $aluno_id,
            $turma_id,
            $disciplinas[$i],
            $ano_lectivo,
            $classe,
            $curso,
            $mt1s[$i],
            $mt2s[$i],
            $mt3s[$i],
            $mfds[$i],
            $exames[$i],
            $mfs[$i]
        );
        $stmt->execute();
    }

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

// --- DADOS PARA O FORMULÁRIO ---
$anos = [];
for ($i = 2024; $i <= 2030; $i++) {
    $anos[] = "$i/" . ($i + 1);
}

// Turmas
$turmas = [];
$res = $conn->query("SELECT id, nome FROM turmas ORDER BY nome");
while ($row = $res->fetch_assoc()) {
    $turmas[] = $row;
}

// Disciplinas agrupadas por turma
$disciplinasPorTurma = [];
$res = $conn->query("SELECT turma_id, nome FROM disciplinas");
while ($row = $res->fetch_assoc()) {
    $disciplinasPorTurma[$row['turma_id']][] = $row['nome'];
}

// Alunos agrupados por turma
$alunosPorTurma = [];
$res = $conn->query("SELECT id, nome, turma_id FROM alunos ORDER BY nome");
while ($row = $res->fetch_assoc()) {
    $alunosPorTurma[$row['turma_id']][] = $row;
}

// Notas anteriores existentes
$notasExistentes = [];
$res = $conn->query("SELECT * FROM notas_termos_anteriores");
while ($row = $res->fetch_assoc()) {
    $chave = $row['aluno_id'] . '_' . $row['turma_id'] . '_' . $row['disciplina'];
    $notasExistentes[$chave] = $row;
}








?>

<!DOCTYPE html>
<html lang="pt">
<head>
  <meta charset="UTF-8">
  <title>Termos Anteriores</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body { font-family: sans-serif; background: #f4f6f9; padding: 10px; }
    .box { background: white; padding: 15px; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 20px; }
    select, input[type=text], input[type=number] {
      padding: 6px; border: 1px solid #ccc; border-radius: 5px; width: 100%;
    }
    label { font-weight: bold; margin-top: 10px; display: block; }
    table { width: 100%; border-collapse: collapse; margin-top: 15px; }
    th, td { border: 1px solid #ccc; padding: 5px; text-align: center; font-size: 14px; }
    .form-row { display: flex; flex-wrap: wrap; gap: 10px; }
    .form-row > div { flex: 1 1 120px; }
    button {
      padding: 10px 20px; margin-top: 15px;
      background: #007bff; border: none; color: white; border-radius: 4px;
    }
    button:hover { background: #0056b3; }
    @media (max-width: 600px) {
      .form-row { flex-direction: column; }
    }
  </style>
</head>
<body>

<form method="POST">
  <div class="box">
    <h2>Preencher Termos Anteriores</h2>

    <div class="form-row">
      <div>
        <label>Ano Lectivo</label>
        <select name="ano_lectivo" required>
          <option value="">-- Selecione --</option>
          <?php foreach ($anos as $ano): ?>
           <option value="<?= $ano ?>" <?= ($ano == $ano_lectivo ? 'selected' : '') ?>><?= $ano ?></option>

          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label>Turma</label>
        <select name="turma_id" id="turma_id" required onchange="atualizarAlunos()">
          <option value="">-- Selecione --</option>
          <?php foreach ($turmas as $turma): ?>
           <option value="<?= $turma['id'] ?>" <?= ($turma['id'] == $turma_id ? 'selected' : '') ?>>
    <?= htmlspecialchars($turma['nome']) ?>
</option>

          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label>Classe</label>
        <select name="classe" required>
          <option value="">-- Selecione --</option>
          <?php for ($i = 7; $i <= 13; $i++): ?>
           <option value="<?= $i ?>ª" <?= ("$iª" == $classe ? 'selected' : '') ?>><?= $i ?>ª</option>

          <?php endfor; ?>
        </select>
      </div>
      <div>
        <label>Curso</label>
        <select name="curso" required>
          <option value="">-- Selecione --</option>
         <option value="Regular" <?= ($curso == 'Regular' ? 'selected' : '') ?>>Regular</option>
<option value="CEJ" <?= ($curso == 'CEJ' ? 'selected' : '') ?>>CEJ</option>
<option value="CH" <?= ($curso == 'CH' ? 'selected' : '') ?>>CH</option>

        </select>
      </div>
      <div>
        <label>Aluno</label>
        <select name="aluno_id" id="aluno_id" required onchange="atualizarNotas()">
          <option value="">-- Selecione uma turma --</option>
        </select>
      </div>
    </div>

    <div id="tabelaNotas" style="display:none;">
      <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 id="linhasNotas"></tbody>
      </table>
      <button type="submit">Salvar Termo</button>
      <button type="button" onclick="window.print()">Imprimir</button>
    </div>
  </div>
</form>

<script>
const alunosPorTurma = <?= json_encode($alunosPorTurma) ?>;
const disciplinasPorTurma = <?= json_encode($disciplinasPorTurma) ?>;
const notasExistentes = <?= json_encode($notasExistentes) ?>;

function atualizarAlunos() {
  const turmaId = document.getElementById('turma_id').value;
  const alunoSelect = document.getElementById('aluno_id');
  alunoSelect.innerHTML = '<option value="">-- Selecione --</option>';

  if (turmaId && alunosPorTurma[turmaId]) {
    alunosPorTurma[turmaId].forEach(aluno => {
      const opt = document.createElement('option');
      opt.value = aluno.id;
      opt.textContent = aluno.nome;
      alunoSelect.appendChild(opt);
    });
  }

  document.getElementById('tabelaNotas').style.display = 'none';
  document.getElementById('linhasNotas').innerHTML = '';

const alunoIdURL = "<?= $aluno_id ?>";
if (alunoIdURL && alunoSelect.querySelector(`option[value="${alunoIdURL}"]`)) {
    alunoSelect.value = alunoIdURL;
    atualizarNotas();
}





}

function atualizarNotas() {
  const turmaId = document.getElementById('turma_id').value;
  const alunoId = document.getElementById('aluno_id').value;
  const linhas = document.getElementById('linhasNotas');
  linhas.innerHTML = '';

  if (turmaId && disciplinasPorTurma[turmaId]) {
    disciplinasPorTurma[turmaId].forEach(disciplina => {
      const chave = alunoId + '_' + turmaId + '_' + disciplina;
      const nota = notasExistentes[chave] || {};
      const tr = document.createElement('tr');
      tr.innerHTML = `
        <td><input type="hidden" name="disciplina[]" value="${disciplina}">${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>
      `;
      linhas.appendChild(tr);
    });

    document.getElementById('tabelaNotas').style.display = 'block';
  }
}

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 = ((mt1 + mt2 + mt3) / 3).toFixed(2);
  const mf = Math.round(mfd);
  row.querySelector('input[name="mfd[]"]').value = mfd;
  row.querySelector('input[name="mf[]"]').value = mf;
}
</script>

</body>
</html>
