<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('America/Sao_Paulo');
include_once('../config.php');

$data_alvo = $_GET['data'] ?? date('Y-m-d');

// --- 1. SALVAMENTO AUTOMÁTICO (VIA AJAX) ---
if (isset($_POST['ajax_sync'])) {
    $d = $_POST['dt'];
    $mo_ab = str_replace(',', '.', str_replace('.', '', $_POST['mo_ab']));
    $no_ab = str_replace(',', '.', str_replace('.', '', $_POST['no_ab']));
    $bo_ab = str_replace(',', '.', str_replace('.', '', $_POST['bo_ab']));
    $mp_ab = str_replace(',', '.', str_replace('.', '', $_POST['mp_ab']));
    $total_ab = (float)$mo_ab + (float)$no_ab + (float)$bo_ab + (float)$mp_ab;

    $mo = str_replace(',', '.', str_replace('.', '', $_POST['mo']));
    $no = str_replace(',', '.', str_replace('.', '', $_POST['no']));
    $bo = str_replace(',', '.', str_replace('.', '', $_POST['bo']));
    $mp = str_replace(',', '.', str_replace('.', '', $_POST['mp']));
    $total_f = (float)$mo + (float)$no + (float)$bo + (float)$mp;

    $conn->query("DELETE FROM fechamentos_caixa WHERE data = '$d'");
    $sql = "INSERT INTO fechamentos_caixa (data, moedas_ab, notas_ab, bolsinha_ab, mp_ab, total_abertura, moedas, notas, bolsinha, mercado_pago, total_fechamento) 
            VALUES ('$d', '$mo_ab', '$no_ab', '$bo_ab', '$mp_ab', '$total_ab', '$mo', '$no', '$bo', '$mp', '$total_f')";
    $conn->query($sql);
    exit;
}

// --- 2. BUSCA DE DADOS ---
$f = $conn->query("SELECT * FROM fechamentos_caixa WHERE data = '$data_alvo'")->fetch_assoc();

$movimentos = $conn->query("SELECT ID, DATA_MOVIMENTACAO, TIPO, USUARIO, CLIENTE_FORNECEDOR, SUM(QUANTIDADE) as TOTAL_QTD, GROUP_CONCAT(PRODUTO_NOME SEPARATOR ' + ') as PRODUTOS, COUNT(PRODUTO_NOME) as QTD_ITENS_DIFERENTES, FORMA_PAGAMENTO, SUM(VALOR_TOTAL) as SOMA_TOTAL FROM movimentacoes WHERE DATE(DATA_MOVIMENTACAO) = '$data_alvo' GROUP BY DATA_MOVIMENTACAO, CLIENTE_FORNECEDOR, TIPO, USUARIO, FORMA_PAGAMENTO ORDER BY DATA_MOVIMENTACAO ASC");

$t = $conn->query("SELECT SUM(CASE WHEN TIPO='ENTRADA' THEN VALOR_TOTAL ELSE 0 END) as E, SUM(CASE WHEN TIPO='SAÍDA' THEN VALOR_TOTAL ELSE 0 END) as S FROM movimentacoes WHERE DATE(DATA_MOVIMENTACAO) = '$data_alvo'")->fetch_assoc();
$entradas = (float)($t['E'] ?? 0);
$saidas = (float)($t['S'] ?? 0);

include_once('../header.php');
?>

<style>
    .caixa-body { background: #fff; padding: 20px; font-family: 'Segoe UI', sans-serif; text-transform: uppercase; }
    
    #status_caixa { width: 100%; padding: 15px; margin-bottom: 15px; border-radius: 4px; text-align: center; font-weight: bold; font-size: 18px; color: #fff; }
    .status-ok { background-color: #28a745 !important; }      
    .status-sobra { background-color: #007bff !important; }   
    .status-falta { background-color: #dc3545 !important; }    

    .resumo-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 10px; margin-bottom: 20px; }
    .card-res { padding: 10px; text-align: center; border-radius: 4px; color: #fff !important; font-weight: bold; font-size: 10px; }
    .v-res { font-size: 15px; display: block; margin-top: 5px; }

    .tab-conf { width: 100%; border-collapse: collapse; margin-bottom: 20px; border: 2px solid #333; }
    .tab-conf td { padding: 8px; border: 1px solid #ccc; font-weight: bold; }
    .label-grey { background: #eeeeee !important; width: 25%; }
    .input-edit { width: 100%; border: none; background: transparent; text-align: right; font-weight: bold; font-size: 14px; outline: none; }

    .planilha-caixa { width: 100%; border-collapse: collapse; font-size: 11px; border: 1px solid #ccc; }
    .planilha-caixa th { background: #000 !important; color: #fff !important; padding: 10px; border: 1px solid #333; text-align: left; }
    .planilha-caixa td { padding: 8px; border: 1px solid #ddd; vertical-align: middle; }
    
    .linha-entrada { background: #ccffcc !important; color: #000; }
    .linha-saida { background: #ffcccc !important; color: #000; }
    
    .label-venda { font-size: 9px; font-weight: bold; display: inline-block; padding: 2px 6px; border-radius: 3px; margin-bottom: 3px; color: #fff !important; }
    .venda-simples { background: #8e44ad !important; } 
    .venda-multipla { background: #f1c40f !important; color: #000 !important; } 
    .saida-label { background: #ff0000 !important; } 

    .badge-pg { padding: 4px 8px; border-radius: 4px; font-weight: bold; color: #fff !important; font-size: 10px; display: block; text-align: center; min-width: 90px; }
    .pg-dinheiro { background: #2e7d32 !important; }
    .pg-pix { background: #00bcd4 !important; }
    .pg-cartao { background: #f39c12 !important; }
    .pg-outros { background: #7f8c8d !important; }

    @media print {
        /* FORÇA CORES NA IMPRESSÃO */
        * { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
        
        .no-print, .btn-print, .top-category-bar, .system-title-bar, .ribbon-bar { display: none !important; }
        body { background: #fff; padding: 0; }
        .caixa-body { padding: 0; }
        .tab-conf, .planilha-caixa { border: 1px solid #000 !important; }
        .planilha-caixa th { background: #000 !important; color: #fff !important; }
        .linha-entrada { background: #ccffcc !important; }
        .linha-saida { background: #ffcccc !important; }
    }
</style>

<div class="caixa-body">
    <div class="no-print" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
        <a href="caixas.php" style="background:#333; color:#fff; padding:8px 15px; text-decoration:none; border-radius:4px; font-weight:bold; font-size:11px;">⬅ VOLTAR</a>
        <h2 style="font-size:14px; margin:0;">ARQUIVO: <?php echo date('d/m/Y', strtotime($data_alvo)); ?></h2>
        <button onclick="window.print()" style="background:#00569e; color:#fff; border:none; padding:8px 15px; border-radius:4px; cursor:pointer; font-weight:bold;"><i class="fa fa-print"></i> IMPRIMIR COLORIDO</button>
    </div>

    <div id="status_caixa" class="status-ok">CALCULANDO...</div>

    <div class="resumo-grid">
        <div class="card-res" style="background:#607d8b !important;">ABERTURA<span class="v-res" id="res_ab">R$ 0,00</span></div>
        <div class="card-res" style="background:#2e7d32 !important;">ENTRADAS<span class="v-res">R$ <?php echo number_format($entradas, 2, ',', '.'); ?></span></div>
        <div class="card-res" style="background:#c62828 !important;">SAÍDAS<span class="v-res">R$ <?php echo number_format($saidas, 2, ',', '.'); ?></span></div>
        <div class="card-res" style="background:#0288d1 !important;">SALDO ESPERADO<span class="v-res" id="res_esperado">R$ 0,00</span></div>
        <div class="card-res" style="background:#455a64 !important;">FECHAMENTO<span class="v-res" id="res_fe">R$ 0,00</span></div>
    </div>

    <table class="tab-conf">
        <tr>
            <td class="label-grey">MOEDAS</td>
            <td><input type="text" id="mo_ab" class="input-edit" value="<?php echo number_format($f['moedas_ab'] ?? 0, 2, ',', '.'); ?>" oninput="mascara(this); calc()"></td>
            <td><input type="text" id="mo_fe" class="input-edit" value="<?php echo number_format($f['moedas'] ?? 0, 2, ',', '.'); ?>" oninput="mascara(this); calc()"></td>
        </tr>
        <tr>
            <td class="label-grey">NOTAS</td>
            <td><input type="text" id="no_ab" class="input-edit" value="<?php echo number_format($f['notas_ab'] ?? 0, 2, ',', '.'); ?>" oninput="mascara(this); calc()"></td>
            <td><input type="text" id="no_fe" class="input-edit" value="<?php echo number_format($f['notas'] ?? 0, 2, ',', '.'); ?>" oninput="mascara(this); calc()"></td>
        </tr>
        <tr>
            <td class="label-grey">BOLSINHA</td>
            <td><input type="text" id="bo_ab" class="input-edit" value="<?php echo number_format($f['bolsinha_ab'] ?? 0, 2, ',', '.'); ?>" oninput="mascara(this); calc()"></td>
            <td><input type="text" id="bo_fe" class="input-edit" value="<?php echo number_format($f['bolsinha'] ?? 0, 2, ',', '.'); ?>" oninput="mascara(this); calc()"></td>
        </tr>
        <tr>
            <td class="label-grey">MERCADO PAGO</td>
            <td><input type="text" id="mp_ab" class="input-edit" value="<?php echo number_format($f['mp_ab'] ?? 0, 2, ',', '.'); ?>" oninput="mascara(this); calc()"></td>
            <td><input type="text" id="mp_fe" class="input-edit" value="<?php echo number_format($f['mercado_pago'] ?? 0, 2, ',', '.'); ?>" oninput="mascara(this); calc()"></td>
        </tr>
    </table>

    <table class="planilha-caixa">
        <thead>
            <tr>
                <th>HORA</th>
                <th>TIPO</th>
                <th>USUÁRIO</th>
                <th>CLIENTE</th>
                <th style="text-align:center">QTD</th>
                <th>PRODUTO / MOTIVO</th>
                <th style="text-align:right">TOTAL</th>
                <th style="text-align:center">PAGAMENTO</th>
            </tr>
        </thead>
        <tbody>
            <?php while($m = $movimentos->fetch_assoc()): 
                $tipo = $m['TIPO'];
                $classe_linha = ($tipo == 'SAÍDA') ? 'linha-saida' : 'linha-entrada';
                $metodo = strtoupper($m['FORMA_PAGAMENTO']);

                $classe_pg = 'pg-outros';
                if(strpos($metodo, 'DINHEIRO') !== false) $classe_pg = 'pg-dinheiro';
                elseif(strpos($metodo, 'PIX') !== false) $classe_pg = 'pg-pix';
                elseif(strpos($metodo, 'CARTÃO') !== false || strpos($metodo, 'DÉBITO') !== false || strpos($metodo, 'CRÉDITO') !== false) $classe_pg = 'pg-cartao';

                if($tipo == 'SAÍDA') {
                    $txt_label = "[ SAÍDA DE CAIXA ]";
                    $classe_label = "saida-label";
                } else {
                    $txt_label = ($m['QTD_ITENS_DIFERENTES'] > 1) ? "[ VENDA MÚLTIPLA ]" : "[ VENDA SIMPLES ]";
                    $classe_label = ($m['QTD_ITENS_DIFERENTES'] > 1) ? "venda-multipla" : "venda-simples";
                }
            ?>
            <tr class="<?php echo $classe_linha; ?>">
                <td style="font-weight:bold;"><?php echo date('H:i', strtotime($m['DATA_MOVIMENTACAO'])); ?></td>
                <td><strong><?php echo $tipo; ?></strong></td>
                <td><?php echo $m['USUARIO']; ?></td>
                <td><?php echo $m['CLIENTE_FORNECEDOR']; ?></td>
                <td style="text-align:center"><?php echo (int)$m['TOTAL_QTD']; ?></td>
                <td>
                    <span class="label-venda <?php echo $classe_label; ?>"><?php echo $txt_label; ?></span><br>
                    <?php echo $m['PRODUTOS']; ?>
                </td>
                <td style="text-align:right; font-weight:bold;">R$ <?php echo number_format($m['SOMA_TOTAL'], 2, ',', '.'); ?></td>
                <td style="text-align:center;"><span class="badge-pg <?php echo $classe_pg; ?>"><?php echo $m['FORMA_PAGAMENTO']; ?></span></td>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

<script>
function mascara(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;
}

function sParaF(s) {
    if(!s) return 0;
    return parseFloat(s.replace(/\./g, '').replace(',', '.')) || 0;
}

const vE = <?php echo $entradas; ?>;
const vS = <?php echo $saidas; ?>;

function calc() {
    let t_ab = sParaF(document.getElementById('mo_ab').value) + sParaF(document.getElementById('no_ab').value) + sParaF(document.getElementById('bo_ab').value) + sParaF(document.getElementById('mp_ab').value);
    let t_fe = sParaF(document.getElementById('mo_fe').value) + sParaF(document.getElementById('no_fe').value) + sParaF(document.getElementById('bo_fe').value) + sParaF(document.getElementById('mp_fe').value);
    
    let esperado = (t_ab + vE) - vS;
    let dif = t_fe - esperado;
    
    const fmt = (v) => v.toLocaleString('pt-br', {style: 'currency', currency: 'BRL'});
    document.getElementById('res_ab').innerText = fmt(t_ab);
    document.getElementById('res_fe').innerText = fmt(t_fe);
    document.getElementById('res_esperado').innerText = fmt(esperado);

    const ds = document.getElementById('status_caixa');
    ds.className = '';
    if (Math.abs(dif) < 0.01) { ds.innerText = "✅ CAIXA OK"; ds.classList.add('status-ok'); }
    else if (dif > 0) { ds.innerText = "🔵 SOBROU " + fmt(dif); ds.classList.add('status-sobra'); }
    else { ds.innerText = "🔴 FALTOU " + fmt(Math.abs(dif)); ds.classList.add('status-falta'); }

    let fd = new FormData();
    fd.append('ajax_sync', 1); fd.append('dt', '<?php echo $data_alvo; ?>');
    fd.append('mo_ab', document.getElementById('mo_ab').value); fd.append('no_ab', document.getElementById('no_ab').value);
    fd.append('bo_ab', document.getElementById('bo_ab').value); fd.append('mp_ab', document.getElementById('mp_ab').value);
    fd.append('mo', document.getElementById('mo_fe').value); fd.append('no', document.getElementById('no_fe').value);
    fd.append('bo', document.getElementById('bo_fe').value); fd.append('mp', document.getElementById('mp_fe').value);
    fetch(window.location.href, { method: 'POST', body: fd });
}
window.onload = calc;
</script>