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

// Buscar turmas para listar e popular select
$turmas = [];
$res = $conn->query("SELECT id, nome, curso, classe, sala, ano, turno FROM turmas ORDER BY nome");
while ($row = $res->fetch_assoc()) {
    $turmas[] = $row;
}

// valores padrão para edição
$editando = ['id'=>'', 'nome'=>'', 'curso'=>'', 'classe'=>'', 'sala'=>'', 'ano'=>'', 'turno'=>''];

// Inserir nova turma
if ($_SERVER['REQUEST_METHOD']==='POST' && $_POST['acao']==='salvar') {
    $nome  = trim($_POST['nome']);
    $curso = $_POST['curso'];
    $ano   = $_POST['ano'];
    $turno = $_POST['turno'];
    if ($nome && $curso && $ano && $turno) {
        $classe = $_POST['classe'];
$sala   = $_POST['sala'];

$stmt = $conn->prepare("INSERT INTO turmas(nome,curso,classe,sala,ano,turno) VALUES(?,?,?,?,?,?)");
$stmt->bind_param("ssssss",$nome,$curso,$classe,$sala,$ano,$turno);

        $stmt->execute();
        header("Location: cadastrar_turma1.php");
        exit;
    }
}

// Atualizar turma existente
if ($_SERVER['REQUEST_METHOD']==='POST' && $_POST['acao']==='atualizar') {
    $id    = intval($_POST['id']);
    $nome  = trim($_POST['nome']);
    $curso = $_POST['curso'];
    $ano   = $_POST['ano'];
    $turno = $_POST['turno'];
    if ($id && $nome && $curso && $ano && $turno) {
       $classe = $_POST['classe'];
$sala   = $_POST['sala'];

$stmt = $conn->prepare("UPDATE turmas SET nome=?,curso=?,classe=?,sala=?,ano=?,turno=? WHERE id=?");
$stmt->bind_param("ssssssi",$nome,$curso,$classe,$sala,$ano,$turno,$id);

        $stmt->execute();
        header("Location: cadastrar_turma1.php");
        exit;
    }
}

// Apagar turma (verifica notas)
if (isset($_GET['apagar'])) {
    $id = intval($_GET['apagar']);
    // opcional: verificar FK notas...
    $conn->query("DELETE FROM turmas WHERE id=$id");
    header("Location: cadastrar_turma.php");
    exit;
}

// Carregar turma para editar
if (isset($_GET['editar'])) {
    $id = intval($_GET['editar']);
    $stmt = $conn->prepare("SELECT * FROM turmas WHERE id=?");
    $stmt->bind_param("i",$id);
    $stmt->execute();
    $editando = $stmt->get_result()->fetch_assoc();
}

?>
<!DOCTYPE html>
<html lang="pt">
<head>
  <meta charset="UTF-8">
  <title>Cadastrar Turma</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="adminlte/plugins/fontawesome-free/css/all.min.css">
  <style>
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
      font-family: 'Segoe UI', sans-serif;
    }

    body {
      background: #f4f6f9;
      display: flex;
      flex-direction: column;
      min-height: 100vh;
    }

    .main-header {
      background: #003366;
      color: #fff;
      height: 60px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;
      position: sticky;
      top: 0;
      z-index: 1000;
    }

    .sidebar {
      background: #001f3f;
      color: #fff;
      width: 100%;
      padding: 10px 0;
    }

    .sidebar ul {
      list-style: none;
      display: flex;
      overflow-x: auto;
      white-space: nowrap;
    }

    .sidebar li {
      padding: 12px 20px;
      cursor: pointer;
      flex: none;
      transition: background .3s;
    }

    .sidebar li.active, .sidebar li:hover {
      background: #0056b3;
    }

    .content {
      flex: 1;
      padding: 20px;
      width: 100%;
      max-width: 1200px;
      margin: auto;
    }

    form {
      background: #fff;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
      margin-bottom: 20px;
    }

    .form-row {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
    }

    .form-row > div {
      flex: 1 1 250px;
    }

    label {
      font-weight: bold;
      margin-bottom: 6px;
      display: block;
    }

    input, select {
      width: 100%;
      padding: 8px;
      border: 1px solid #ccc;
      border-radius: 6px;
      margin-bottom: 10px;
      font-size: 14px;
    }

    button {
      padding: 10px 20px;
      font-weight: bold;
      border: none;
      border-radius: 6px;
      margin-top: 10px;
      cursor: pointer;
    }

    .btn-save {
      background: #28a745;
      color: #fff;
    }

    .btn-update {
      background: #ffc107;
      color: #000;
    }

    .btn-delete {
      background: #dc3545;
      color: #fff;
    }

    table {
      width: 100%;
      background: #fff;
      border-collapse: collapse;
      box-shadow: 0 0 10px rgba(0,0,0,0.05);
      border-radius: 8px;
      overflow: hidden;
    }

    th, td {
      padding: 10px;
      text-align: center;
      border: 1px solid #ccc;
      font-size: 14px;
    }

    th {
      background: #003366;
      color: white;
    }

    @media (max-width: 768px) {
      .form-row {
        flex-direction: column;
      }

      .sidebar ul {
        flex-direction: column;
        align-items: stretch;
      }

      .sidebar li {
        text-align: center;
      }
    }
  </style>
</head>
<body>

  <div class="main-header">
    <div>SISMAG — Cadastro de Turmas</div>
    <div>Usuário: <?= htmlspecialchars($_SESSION['usuario']['nome'] ?? 'Desconhecido') ?></div>
  </div>

  <aside class="sidebar">
    <ul>
      <li onclick="location.href='painel_secretaria_geral.php'"><i class="fas fa-home"></i> Painel Principal</li>
      <li class="active"><i class="fas fa-layer-group"></i> Turmas</li>
      <li onclick="location.href='cadastrar_disciplina_anterior.php'"><i class="fas fa-book"></i> Disciplinas</li>
      <li onclick="location.href='ver_turmas.php'"><i class="fas fa-user-graduate"></i>Ver Turmas</li>
      <li onclick="location.href='configuracoes.php'"><i class="fas fa-cogs"></i> Configurações</li>
    </ul>
  </aside>

  <div class="content">
    <!-- Formulário -->
    <form method="post">
      <input type="hidden" name="id" value="<?= $editando['id'] ?>">
      <div class="form-row">
        <div>
          <label>Nome da Turma</label>
          <input type="text" name="nome" value="<?= htmlspecialchars($editando['nome']) ?>" required>
        </div>
        <div>
          <label>Curso</label>
          <select name="curso" required>
            <option value="">--Selecionar--</option>
            <option value="REGULAR" <?= $editando['curso']==='REGULAR'?'selected':'' ?>>REGULAR</option>
            <option value="C.E.J" <?= $editando['curso']==='C.E.J'?'selected':'' ?>>C.E.J</option>
            <option value="C.H" <?= $editando['curso']==='C.H'?'selected':'' ?>>C.H</option>
          </select>
        </div>
        <div>
          <label>Classe</label>
          <select name="classe" required>
            <option value="">--Selecionar--</option>
            <option value="7ª" <?= $editando['classe']==='7ª'?'selected':'' ?>>7ª</option>
            <option value="8ª" <?= $editando['classe']==='8ª'?'selected':'' ?>>8ª</option>
            <option value="9ª" <?= $editando['classe']==='9ª'?'selected':'' ?>>9ª</option>
            <option value="10ª" <?= $editando['classe']==='10ª'?'selected':'' ?>>10ª</option>
            <option value="11ª" <?= $editando['classe']==='11ª'?'selected':'' ?>>11ª</option>
            <option value="12ª" <?= $editando['classe']==='12ª'?'selected':'' ?>>12ª</option>
            <option value="13ª" <?= $editando['classe']==='13ª'?'selected':'' ?>>13ª</option>
          </select>
        </div>
        <div>
          <label>Sala</label>
          <input type="text" name="sala" value="<?= htmlspecialchars($editando['sala'] ?? '') ?>" required>
        </div>
        <div>
          <label>Ano Letivo</label>
          <select name="ano" required>
            <?php for($i=2020;$i<=2030;$i++): $val="$i/".($i+1); ?>
              <option value="<?= $val ?>" <?= $editando['ano']===$val?'selected':'' ?>><?= $val ?></option>
            <?php endfor; ?>
          </select>
        </div>
        <div>
          <label>Turno</label>
          <select name="turno" required>
            <option value="Manhã" <?= $editando['turno']==='Manhã'?'selected':'' ?>>Manhã</option>
            <option value="Tarde" <?= $editando['turno']==='Tarde'?'selected':'' ?>>Tarde</option>
            <option value="Noite" <?= $editando['turno']==='Noite'?'selected':'' ?>>Noite</option>
          </select>
        </div>
      </div>

      <?php if($editando['id']): ?>
        <button type="submit" name="acao" value="atualizar" class="btn-update">Alterar</button>
      <?php else: ?>
        <button type="submit" name="acao" value="salvar" class="btn-save">Salvar</button>
      <?php endif; ?>
    </form>

    <!-- Tabela -->
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Turma</th>
          <th>Curso</th>
          <th>Classe</th>
          <th>Sala</th>
          <th>Ano</th>
          <th>Turno</th>
          <th>Ações</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($turmas as $t): ?>
        <tr>
          <td><?= $t['id'] ?></td>
          <td><?= htmlspecialchars($t['nome']) ?></td>
          <td><?= htmlspecialchars($t['curso']) ?></td>
          <td><?= htmlspecialchars($t['classe'] ?? '-') ?></td>
          <td><?= htmlspecialchars($t['sala'] ?? '-') ?></td>
          <td><?= htmlspecialchars($t['ano']) ?></td>
          <td><?= htmlspecialchars($t['turno']) ?></td>
          <td>
            <a href="?editar=<?= $t['id'] ?>" class="btn-update" style="padding:4px 8px;">Alterar</a>
            <a href="?apagar=<?= $t['id'] ?>" class="btn-delete" onclick="return confirm('Apagar esta turma?')" style="padding:4px 8px;">Apagar</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</body>
</html>
