<?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', 3600);
session_set_cookie_params(3600);

// Inicia a sessão
session_start();

// Redireciona se a sessão não estiver definida
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>
  <!--script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.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-color: #ffffff;
      margin: 20px;
      color: #000000;
    }

    .container-fluid {
      width: 100%;
    }

    h4, h5 {
      margin: 0 0 10px;
    }

    .btn-cadastrar, .filtro-btns {
      margin-left: 15px;
      margin-bottom: 10px;
    }

    .table-responsive-custom {
      overflow-x: auto;
      -webkit-overflow-scrolling: touch;
      margin: 0 15px 20px 15px;
      display: block;
    }

    .table-scroll-top {
      overflow-x: auto;
      overflow-y: hidden;
      height: 20px;
      margin: 0 15px 5px 15px;
    }

    .table-scroll-top::-webkit-scrollbar {
      height: 8px;
    }

    .table-scroll-top::-webkit-scrollbar-thumb {
      background-color: #888;
      border-radius: 4px;
    }

    table {
      white-space: nowrap;
      width: 100%;
      border-collapse: collapse;
      background-color: #ffffff;
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
      text-transform: uppercase;
      min-width: 700px;
    }

    th, td {
      padding: 12px 15px;
      text-align: left;
      font-size: 12px;
      border: 1px solid #000;
      vertical-align: middle !important;
    }

    th {
      background-color: #000;
      color: #fff;
    }

    tr:nth-child(even) {
      background-color: #f4f4f4;
    }

    tr:hover {
      background-color: #e0e0e0;
    }

    .mensagem-erro {
      color: red;
      font-size: 11px;
      margin-top: 4px;
      display: none;
    }

    .input-error {
      border: 2px solid red !important;
      background-color: #ffe6e6;
    }
    .input-vermelho {
      color: red;
    }

    @media (max-width: 768px) {
      .btn-cadastrar, .filtro-btns .btn {
        width: 100% !important;
        margin: 10px auto;
        font-size: 16px;
        height: 45px;
        padding: 10px 12px;
      }

      .form-group label,
      .form-control {
        font-size: 14px;
      }

      .form-control,
      input[type="text"],
      select {
        height: 40px;
      }

      .table-responsive-custom {
        overflow-x: auto;
        display: block;
      }

      table {
        width: 1000px;
      }

      .table th, .table td {
        min-width: 125px;
        font-size: 14px;
        padding: 8px 10px;
      }

      h4 {
        text-align: center;
      }
    }
  </style>


</head>
<body>


<div class="container-fluid">
  <div>
   <h4>Tempo restante da sessão: <span id="session-timer"></span></h4> 
  </div>
  <h4>TAREFAS TRIMESTRAIS</h4>
  <h5>LEGENDAS</h5>
  <p>NT = NOTA TAREFAS / MT = MÉDIA TAREFAS / P3 = SOMATÓRIA DA MT(80% ou 8,0) + NOTA SIMULADO(20% ou 2,0)</p>
  <p class="text-uppercase">PROFESSOR(A): <strong><?= $_SESSION['nomeProfessor']?></p></strong>
  <p>TRIMESTRE: <?= $_SESSION['trimestre']?></p>
  <!--button class="btn btn-success" onclick="window.location.href='https://avilagoiania.kaltekgoiania.com.br/simulados/point/'">Ir para a tela de Nota Point</button--> 
  <button class="btn btn-success" onclick="window.location.href='https://avilagoiania.kaltekgoiania.com.br/simulados/tarefas/cadastrarTarefa.php'">Ir para a tela de cadastro de tarefas</button> 
  <button class="btn btn-success" onclick="window.location.href='https://avilagoiania.kaltekgoiania.com.br/simulados/tarefas/logout.php'">Clique aqui para sair</button>
  <div id="alerta" class="alert d-none" style="margin-top: 5px;"></div>

  <div class="row">
    <div class="col-md-6">
      <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-6">
      <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>

  <div id="topScroll" class="table-scroll-top">
    <div id="topScrollInner"></div>
  </div>

  <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">

      <table class="table table-bordered">
        <thead>
<?php $totalNotas = $totalTarefas; ?>
<tr>
  <th>Matrícula</th>
  <th>Aluno</th>
  <?php for ($i = 1; $i <= $totalNotas; $i++) echo "<th style='width:55px'>NT {$i}</th>"; ?>
  <th style="width:55px">MT</th><th style="width:55px">Simulado</th><th style="width:55px">P3</th>
</tr>
        </thead>
        <tbody></tbody>
      </table>
      <button type="submit" class="btn btn-success">Gravar</button><br>
    </form>
  </div>
</div>

<script>
function verificaSelecoes() {
  const turma = document.getElementById('selectTurma').value;
  const disciplina = document.getElementById('selectTurma2').value;
  document.getElementById('inputTurma').value = turma;
  document.getElementById('inputDisciplina').value = disciplina;
  document.getElementById('secaoTabela').style.display = (turma && disciplina) ? 'block' : 'none';
}

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

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

  // 1. Buscar total de tarefas
  fetch(`contar_tarefas.php?id_turma=${turmaId}&id_disciplina=${disciplinaId}`)
    .then(res => res.json())
    .then(data => {
      const totalTarefas = parseInt(data.total);
      
      // 2. Montar cabeçalho da tabela dinamicamente
      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;

      // 3. Buscar alunos
      fetch(`buscar_alunos.php?id_turma=${turmaId}&id_disciplina=${disciplinaId}`)
        .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.';
        });
    });
}

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>`;
      });

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

  const bottomScroll = document.querySelector('.table-responsive-custom');
  const topScroll = document.getElementById('topScroll');
  const topScrollInner = document.getElementById('topScrollInner');

  function atualizarLargura() {
    const tabela = bottomScroll.querySelector('table');
    if (tabela) {
      topScrollInner.style.width = tabela.offsetWidth + 'px';
    }
  }

  topScroll.addEventListener('scroll', () => {
    bottomScroll.scrollLeft = topScroll.scrollLeft;
  });
  bottomScroll.addEventListener('scroll', () => {
    topScroll.scrollLeft = bottomScroll.scrollLeft;
  });

  const observer = new MutationObserver(() => {
    atualizarLargura();
  });
  observer.observe(document.querySelector('table tbody'), { childList: true });

  atualizarLargura();
});

document.getElementById('selectTurma').addEventListener('change', function () {
  const turmaId = this.value;
  localStorage.setItem('turmaSelecionada', turmaId);
  atualizarDisciplinas(turmaId);
});

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

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';
      }
    });
}

document.getElementById('formP3').addEventListener('submit', function(e) {
  e.preventDefault();
  const alerta = document.getElementById('alerta');
  alerta.classList.add('d-none');

  const inputs = document.querySelectorAll('input[name^="t"]');
  let camposValidos = true;
  inputs.forEach(input => {
    if (!input.value.trim()) {
      input.classList.add('input-error');
      camposValidos = false;
    }
  });
  if (!camposValidos) {
    alerta.classList.remove('d-none');
    alerta.classList.add('alert-danger');
    alerta.textContent = 'Preencha todos os campos antes de salvar.';
    return;
  }

  const dados = new FormData(this);
  fetch('salvar.php', {
    method: 'POST',
    body: dados
  })
    .then(res => res.json())
    .then(data => {
      alerta.classList.remove('d-none');
      alerta.classList.add(data.sucesso ? 'alert-success' : 'alert-danger');
      alerta.textContent = data.mensagem;
      if (data.sucesso) {
        setTimeout(() => {
          location.reload();
        }, 1500);
      }
    })
    .catch(() => {
      alerta.classList.remove('d-none');
      alerta.classList.add('alert-danger');
      alerta.textContent = 'Erro ao salvar os dados.';
    });
});

document.addEventListener('focusout', function (e) {
  const campos = [
    't1[]', 't2[]', 't3[]', 't4[]', 't5[]',
    't6[]', 't7[]', 't8[]', 't9[]', 't10[]', 't11[]',
    't12[]', 't13[]', 't14[]', 't15[]', 't16[]',
    't17[]', 't18[]', 't19[]', 't20[]', 't21[]', 't22[]', 't23[]', 't24[]', 't25[]',
    't26[]', 't27[]', 't28[]', 't29[]', 't30[]'
  ];

  if (campos.includes(e.target.name)) {
    let valor = e.target.value.replace(',', '.');
    let num = parseFloat(valor);

    let mensagem = e.target.nextElementSibling;
    if (!mensagem || !mensagem.classList.contains('mensagem-erro')) {
      mensagem = document.createElement('div');
      mensagem.classList.add('mensagem-erro');
      e.target.parentNode.appendChild(mensagem);
    }

    if (isNaN(num)) {
      e.target.classList.add('input-error');
      mensagem.textContent = "Digite um número válido.";
      mensagem.style.display = 'block';
    } else if (num < 0 || num > 10) {
      e.target.classList.add('input-error');
      mensagem.textContent = "Entre 0 e 10.";
      mensagem.style.display = 'block';
    } else {
      e.target.classList.remove('input-error');
      mensagem.style.display = 'none';
      e.target.value = num.toFixed(2).replace('.', ',');
    }
  }
});

// Evento para abrir o modal ao clicar em um <th>
document.addEventListener('click', function (e) {
  const th = e.target.closest('th');
  if (th && th.textContent.startsWith('NT')) {
    const index = th.textContent.match(/\d+/);
    const turmaId = document.getElementById('selectTurma').value;
    const disciplinaId = document.getElementById('selectTurma2').value;

    if (index && turmaId && disciplinaId) {
      $('#modalInfo').modal('show');
      document.getElementById('modalContent').innerHTML = 'Carregando...';
      fetch(`info_tarefa.php?tarefa=NT${index}&turma=${turmaId}&disciplina=${disciplinaId}`)
        .then(res => res.text())
        .then(data => {
          document.getElementById('modalContent').innerHTML = data;
        })
        .catch(() => {
          document.getElementById('modalContent').innerHTML = '<div class="alert alert-danger">Erro ao carregar informações da tarefa.</div>';
        });
    }
  }
});

</script>
<script>
    const loginTime = <?= $_SESSION['login_time'] ?? time(); ?>;
    const sessionDuration = <?= $_SESSION['session_duration'] ?? 3600; ?>;
</script>
<script>
    function formatTime(seconds) {
        const h = Math.floor(seconds / 3600).toString().padStart(2, '0');
        const m = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');
        const s = (seconds % 60).toString().padStart(2, '0');
        return `${h}:${m}:${s}`;
    }

    const display = document.getElementById('session-timer');
    const endTime = loginTime + sessionDuration;

    function updateTimer() {
        const now = Math.floor(Date.now() / 1000);
        const remaining = endTime - now;

        if (remaining <= 0) {
            display.textContent = 'Sessão expirada';
            clearInterval(timer);
            // Opcional: redirecionar para login
            window.location.href = 'logout.php';
        } else {
            display.textContent = formatTime(remaining);
        }
    }

    updateTimer();
    const timer = setInterval(updateTimer, 1000);
</script>

<!-- Modal -->
<div class="modal fade" id="modalInfo" tabindex="-1" role="dialog" aria-labelledby="modalInfoLabel">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header bg-success text-white text-uppercase">
        <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
          <span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title" id="modalInfoLabel">Informações da Tarefa</h4>
      </div>
      <div class="modal-body" id="modalContent">
        Carregando...
      </div>
    </div>
  </div>
</div>

</body>
</html>