<?php
// ==== Conexão com o banco (PDO) ====
$host = "localhost";
$user = "kaltekgo_admin";       
$pass = "kaltek@2024";          
$db   = "kaltekgo_avila";       

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Erro na conexão: " . $e->getMessage());
}

// ==== Consulta unindo alunos com notas (sem simulado) ====
$sql = "SELECT 
            a.matricula,
            a.nome,
            a.identificadorturma,
            n.enem_dia1,
            n.enem_dia2,
            n.redacao,
            n.media
        FROM alunos_confirmados_2025 a
        LEFT JOIN notas_enemfit_2025 n ON a.matricula = n.matricula
        WHERE a.identificadorturma = '1º ANO  - M (2025)'
        ORDER BY a.nome ASC";

$stmt = $pdo->query($sql);
$alunos = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>ENEMFIT</title>

<!-- ✅ Bootstrap 3 -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<style>
body {
    background-color: #ffffff;
    color: #000000;
    margin: 20px;
    text-align: center;
    font-family: Arial, sans-serif;
}

.tabela-container {
    width: 95%;
    margin: 30px auto;
    overflow-x: auto;
}

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

th, td {
    text-align: center;
    vertical-align: middle !important;
    border: 1px solid #000;
    padding: 8px;
}

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

tr:nth-child(even) { background-color: #f9f9f9; }
tr:hover { background-color: #f1f1f1; }

input[type=number] {
    width: 60px;
    text-align: center;
    font-size: 12px;
    border-radius: 3px;
    margin: 0 auto;
    display: block;
}

/* 🚫 Remove as setas dos inputs numéricos */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
input[type=number] {
    -moz-appearance: textfield;
}

.topo-logo {
    position: relative;
    float: right;
    margin-top: 10px;
    margin-right: 50px;
    width: 120px;
}

h3 {
    font-weight: bold;
    margin-top: 10px;
    margin-bottom: 20px;
    color: #000;
}
.media {
    background-color: #f3f3f3;
    font-weight: 500;
    font-size: 12px;
}
</style>
</head>
<body>

<img class="topo-logo" src="https://colegioavila.com.br/wp-content/uploads/2018/11/logo-com-sombra2.png" alt="Logo Colégio Ávila">

<div class="container-fluid tabela-container">
    <h3>ENEMFIT - 3º TRIMESTRE</h3>

    <form method="post" action="salvar_notas_.php" id="formNotas">
        <table class="table table-bordered table-hover" id="tabelaNotas">
            <thead>
                <tr>
                    <th>MATRÍCULA</th>
                    <th>NOME</th>
                    <th>TURMA</th>
                    <th>ED1</th>
                    <th>ED2</th>
                    <th>RE</th>
                    <th>MÉDIA</th>
                </tr>
            </thead>
            <tbody>
            <?php if (count($alunos) > 0): ?>
                <?php foreach ($alunos as $a): ?>
                    <?php 
                        // ✅ Média = (ED1 + ED2 + RE) / 3
                        $valores = array_map('floatval', [
                            $a['enem_dia1'],
                            $a['enem_dia2'],
                            $a['redacao']
                        ]);
                        $validos = array_filter($valores, function($v) {
    return is_numeric($v) && $v > 0;
});
                        $media = count($validos) > 0 ? (array_sum($validos) / 3) : '';
                    ?>
                    <tr class="text-center">
                        <td><?= htmlspecialchars($a['matricula']) ?>
                            <input type="hidden" name="matricula[]" value="<?= htmlspecialchars($a['matricula']) ?>">
                        </td>
                        <td><?= htmlspecialchars($a['nome']) ?>
                            <input type="hidden" name="nome[]" value="<?= htmlspecialchars($a['nome']) ?>">
                        </td>
                        <td><?= htmlspecialchars($a['identificadorturma']) ?>
                            <input type="hidden" name="turma[]" value="<?= htmlspecialchars($a['identificadorturma']) ?>">
                        </td>
                        <td><input type="number" step="0.01" min="0" max="10" name="enem1[]" class="form-control nota" value="<?= htmlspecialchars($a['enem_dia1']) ?>"></td>
                        <td><input type="number" step="0.01" min="0" max="10" name="enem2[]" class="form-control nota" value="<?= htmlspecialchars($a['enem_dia2']) ?>"></td>
                        <td><input type="number" step="0.01" min="0" max="10" name="redacao[]" class="form-control nota" value="<?= htmlspecialchars($a['redacao']) ?>"></td>
                        <td><input type="text" class="form-control media" value="<?= $media !== '' ? number_format($media, 2, ',', '') : '-' ?>" readonly style="width:60px; text-align:center; margin:0 auto;"></td>
                        <input type="hidden" name="media[]" value="<?= $media !== '' ? number_format($media, 2, '.', '') : '' ?>">
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr><td colspan="7" class="text-center text-danger">Nenhum aluno encontrado.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>

        <div class="text-center" style="margin-top: 20px;">
            <button type="submit" class="btn btn-success btn-sm">
                <span class="glyphicon glyphicon-floppy-disk"></span> Salvar / Atualizar Notas
            </button>
        </div>
    </form>
</div>

<script>
// ✅ Cálculo automático da média (3 campos)
$(document).on('input', '.nota', function() {
    var linha = $(this).closest('tr');
    var soma = 0;
    var contador = 0;

    linha.find('.nota').each(function() {
        var val = parseFloat($(this).val());
        if (!isNaN(val)) {
            soma += val;
            contador++;
        }
    });

    var media = contador > 0 ? (soma / 3).toFixed(2) : '';
    linha.find('.media').val(media ? media.replace('.', ',') : '-');
    linha.find('input[name="media[]"]').val(media);
});
</script>

</body>
</html>
