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

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

// 1. LÓGICA DE BAIXA RÁPIDA (Double Click)
if (isset($_GET['baixa_rapida'])) {
    $id = intval($_GET['id']); 
    $col = mysqli_real_escape_string($conn, $_GET['col']);
    $val = floatval($_GET['val']); 
    
    if ($val == 0) {
        $novo_val = -0.01;
    } elseif ($val > 0) {
        $novo_val = abs($val) * -1;
    } else {
        $novo_val = ($val == -0.01) ? 0 : abs($val);
    }
    
    $conn->query("UPDATE contas_casa SET `$col` = '$novo_val' WHERE id = $id");
    echo "<script>window.location.href='contas.php';</script>"; exit;
}

// 2. SALVAR VALOR DIGITADO
if (isset($_POST['atualizar_valor'])) {
    $id = intval($_POST['id']); 
    $coluna_mes = mysqli_real_escape_string($conn, $_POST['mes_col']);
    // Limpeza de formatação brasileira para decimal do banco
    $valor_limpo = str_replace(',', '.', str_replace('.', '', $_POST['valor_digitado']));
    $conn->query("UPDATE contas_casa SET `$coluna_mes` = '$valor_limpo' WHERE id = $id");
    echo "<script>window.location.href='contas.php';</script>"; exit;
}

// 3. EXCLUSÃO
if (isset($_GET['excluir'])) {
    $conn->query("DELETE FROM contas_casa WHERE id = " . intval($_GET['excluir']));
    echo "<script>window.location.href='contas.php';</script>"; exit;
}

$contas_query = $conn->query("SELECT * FROM contas_casa ORDER BY descricao ASC");
$contas = [];
$totais_pendentes = array_fill_keys($meses_colunas, 0);

while($row = $contas_query->fetch_assoc()) {
    $contas[] = $row;
    foreach($meses_colunas as $m) {
        $v = floatval($row[$m]);
        if ($v > 0) $totais_pendentes[$m] += $v;
    }
}

$mes_atual_idx = date('n') - 1;
$coluna_atual = $meses_colunas[$mes_atual_idx];
?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

<style>
    .excel-container { padding: 10px; font-family: 'Segoe UI', sans-serif; text-transform: uppercase; overflow-x: auto; }
    .excel-table { width: 100%; border-collapse: collapse; font-size: 9px; background: white; border: 1px solid #bbb; min-width: 1200px; }
    .excel-table th { background: #217346; color: white; border: 1px solid #bbb; padding: 5px; }
    .excel-table td { border: 1px solid #ccc; text-align: center; height: 35px; vertical-align: middle; color: #000 !important; font-weight: bold !important; }
    .campo-pendente { background-color: #FA8072 !important; }
    .campo-pago { background-color: #00FA9A !important; }
    .txt-pendente { color: #d6453d !important; font-weight: 900 !important; }
    .btn-acao { text-decoration: none; font-size: 8px; font-weight: bold; color: #00569e; }
    .input-excel { width: 100%; border: none; text-align: center; background: transparent; font-weight: bold; font-size: 9px; outline: none; color: #000; height: 100%; }
    .btn-whatsapp { background: #25D366; color: white; border: none; cursor: pointer; padding: 8px 15px; font-weight: bold; border-radius: 4px; font-size: 11px; margin-right: 5px; display: inline-flex; align-items: center; }

    #area-foto { 
        position: absolute; left: -9999px; top: 0; 
        background: #fff; padding: 20px; width: 450px; border: 2px solid #217346;
    }
    .foto-titulo { color: #217346; text-align: center; margin-bottom: 15px; font-family: sans-serif; }
    .foto-table { width: 100%; border-collapse: collapse; font-family: sans-serif; font-size: 14px; }
    .foto-table th { background: #217346; color: white; padding: 10px; border: 1px solid #ddd; }
    .foto-table td { padding: 10px; border: 1px solid #ddd; color: #333; }
    .foto-total { background: #f2f2f2; font-weight: bold; font-size: 16px; }
</style>

<div class="excel-container">
    <div style="display: flex; justify-content: space-between; margin-bottom: 10px; align-items: center;">
        <h2 style="color: #217346; font-size: 14px; margin: 0;">📅 PLANILHA ANUAL DE CONTAS</h2>
        <div>
            <button onclick="gerarImagem()" class="btn-whatsapp">📲 COMPARTILHAR IMAGEM</button>
            <a href="cadastrar_conta.php" style="background: #217346; color: white; text-decoration: none; padding: 8px 15px; font-weight: bold; border-radius: 4px; font-size: 11px;">➕ NOVA CONTA</a>
        </div>
    </div>

    <table class="excel-table">
        <thead>
            <tr>
                <th>DESCRIÇÃO</th>
                <th>OBSERVAÇÃO</th>
                <th style="width:30px;">DIA</th>
                <th style="width:60px;">AÇÕES</th>
                <?php foreach(["JAN","FEV","MAR","ABR","MAI","JUN","JUL","AGO","SET","OUT","NOV","DEZ"] as $m): ?> 
                    <th style="width:70px;"><?php echo $m; ?></th> 
                <?php endforeach; ?>
            </tr>
            <tr style="background:#f2f2f2; font-weight:bold;">
                <td colspan="4" style="text-align: right; padding-right:5px;">TOTAL PENDENTE:</td>
                <?php foreach($meses_colunas as $m): ?>
                    <td style="width:70px;"><span class="txt-pendente">R$ <?php echo number_format($totais_pendentes[$m], 2, ',', '.'); ?></span></td>
                <?php endforeach; ?>
            </tr>
        </thead>
        <tbody>
            <?php foreach($contas as $c): ?>
            <tr>
                <td style="text-align:left; padding-left:5px; font-weight:bold;"><?php echo $c['descricao']; ?></td>
                <td style="text-align:left; padding-left:5px; font-size:8px; color:#666;"><?php echo $c['observacao']; ?></td>
                <td style="background:#eee; font-weight:bold;"><?php echo str_pad($c['melhor_data'], 2, "0", STR_PAD_LEFT); ?></td>
                <td>
                    <a href="alterar_conta.php?id=<?php echo $c['id']; ?>" class="btn-acao">ALT</a> | 
                    <a href="contas.php?excluir=<?php echo $c['id']; ?>" class="btn-acao" style="color:red;" onclick="return confirm('APAGAR?')">EXC</a>
                </td>
                
                <?php foreach($meses_colunas as $col): 
                    $v = floatval($c[$col]);
                    $classe = ($v > 0) ? "campo-pendente" : ($v < 0 ? "campo-pago" : "");
                ?>
                <td class="<?php echo $classe; ?>" ondblclick="window.location.href='contas.php?baixa_rapida=1&id=<?php echo $c['id']; ?>&col=<?php echo $col; ?>&val=<?php echo $v; ?>'" style="cursor:pointer; width:70px; padding: 0;">
                    <form method="POST" style="margin:0; height:100%; display: flex; flex-direction: column; justify-content: center;">
                        <input type="hidden" name="id" value="<?php echo $c['id']; ?>">
                        <input type="hidden" name="mes_col" value="<?php echo $col; ?>">
                        <input type="hidden" name="atualizar_valor" value="1">
                        
                        <input type="text" name="valor_digitado" class="input-excel" 
                               value="<?php echo ($v != 0 && $v != -0.01) ? number_format(abs($v), 2, ',', '.') : ''; ?>" 
                               placeholder="<?php echo ($v == -0.01) ? 'S/ ATIV' : '0,00'; ?>"
                               onchange="this.form.submit()">

                        <?php if($v != 0 && $v != -0.01): ?>
                            <small style="font-size:7px; display: block; line-height: 1;"><?php echo ($v > 0) ? "PEND" : "PAGO"; ?></small>
                        <?php endif; ?>
                    </form>
                </td>
                <?php endforeach; ?>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<div id="area-foto">
    <div class="foto-titulo">
        <h2 style="margin:0;">📋 CONTAS DO MÊS</h2>
        <small><?php echo strtoupper($coluna_atual); ?> / 2026</small>
    </div>
    <table class="foto-table">
        <thead>
            <tr>
                <th align="left">DESCRIÇÃO</th>
                <th align="right">VALOR</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $existe_pendencia = false;
            foreach($contas as $c): 
                $v_atual = floatval($c[$coluna_atual]);
                if($v_atual > 0): 
                    $existe_pendencia = true;
            ?>
            <tr>
                <td><?php echo strtoupper($c['descricao']); ?></td>
                <td align="right">R$ <?php echo number_format($v_atual, 2, ',', '.'); ?></td>
            </tr>
            <?php endif; endforeach; ?>
            
            <?php if(!$existe_pendencia): ?>
            <tr>
                <td colspan="2" align="center" style="color:green; padding: 20px;">✅ TUDO PAGO NESTE MÊS!</td>
            </tr>
            <?php endif; ?>

            <tr class="foto-total">
                <td>TOTAL PENDENTE</td>
                <td align="right">R$ <?php echo number_format($totais_pendentes[$coluna_atual], 2, ',', '.'); ?></td>
            </tr>
        </tbody>
    </table>
    <p style="text-align:center; font-size:10px; color:#999; margin-top:10px;">Gerado em: <?php echo date('d/m/Y H:i'); ?></p>
</div>

<script>
function gerarImagem() {
    const area = document.getElementById('area-foto');
    html2canvas(area, { scale: 2 }).then(canvas => {
        canvas.toBlob(function(blob) {
            const file = new File([blob], "contas_mes.png", { type: "image/png" });
            if (navigator.canShare && navigator.canShare({ files: [file] })) {
                navigator.share({
                    files: [file],
                    title: 'Contas Pendentes',
                    text: 'Segue resumo das contas pendentes do mês.'
                }).catch(error => console.log('Erro ao compartilhar:', error));
            } else {
                const link = document.createElement('a');
                link.download = 'contas_pendentes.png';
                link.href = canvas.toDataURL("image/png");
                link.click();
                alert("Imagem baixada. Agora você pode anexar no WhatsApp.");
            }
        }, 'image/png');
    });
}
</script>