<?php
// 1. CONFIGURAÇÕES
ini_set('display_errors', 0); 
date_default_timezone_set('America/Sao_Paulo');

include_once('../config.php'); 
include_once('../header.php');

// 2. IDENTIFICAR MÊS ATUAL
$meses_col = ["jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "setem", "outu", "nov", "dez"];
$mes_idx = (int)date('m') - 1; 
$coluna_mes = $meses_col[$mes_idx];

// 3. DADOS DE CONTAS (FILTRADO POR VENCIMENTO)
$total_pendente = 0; $total_pago = 0;
$res_contas_total = $conn->query("SELECT `$coluna_mes` FROM contas_casa");
if($res_contas_total) {
    while($row = $res_contas_total->fetch_assoc()) {
        $v = floatval($row[$coluna_mes]);
        if($v > 0) $total_pendente += $v;
        elseif ($v < 0) $total_pago += abs($v);
    }
}
// BUSCA 5 CONTAS PENDENTES (> 0) ORDENADAS PELO DIA (melhor_data)
$proximas_contas = $conn->query("SELECT descricao, melhor_data, `$coluna_mes` as valor 
                                 FROM contas_casa 
                                 WHERE `$coluna_mes` > 0 
                                 ORDER BY melhor_data ASC LIMIT 5");

// 4. SALDO POR CONTA (CAIXA)
$contas_bancarias = []; $saldo_geral = 0;
$res_bancos = $conn->query("SELECT id, nome_conta FROM contas_bancarias_casa");
if($res_bancos) {
    while($banco = $res_bancos->fetch_assoc()) {
        $id_c = $banco['id'];
        $res_s = $conn->query("SELECT SUM(CASE WHEN tipo = 'ENTRADA' THEN valor ELSE 0 END) - SUM(CASE WHEN tipo = 'SAIDA' THEN valor ELSE 0 END) as saldo FROM lancamentos_casa WHERE conta_id = $id_c");
        $saldo_c = ($res_s) ? floatval($res_s->fetch_assoc()['saldo']) : 0;
        $contas_bancarias[] = ['nome' => $banco['nome_conta'], 'saldo' => $saldo_c];
        $saldo_geral += $saldo_c;
    }
}
$ultimos_lancamentos = $conn->query("SELECT l.*, c.nome_conta FROM lancamentos_casa l JOIN contas_bancarias_casa c ON l.conta_id = c.id ORDER BY l.data_mov DESC, l.id DESC LIMIT 5");

// 5. RESUMO DO CARTÃO
$total_alexandre = 0; $total_fran = 0;
$res_cartao_fatura = $conn->query("SELECT dono, `$coluna_mes` FROM cartao_credito");
if($res_cartao_fatura){
    while($rc = $res_cartao_fatura->fetch_assoc()){
        $val_c = abs(floatval($rc[$coluna_mes]));
        if(strpos(strtoupper($rc['dono']), 'ALEXANDRE') !== false) $total_alexandre += $val_c;
        else $total_fran += $val_c;
    }
}
$ultimos_cartao = $conn->query("SELECT descricao, dono, `$coluna_mes` as valor FROM cartao_credito WHERE `$coluna_mes` <> 0 ORDER BY id DESC LIMIT 5");

// 6. MANUTENÇÃO
$total_manutencao = 0;
$res_m_total = $conn->query("SELECT SUM(valor) as total FROM manutencoes_veiculos");
$total_manutencao = ($res_m_total) ? floatval($res_m_total->fetch_assoc()['total']) : 0;
$ultimas_manutencoes = $conn->query("SELECT m.*, v.nome as v_nome FROM manutencoes_veiculos m JOIN veiculos v ON m.veiculo_id = v.id ORDER BY m.data_servico DESC LIMIT 5");
?>

<style>
    .dashboard-wrapper { padding: 10px; font-family: 'Segoe UI', sans-serif; text-transform: uppercase; background: #f4f4f4; }
    .grid-resumo { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; }
    .card-valor { background: white; border-radius: 8px; padding: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); border: 1px solid #ddd; display: flex; flex-direction: column; min-height: 280px; }
    .card-valor h3 { margin: 0 0 10px 0; font-size: 10px; color: #fff; text-align: center; background: #333; padding: 6px; border-radius: 4px; }
    .lista-registros { flex-grow: 1; }
    .reg-row { display: flex; justify-content: space-between; padding: 5px 0; border-bottom: 1px solid #eee; font-size: 8.5px; font-weight: bold; align-items: center; }
    .reg-row span { color: #666; max-width: 140px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .footer-card { text-align: center; border-top: 2px solid #eee; padding-top: 8px; margin-top: 8px; }
    .valor-footer { font-size: 18px; font-weight: 900; font-family: monospace; display: block; }
    .txt-azul { color: #00569e; } .txt-vermelho { color: #d6453d; } .txt-verde { color: #217346; }
    .tag-dia { font-size: 7.5px; background: #f2f2f2; padding: 2px 4px; border-radius: 3px; color: #333; margin-right: 5px; border: 1px solid #ccc; }
    @media (max-width: 1000px) { .grid-resumo { grid-template-columns: 1fr; } }
</style>

<div class="dashboard-wrapper">
    <div style="margin-bottom: 15px; font-weight: 900; color: #333; border-left: 5px solid #217346; padding-left: 10px; font-size: 14px;">
        PAINEL GERAL - <?php echo strtoupper($coluna_mes); ?> / <?php echo date('Y'); ?>
    </div>

    <div class="grid-resumo">
        <div class="card-valor">
            <h3>💰 ÚLTIMOS LANÇAMENTOS</h3>
            <div class="lista-registros">
                <?php while($l = $ultimos_lancamentos->fetch_assoc()): ?>
                <div class="reg-row">
                    <span><?php echo $l['descricao']; ?></span>
                    <b class="<?php echo ($l['tipo']=='ENTRADA')?'txt-verde':'txt-vermelho'; ?>">
                        R$ <?php echo number_format($l['valor'], 2, ',', '.'); ?>
                    </b>
                </div>
                <?php endwhile; ?>
            </div>
            <div class="footer-card">
                <small style="font-size: 7px;">SALDO GERAL</small>
                <span class="valor-footer txt-azul">R$ <?php echo number_format($saldo_geral, 2, ',', '.'); ?></span>
            </div>
        </div>

        <div class="card-valor">
            <h3>📅 PRÓXIMOS VENCIMENTOS</h3>
            <div class="lista-registros">
                <?php if($proximas_contas && $proximas_contas->num_rows > 0): ?>
                    <?php while($c = $proximas_contas->fetch_assoc()): ?>
                    <div class="reg-row">
                        <span><b class="tag-dia">DIA <?php echo str_pad($c['melhor_data'], 2, "0", STR_PAD_LEFT); ?></b> <?php echo $c['descricao']; ?></span>
                        <b class="txt-vermelho">R$ <?php echo number_format($c['valor'], 2, ',', '.'); ?></b>
                    </div>
                    <?php endwhile; ?>
                <?php else: ?>
                    <div style="text-align:center; font-size:9px; color:green; margin-top:20px; font-weight:bold;">✅ TUDO PAGO NESTE MÊS!</div>
                <?php endif; ?>
            </div>
            <div class="footer-card">
                <small style="font-size: 7px;">TOTAL A PAGAR</small>
                <span class="valor-footer txt-vermelho">R$ <?php echo number_format($total_pendente, 2, ',', '.'); ?></span>
            </div>
        </div>

        <div class="card-valor">
            <h3>💳 GASTOS NO CARTÃO</h3>
            <div class="lista-registros">
                <?php while($cart = $ultimos_cartao->fetch_assoc()): ?>
                <div class="reg-row">
                    <span><?php echo $cart['descricao']; ?> <i style="font-size:7px; background:#eee; padding:1px 3px;"><?php echo strtoupper(substr($cart['dono'],0,1)); ?></i></span>
                    <b>R$ <?php echo number_format(abs($cart['valor']), 2, ',', '.'); ?></b>
                </div>
                <?php endwhile; ?>
            </div>
            <div class="footer-card">
                <small style="font-size: 7px;">FATURA DO MÊS</small>
                <span class="valor-footer" style="color:#000;">R$ <?php echo number_format($total_alexandre + $total_fran, 2, ',', '.'); ?></span>
            </div>
        </div>

        <div class="card-valor">
            <h3>🔧 ÚLTIMAS MANUTENÇÕES</h3>
            <div class="lista-registros">
                <?php while($m = $ultimas_manutencoes->fetch_assoc()): ?>
                <div class="reg-row">
                    <span><?php echo $m['v_nome']; ?> - <?php echo $m['descricao']; ?></span>
                    <b>R$ <?php echo number_format($m['valor'], 2, ',', '.'); ?></b>
                </div>
                <?php endwhile; ?>
            </div>
            <div class="footer-card">
                <small style="font-size: 7px;">TOTAL VEÍCULOS</small>
                <span class="valor-footer" style="color:#666;">R$ <?php echo number_format($total_manutencao, 2, ',', '.'); ?></span>
            </div>
        </div>
    </div>
</div>