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

$turmas = $conn->query("SELECT id, nome FROM turmas ORDER BY nome")->fetch_all(MYSQLI_ASSOC);
$professores = $conn->query("SELECT id, nome FROM usuarios WHERE perfil = 'Professor' ORDER BY nome")->fetch_all(MYSQLI_ASSOC);
$disciplinas = $conn->query("SELECT id, nome FROM disciplinas ORDER BY nome")->fetch_all(MYSQLI_ASSOC);

$dias = ['Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta'];
$tempos = [
  '07:30-08:15', '08:20-09:05', '09:10-09:55',
  '10:10-10:55', '11:00-11:45', '11:50-12:35'
];

// Atualizar horário se enviado
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update'])) {
    $id = intval($_POST['id']);
    $professor = intval($_POST['professor']);
    $disciplina = intval($_POST['disciplina']);

    $stmt = $conn->prepare("UPDATE horario SET professor = ?, disciplina = ? WHERE id = ?");
    $stmt->bind_param("iii", $professor, $disciplina, $id);
    $stmt->execute();
    $mensagem = "Horário atualizado com sucesso!";
}

// Buscar horários por turma
$horarios = [];
foreach ($turmas as $turma) {
    $turma_id = $turma['id'];
    $result = $conn->query("
        SELECT h.id, h.turma_id, h.dia, h.tempo,
               d.nome AS disciplina, u.nome AS professor
        FROM horario h
        LEFT JOIN disciplinas d ON h.disciplina = d.id
        LEFT JOIN usuarios u ON h.professor = u.id
        WHERE h.turma_id = $turma_id
    ");
    while ($row = $result->fetch_assoc()) {
        $horarios[$turma_id][$row['dia']][$row['tempo']] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="pt">
<head>
  <meta charset="UTF-8">
  <title>Editar Horário Escolar</title>
  <style>
    body { font-family: 'Segoe UI', sans-serif; background: #f4f6f9; margin: 0; padding: 20px; }
    h2 { text-align: center; color: #003366; }
    table { width: 100%; border-collapse: collapse; margin-top: 20px; margin-bottom: 40px; background: white; }
    th, td { border: 1px solid #ccc; padding: 6px; text-align: center; font-size: 13px; }
    th { background: #003366; color: white; }
    select { width: 100%; padding: 5px; }
    form { margin: 0; }
    .turma-title {
        background: #003366;
        color: white;
        padding: 10px;
        margin-top: 40px;
        text-align: center;
        border-radius: 5px;
    }
    .mensagem {
        background: #d4edda;
        color: #155724;
        padding: 10px;
        border-left: 5px solid #155724;
        margin-bottom: 20px;
        max-width: 800px;
        margin-left: auto;
        margin-right: auto;
    }
  </style>
</head>
<body>

<h2>Editar Horário Escolar</h2>

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

<?php foreach ($turmas as $turma): ?>
  <div class="turma-title">Horário da Turma: <?= htmlspecialchars($turma['nome']) ?></div>

  <table>
    <thead>
      <tr>
        <th>Hora</th>
        <?php foreach ($dias as $dia): ?>
          <th><?= $dia ?></th>
        <?php endforeach; ?>
      </tr>
    </thead>
    <tbody>
      <?php for ($i = 1; $i <= count($tempos); $i++): ?>
        <tr>
          <td><strong><?= $tempos[$i - 1] ?></strong></td>
          <?php foreach ($dias as $dia): 
            $slot = $horarios[$turma['id']][$dia][$i] ?? null;
            ?>
            <td>
              <?php if ($slot): ?>
                <form method="post">
                  <input type="hidden" name="id" value="<?= $slot['id'] ?>">
                  <select name="disciplina">
                    <?php foreach ($disciplinas as $d): ?>
                      <option value="<?= $d['id'] ?>" <?= ($d['nome'] == $slot['disciplina']) ? 'selected' : '' ?>>
                        <?= htmlspecialchars($d['nome']) ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                  <select name="professor">
                    <?php foreach ($professores as $p): ?>
                      <option value="<?= $p['id'] ?>" <?= ($p['nome'] == $slot['professor']) ? 'selected' : '' ?>>
                        <?= htmlspecialchars($p['nome']) ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                  <button type="submit" name="update">Salvar</button>
                </form>
              <?php else: ?>
                —
              <?php endif; ?>
            </td>
          <?php endforeach; ?>
        </tr>
      <?php endfor; ?>
    </tbody>
  </table>
<?php endforeach; ?>

</body>
</html>
