<?php
// Conexão com banco
$pdo = new PDO("mysql:host=localhost;dbname=kaltekgo_avila;charset=utf8", "kaltekgo_admin", "kaltek@2024");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// ===============================
// BUSCAR TURMAS DISTINCT
// ===============================
$stmtTurmas = $pdo->query("SELECT DISTINCT turma FROM simulado_geral ORDER BY turma ASC");
$turmas = $stmtTurmas->fetchAll(PDO::FETCH_ASSOC);

// ===============================
// FILTRO DE TURMA (SE SELECIONADO)
// ===============================
$turmaSelecionada = $_GET['turma'] ?? '';

if (!empty($turmaSelecionada)) {
    $stmt = $pdo->prepare("SELECT * FROM simulado_geral WHERE turma = :turma ORDER BY nome ASC");
    $stmt->bindParam(':turma', $turmaSelecionada);
    $stmt->execute();
    $alunos = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
    $alunos = $pdo->query("
        SELECT * FROM simulado_geral
        ORDER BY turma ASC, nome ASC
    ")->fetchAll(PDO::FETCH_ASSOC);
}

//$alunos = $pdo->query("SELECT * FROM simulado_geral WHERE turma = '1º ANO - M//(2025)' ORDER BY nome")->fetchAll(PDO::FETCH_ASSOC);

//$alunos = $pdo->query("SELECT *
//FROM simulado_geral
//ORDER BY turma ASC, nome ASC;")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Lançamento de Notas - AJAX</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <style>
        input[type="number"] {
            width: 80px;
        }
        .success {
            background-color: #dff0d8;
        }
        .error {
            background-color: #f2dede;
        }
    </style>
</head>
<body>
<div class="container">
    <h2 class="text-center text-uppercase">Lançamento de Notas - Simulado</h2>
    <form method="GET" class="form-inline text-center" style="margin-bottom:20px;">
    <select name="turma" class="form-control" onchange="this.form.submit()">
        <option value="">-- TODAS AS TURMAS --</option>

        <?php foreach ($turmas as $t): ?>
            <option value="<?= htmlspecialchars($t['turma']) ?>"
                <?= ($turmaSelecionada == $t['turma']) ? 'selected' : '' ?>>
                <?= htmlspecialchars($t['turma']) ?>
            </option>
        <?php endforeach; ?>
    </select>
</form>

    <table class="table table-bordered table-hover">
        <thead>
            <tr class="text-uppercase">
                <th>Matrícula</th>
                <th>Nome Aluno</th>
                <th>Série / Turma</th>
                <th>Simulado 1</th>
                <th>Simulado 2</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($alunos as $aluno): ?>
                <tr>
                    <td><?= htmlspecialchars($aluno['matricula']) ?></td>
                    <td><?= htmlspecialchars($aluno['nome']) ?></td>
                    <td><?= htmlspecialchars($aluno['turma']) ?></td>
                    <td>
                        <input type="number" step="0.01" 
                               class="nota-input" 
                               data-matricula="<?= $aluno['matricula'] ?>" 
                               data-campo="nota"
                               value="<?= $aluno['nota'] ?>">
                    </td>
                    <td>
                        <input type="number" step="0.01" 
                               class="nota-input" 
                               data-matricula="<?= $aluno['matricula'] ?>" 
                               data-campo="nota2"
                               value="<?= $aluno['nota2'] ?>">
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <a href="../"><button class="btn btn-success">Voltar</button></a>
    
</div>
<br>
<script>
document.addEventListener("DOMContentLoaded", function () {
    var inputs = document.querySelectorAll('.nota-input');

    inputs.forEach(function (input) {
        input.addEventListener('change', function () {
            var matricula = this.getAttribute('data-matricula');
            var campo = this.getAttribute('data-campo');
            var valor = this.value;
            var self = this;

            var xhr = new XMLHttpRequest();
            xhr.open("POST", "atualizar.php", true);
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

            xhr.onload = function () {
                if (xhr.status === 200 && xhr.responseText === "ok") {
                    self.classList.remove('error');
                    self.classList.add('success');
                    setTimeout(() => self.classList.remove('success'), 1000);
                } else {
                    self.classList.add('error');
                    alert("Erro ao salvar nota!");
                }
            };

            xhr.send("matricula=" + matricula + "&campo=" + campo + "&valor=" + valor);
        });
    });
});
</script>
</body>
</html>
