<?php
date_default_timezone_set('America/Sao_Paulo');
include_once('../config.php'); 
include_once('../header.php');

$mensagem = "";

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['btn_salvar'])) {
    $descricao    = strtoupper($_POST['descricao']);
    $observacao   = strtoupper($_POST['observacao']);
    $melhor_data  = intval($_POST['melhor_data']);

    $meses_db = ["jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "setem", "outu", "nov", "dez"];
    $valores = [];

    foreach ($meses_db as $m) {
        $valor_campo = $_POST['val_' . $m] ?? '0,00';
        $valores[$m] = str_replace(',', '.', str_replace('.', '', $valor_campo));
    }

    $sql = "INSERT INTO contas_casa (descricao, observacao, melhor_data, jan, fev, mar, abr, mai, jun, jul, ago, setem, outu, nov, dez) 
            VALUES ('$descricao', '$observacao', '$melhor_data', 
            '{$valores['jan']}', '{$valores['fev']}', '{$valores['mar']}', 
            '{$valores['abr']}', '{$valores['mai']}', '{$valores['jun']}', 
            '{$valores['jul']}', '{$valores['ago']}', '{$valores['setem']}', 
            '{$valores['outu']}', '{$valores['nov']}', '{$valores['dez']}')";

    if ($conn->query($sql)) {
        $mensagem = "<div style='background:#217346; color:white; padding:10px; margin-bottom:15px; border-radius:4px; text-align:center;'>✅ CONTA LANÇADA COM SUCESSO!</div>";
    } else {
        $mensagem = "<div style='background:#dc3545; color:white; padding:10px; margin-bottom:15px; border-radius:4px; text-align:center;'>❌ ERRO: " . $conn->error . "</div>";
    }
}
?>

<style>
    .cadastro-wrapper { padding: 20px; text-transform: uppercase; font-family: 'Segoe UI', sans-serif; max-width: 900px; margin: 0 auto; }
    .form-excel { background: #fff; border: 1px solid #bbb; padding: 25px; border-top: 8px solid #217346; box-shadow: 0 4px 10px rgba(0,0,0,0.1); border-radius: 4px; }
    
    /* LINHA SUPERIOR */
    .row-top { display: grid; grid-template-columns: 2fr 1.5fr 0.5fr; gap: 15px; margin-bottom: 20px; }
    .form-group { display: flex; flex-direction: column; }
    .form-group label { font-size: 10px; font-weight: bold; color: #217346; margin-bottom: 5px; }
    .form-group input { padding: 10px; border: 1px solid #ccc; font-weight: bold; border-radius: 3px; }

    /* GRADE DE MESES CORRIGIDA */
    .section-title { font-size: 10px; font-weight: bold; color: #217346; margin-bottom: 15px; padding-bottom: 5px; border-bottom: 2px solid #217346; display: block; }
    
    .valores-grid { 
        display: grid; 
        grid-template-columns: repeat(4, 1fr); /* 4 colunas iguais */
        gap: 15px; 
        background: #f8f9fa; 
        padding: 20px; 
        border: 1px solid #ddd; 
        border-radius: 4px;
    }
    
    .mes-box { display: flex; align-items: center; justify-content: space-between; background: #fff; padding: 5px 10px; border: 1px solid #eee; border-radius: 3px; }
    .mes-box label { font-size: 10px; font-weight: bold; color: #444; width: 40px; }
    .mes-box input { width: 100%; text-align: right; font-size: 11px; padding: 6px; border: 1px solid #ccc; font-family: monospace; font-weight: bold; }
    .mes-box input:focus { border-color: #217346; background: #fffde7; outline: none; }

    .btn-salvar { background: #217346; color: white; border: none; padding: 16px; font-weight: bold; cursor: pointer; width: 100%; border-radius: 3px; font-size: 13px; margin-top: 25px; transition: 0.3s; }
    .btn-salvar:hover { background: #1a5c38; box-shadow: 0 4px 8px rgba(0,0,0,0.2); }
    .btn-voltar { display: block; text-align: center; margin-top: 20px; color: #666; text-decoration: none; font-size: 10px; font-weight: bold; }
</style>

<div class="cadastro-wrapper">
    <h2 style="text-align:center; color:#217346; font-size: 16px; margin-bottom: 20px;">📊 LANÇAMENTO ANUAL DETALHADO</h2>
    
    <?php echo $mensagem; ?>

    <div class="form-excel">
        <form method="POST">
            <div class="row-top">
                <div class="form-group">
                    <label>DESCRIÇÃO DA CONTA</label>
                    <input type="text" name="descricao" required placeholder="EX: PARCELA CARRO">
                </div>
                <div class="form-group">
                    <label>OBSERVAÇÃO / DETALHES</label>
                    <input type="text" name="observacao" placeholder="EX: FINAL 10/12">
                </div>
                <div class="form-group">
                    <label>DIA VENC.</label>
                    <input type="number" name="melhor_data" min="1" max="31" required value="10">
                </div>
            </div>

            <span class="section-title">INFORME OS VALORES EM CADA MÊS (DEIXE 0,00 PARA OS MESES SEM CONTA)</span>
            
            <div class="valores-grid">
                <?php 
                $m_list = [
                    "JAN" => "jan", "FEV" => "fev", "MAR" => "mar", "ABR" => "abr", 
                    "MAI" => "mai", "JUN" => "jun", "JUL" => "jul", "AGO" => "ago", 
                    "SET" => "setem", "OUT" => "outu", "NOV" => "nov", "DEZ" => "dez"
                ];
                foreach ($m_list as $exibir => $banco): 
                ?>
                    <div class="mes-box">
                        <label><?php echo $exibir; ?></label>
                        <input type="text" name="val_<?php echo $banco; ?>" value="0,00" oninput="mascaraMoeda(this)">
                    </div>
                <?php endforeach; ?>
            </div>

            <button type="submit" name="btn_salvar" class="btn-salvar">💾 SALVAR NA PLANILHA ANUAL</button>
        </form>
    </div>

    <a href="contas.php" class="btn-voltar">⬅️ VOLTAR PARA A PLANILHA PRINCIPAL</a>
</div>

<script>
function mascaraMoeda(i) {
    let v = i.value.replace(/\D/g,'');
    v = (v/100).toFixed(2) + '';
    v = v.replace(".", ",");
    v = v.replace(/(\d)(\d{3})(\d{3}),/g, "$1.$2.$3,");
    v = v.replace(/(\d)(\d{3}),/g, "$1.$2,");
    i.value = v;
}
</script>