<?php
// 1. CONFIGURAÇÕES E ERROS
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('America/Sao_Paulo');

// 2. CONEXÃO E HEADER
if (file_exists('../config.php')) {
    include_once('../config.php');
} else {
    die("ERRO: CONFIG.PHP NÃO ENCONTRADO.");
}

if (file_exists('../header.php')) {
    include_once('../header.php');
}

// 3. GARANTIR COLUNAS NO BANCO
$conn->query("ALTER TABLE escola_registros ADD COLUMN IF NOT EXISTS valor_nota DECIMAL(10,2) AFTER professor");
$conn->query("ALTER TABLE escola_registros ADD COLUMN IF NOT EXISTS descricao TEXT AFTER valor_nota");

// 4. PROCESSAR LANÇAMENTO
$mensagem = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['btn_lancar_nota'])) {
    $materia   = mysqli_real_escape_string($conn, $_POST['materia_selecionada']);
    $valor     = str_replace(',', '.', $_POST['valor_nota']);
    $descricao = mysqli_real_escape_string($conn, $_POST['descricao_nota']);
    $data_hoje = date('Y-m-d');

    $busca_prof = $conn->query("SELECT professor FROM escola_registros WHERE materia = '$materia' LIMIT 1");
    $row_prof = $busca_prof->fetch_assoc();
    $professor = $row_prof ? $row_prof['professor'] : 'NÃO INFORMADO';

    $sql = "INSERT INTO escola_registros (materia, professor, valor_nota, descricao, data_registro) 
            VALUES ('$materia', '$professor', '$valor', '$descricao', '$data_hoje')";

    if ($conn->query($sql)) {
        $mensagem = "<div class='alert alert-success' style='font-size:11px; padding:5px; margin-bottom:10px;'>✅ VALOR LANÇADO NO BOLETIM!</div>";
    }
}

// 5. BUSCAR LISTA DE MATÉRIAS
$lista_materias = $conn->query("SELECT DISTINCT materia FROM escola_registros ORDER BY materia ASC");

// 6. BUSCAR DADOS PARA A TABELA
$sql_tabela = "SELECT * FROM escola_registros WHERE valor_nota IS NOT NULL AND valor_nota > 0 ORDER BY data_registro DESC, id DESC";
$res_tabela = $conn->query($sql_tabela);
?>

<style>
    .excel-container { padding: 10px; font-family: 'Segoe UI', Tahoma, sans-serif; text-transform: uppercase; }
    .excel-entry-bar { background: #f3f3f3; border: 1px solid #ccc; padding: 15px; margin-bottom: 15px; border-radius: 4px; display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end; }
    .entry-group { display: flex; flex-direction: column; }
    .entry-group label { font-size: 9px; font-weight: bold; color: #217346; margin-bottom: 4px; }
    .entry-input { padding: 7px; border: 1px solid #aba9a9; font-size: 11px; text-transform: uppercase; border-radius: 2px; background: #fff; }
    .btn-lancar { background: #217346; color: white; border: none; padding: 0 20px; font-weight: bold; cursor: pointer; font-size: 11px; border-radius: 2px; height: 35px; }
    .excel-table-wrapper { overflow-x: auto; border: 1px solid #bcbcbc; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
    .excel-table { width: 100%; border-collapse: collapse; background: white; min-width: 650px; }
    .excel-table th { background: #e6e6e6; color: #333; font-size: 10px; border: 1px solid #bcbcbc; padding: 10px 8px; text-align: left; }
    .excel-table td { border: 1px solid #d4d4d4; padding: 8px; font-size: 11px; vertical-align: middle; }
    .excel-table tr:nth-child(even) { background: #f9f9f9; }
    .col-valor { font-weight: 900; color: #000; text-align: center; background: #fffce6; font-size: 13px; border-left: 2px solid #bcbcbc !important; }
    .col-materia { font-weight: 900; color: #217346; }
    @media (max-width: 768px) { .excel-entry-bar { flex-direction: column; align-items: stretch; } .entry-input { width: 100% !important; } }
</style>

<div class="excel-container">
    <?php echo $mensagem; ?>

    <form method="POST" class="excel-entry-bar">
        <div class="entry-group" style="flex: 2; min-width: 200px;">
            <label><i class="fas fa-pen"></i> 1. DESCRIÇÃO</label>
            <input type="text" name="descricao_nota" class="entry-input" placeholder="O QUE É ESTE VALOR?" required autofocus>
        </div>

        <div class="entry-group" style="flex: 1; min-width: 150px;">
            <label><i class="fas fa-book"></i> 2. ESCOLHA A MATÉRIA</label>
            <select name="materia_selecionada" class="entry-input" required>
                <option value="">SELECIONE...</option>
                <?php if($lista_materias): while($m = $lista_materias->fetch_assoc()): ?>
                    <option value="<?php echo $m['materia']; ?>"><?php echo strtoupper($m['materia']); ?></option>
                <?php endwhile; endif; ?>
            </select>
        </div>

        <div class="entry-group" style="flex: 0.5; min-width: 100px;">
            <label><i class="fas fa-star"></i> 3. VALOR</label>
            <input type="text" name="valor_nota" class="entry-input" placeholder="0,00" inputmode="decimal" required>
        </div>

        <button type="submit" name="btn_lancar_nota" class="btn-lancar">
            <i class="fas fa-save"></i> INSERIR NO BOLETIM
        </button>
    </form>

    <div class="excel-table-wrapper">
        <table class="excel-table">
            <thead>
                <tr>
                    <th width="80" style="text-align: center;">DATA</th>
                    <th width="200">DISCIPLINA</th>
                    <th>DESCRIÇÃO DO LANÇAMENTO</th>
                    <th width="100" style="text-align: center;">VALOR</th>
                </tr>
            </thead>
            <tbody>
                <?php if($res_tabela && $res_tabela->num_rows > 0): ?>
                    <?php while($row = $res_tabela->fetch_assoc()): ?>
                    <tr>
                        <td style="text-align: center; color: #666;"><?php echo date('d/m/y', strtotime($row['data_registro'])); ?></td>
                        <td class="col-materia"><?php echo strtoupper($row['materia']); ?></td>
                        <td class="col-desc"><?php echo strtoupper($row['descricao']); ?></td>
                        <td class="col-valor"><?php echo number_format($row['valor_nota'], 2, ',', '.'); ?></td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="4" style="text-align: center; padding: 40px; color: #999;">NENHUM VALOR REGISTRADO.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>