<?php
$pdo = new PDO("mysql:host=localhost;dbname=kaltekgo_avila", "kaltekgo_admin", "kaltek@2024");

$id_turma = isset($_GET['id_turma']) ? (int) $_GET['id_turma'] : 0;
$id_disciplina = isset($_GET['id_disciplina']) ? (int) $_GET['id_disciplina'] : 0;

if (!$id_turma || !$id_disciplina) {
    echo '<tr><td colspan="6">Selecione a turma e a disciplina.</td></tr>';
    exit;
}

try {
    // Busca todos os alunos da turma
    $stmt = $pdo->prepare("
        SELECT nome, matricula, NT, NS
        FROM P3
        WHERE id_turma = :id_turma AND id_disciplina = :id_disciplina
        ORDER BY P3.nome ASC
    ");
    $stmt->execute([
        ':id_turma' => $id_turma,
        ':id_disciplina' => $id_disciplina
    ]);
    $alunos = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$alunos) {
        echo '<tr><td colspan="6">Nenhum aluno encontrado.</td></tr>';
        exit;
    }

    foreach ($alunos as $aluno) {
        $nt = isset($aluno['NT']) ? number_format((float)$aluno['NT'], 2, ',', '') : '';
        $ns = isset($aluno['NS']) ? number_format((float)$aluno['NS'], 2, ',', '') : '';
        
        echo '<tr>';
        echo '<td><strong>' . htmlspecialchars($aluno['matricula']) . '</strong>';
        echo '<input type="hidden" name="aluno_id[]" value="' . htmlspecialchars($aluno['matricula']) . '">';
        echo '<input type="hidden" name="id_turma[]" value="' . $id_turma . '">';
        echo '<input type="hidden" name="id_disciplina[]" value="' . $id_disciplina . '">';
        echo '</td>';

        echo '<td><strong>' . htmlspecialchars($aluno['nome']) . '</strong>';
        echo '<input type="hidden" name="nome[]" value="' . htmlspecialchars($aluno['nome']) . '">';
        echo '</td>';

        echo '<td><input type="text" name="tarefa[]" class="form-control campo" value="' . $nt . '" min="0" max="10" step="0.1"></td>';
        echo '<td><input type="text" name="sala[]" class="form-control campo" value="' . $ns . '" min="0" max="10" step="0.1"></td>';
        echo '<td><input type="text" name="sala[]" class="form-control campo" value="' . $ns . '" min="0" max="10" step="0.1"></td>';
        echo '<td><input type="text" name="sala[]" class="form-control campo" value="' . $ns . '" min="0" max="10" step="0.1"></td>';
        echo '<td><input type="text" name="sala[]" class="form-control campo" value="' . $ns . '" min="0" max="10" step="0.1"></td>';
        echo '</tr>';
    }

} catch (Exception $e) {
    echo '<tr><td colspan="6">Erro ao buscar dados: ' . htmlspecialchars($e->getMessage()) . '</td></tr>';
}
?>
