<?php
file_put_contents('debug_post.txt', print_r($_POST, true));
// Define tempo de vida da sessão (12 horas)
ini_set('session.gc_maxlifetime', 14400);
session_set_cookie_params(14400);

session_start();
if (!isset($_SESSION['idProfessor']) || !isset($_SESSION['nomeProfessor'])) {
    header("Location: login.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
  <meta charset="UTF-8">
  <title>TAREFAS TRIMESTRAIS</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <style>
    body { font-family: Arial, sans-serif; background:#fff; margin:20px; color:#000; }
    th { background:#000; color:#fff; }
    td, th { border:1px solid #000; padding:8px; font-size:12px; }
    .mensagem-erro { color:red; font-size:11px; display:none; }
    .input-error { border:2px solid red !important; background:#ffe6e6; }
  </style>
</head>
<body>
<div class="container-fluid">
  <h4>TAREFAS TRIMESTRAIS</h4>
  <p class="text-uppercase"><?= $_SESSION['tipoUsuario']?>(A): <strong><?= $_SESSION['nomeProfessor']?></strong></p>
  <p>TRIMESTRE ATUAL (sessão): <?= $_SESSION['trimestre']?></p>

  <!-- Seletores -->
  <div class="row">
    <div class="col-md-4">
      <div class="form-group">
        <label for="selectTurma">Selecione a turma:</label>
        <select id="selectTurma" class="form-control text-uppercase" name="turma">
          <option value="">Selecione...</option>
        </select>
      </div>
    </div>
    <div class="col-md-4">
      <div class="form-group">
        <label for="selectTurma2">Selecione uma disciplina:</label>
        <select id="selectTurma2" class="form-control text-uppercase" name="disciplina">
          <option value="">Selecione...</option>
        </select>
      </div>
    </div>
    <div class="col-md-4">
      <div class="form-group">
        <label for="selectTrimestre">Selecione o trimestre:</label>
        <select id="selectTrimestre" class="form-control text-uppercase" name="trimestre">
          <option value="">Selecione...</option>
          <option value="1">1º Trimestre</option>
          <option value="2">2º Trimestre</option>
          <option value="3">3º Trimestre</option>
        </select>
      </div>
    </div>
  </div>

  <div id="alerta" class="alert d-none" style="margin-top: 5px;"></div>

  <!-- Tabela de Notas -->
  <div id="secaoTabela" style="display: none;" class="table-responsive-custom">
    <form id="formP3">
      <input type="hidden" name="turma" id="inputTurma">
      <input type="hidden" name="disciplina" id="inputDisciplina">
      <input type="hidden" name="trimestre" id="inputTrimestre">

      <table class="table table-bordered">
        <thead></thead>
        <tbody></tbody>
      </table>
      <button type="submit" class="btn btn-success">Gravar</button>
    </form>
  </div>
</div>

<script>
function verificaSelecoes() {
  const turma = document.getElementById('selectTurma').value;
  const disciplina = document.getElementById('selectTurma2').value;
  const trimestre = document.getElementById('selectTrimestre').value;

  document.getElementById('inputTurma').value = turma;
  document.getElementById('inputDisciplina').value = disciplina;
  document.getElementById('inputTrimestre').value = trimestre;

  document.getElementById('secaoTabela').style.display = 
    (turma && disciplina && trimestre) ? 'block' : 'none';
}

function carregarTabelaAlunos() {
  const turmaId = document.getElementById('selectTurma').value;
  const disciplinaId = document.getElementById('selectTurma2').value;
  const trimestre = document.getElementById('selectTrimestre').value;
  const tbody = document.querySelector('table tbody');
  const thead = document.querySelector('table thead');
  const alerta = document.getElementById('alerta');

  if (!turmaId || !disciplinaId || !trimestre) {
    verificaSelecoes();
    return;
  }

  fetch(`contar_tarefas.php?id_turma=${turmaId}&id_disciplina=${disciplinaId}&trimestre=${trimestre}`)
    .then(res => res.json())
    .then(data => {
      const totalTarefas = parseInt(data.total);

      let header = '<tr><th>Matrícula</th><th>Aluno</th>';
      for (let i = 1; i <= totalTarefas; i++) {
        header += `<th style='width:55px'>NT ${i}</th>`;
      }
      header += "<th style='width:55px'>MT</th><th style='width:55px'>Simulado</th><th style='width:55px'>P3</th></tr>";
      thead.innerHTML = header;

      fetch(`buscar_alunos.php?id_turma=${turmaId}&id_disciplina=${disciplinaId}&trimestre=${trimestre}`)
        .then(res => res.text())
        .then(data => {
          tbody.innerHTML = data;
          verificaSelecoes();
        })
        .catch(() => {
          alerta.classList.remove('d-none', 'alert-success');
          alerta.classList.add('alert-danger');
          alerta.textContent = 'Erro ao carregar alunos da turma.';
        });
    });
}

// Carregar turmas ao abrir
document.addEventListener('DOMContentLoaded', () => {
  const turmaSelect = document.getElementById('selectTurma');
  fetch('select.php')
    .then(res => res.json())
    .then(data => {
      data.turmas.forEach(t => {
        turmaSelect.innerHTML += `<option value="${t.id_serie_turma}">${t.identificador_serie} - ${t.identificador_turma} - ${t.identificador_turno}</option>`;
      });

      // Restaurar localStorage
      const turmaSalva = localStorage.getItem('turmaSelecionada');
      if (turmaSalva) {
        turmaSelect.value = turmaSalva;
        atualizarDisciplinas(turmaSalva);
        const disciplinaSalva = localStorage.getItem('disciplinaSelecionada');
        if (disciplinaSalva) {
          setTimeout(() => {
            document.getElementById('selectTurma2').value = disciplinaSalva;
            const trimestreSalvo = localStorage.getItem('trimestreSelecionado');
            if (trimestreSalvo) {
              document.getElementById('selectTrimestre').value = trimestreSalvo;
            }
            carregarTabelaAlunos();
          }, 500);
        }
      }
    });
});

// Eventos dos selects
document.getElementById('selectTurma').addEventListener('change', function () {
  localStorage.setItem('turmaSelecionada', this.value);
  atualizarDisciplinas(this.value);
});

document.getElementById('selectTurma2').addEventListener('change', function () {
  localStorage.setItem('disciplinaSelecionada', this.value);
  carregarTabelaAlunos();
});

document.getElementById('selectTrimestre').addEventListener('change', function () {
  localStorage.setItem('trimestreSelecionado', this.value);
  carregarTabelaAlunos();
});

// Atualizar disciplinas
function atualizarDisciplinas(turmaId) {
  fetch('select.php?id_turma=' + turmaId)
    .then(res => res.json())
    .then(data => {
      const disciplinaSelect = document.getElementById('selectTurma2');
      disciplinaSelect.innerHTML = '<option value="">Selecione...</option>';
      data.disciplinas.forEach(d => {
        disciplinaSelect.innerHTML += `<option value="${d.id_disciplina}">${d.nomeDisciplina}</option>`;
      });

      const salva = localStorage.getItem('disciplinaSelecionada');
      if (salva && data.disciplinas.some(d => d.id_disciplina === salva)) {
        disciplinaSelect.value = salva;
        carregarTabelaAlunos();
      } else {
        localStorage.removeItem('disciplinaSelecionada');
        disciplinaSelect.value = '';
        document.getElementById('secaoTabela').style.display = 'none';
      }
    });
}
</script>
</body>
</html>
