<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Financeiro - Morfo Engine</title>
    <style>
        * { box-sizing: border-box; }
        html, body { 
            height: 100%; margin: 0; padding: 0; 
            background-color: #d4d0c8; 
            font-family: "Tahoma", sans-serif; font-size: 11px; 
        }
        
        .desktop-wrapper { 
            display: flex; flex-direction: column; height: 100vh; padding: 4px; 
        }

        .window { 
            display: flex; flex-direction: column; flex: 1; 
            border: 2px solid; border-color: #ffffff #808080 #808080 #ffffff; 
            background: #c0c0c0; box-shadow: 1px 1px 0px #000; 
            min-width: 320px;
        }

        .title-bar { 
            background: linear-gradient(90deg, #000080, #1084d0); color: white; 
            padding: 3px 6px; font-weight: bold; display: flex; justify-content: space-between; align-items: center; 
        }

        .content { 
            padding: 8px; flex: 1; display: flex; flex-direction: column; gap: 8px; 
            overflow-y: auto; overflow-x: hidden; 
        }

        fieldset { border: 2px inset #fff; padding: 10px; margin: 0; min-width: 0; }
        legend { font-weight: bold; padding: 0 5px; }
        
        .header-row { 
            display: flex; flex-wrap: wrap; gap: 8px; 
            margin-bottom: 8px; align-items: flex-end; 
        }

        .field-group { 
            display: flex; flex-direction: column; 
            flex-grow: 1; 
            min-width: 80px; 
        }

        label { margin-bottom: 2px; font-weight: bold; white-space: nowrap; }
        
        .input-search-group { display: flex; gap: 2px; }
        .btn-search { 
            width: 22px; height: 22px; background: #d4d0c8; border: 2px solid; 
            border-color: #fff #808080 #808080 #fff; cursor: pointer; 
            display: flex; align-items: center; justify-content: center; font-size: 12px;
        }

        input, select { 
            padding: 3px; border: 2px inset #fff; background: #fff; 
            font-family: "Tahoma", sans-serif; font-size: 11px; height: 22px; outline: none; width: 100%;
        }
        
        input:focus, select:focus { background: #ffffca; border: 2px inset #000080; }
        .money { text-align: right; font-family: "Courier New", monospace; font-weight: bold; color: #000080; }
        .readonly { background: #e0e0e0; cursor: not-allowed; }

        .table-container { 
            flex: 1; background: #fff; border: 2px solid; 
            border-color: #808080 #fff #fff #808080; overflow: auto; 
            min-height: 150px;
        }

        table { width: 100%; border-collapse: collapse; min-width: 600px; }
        th { 
            border: 1px solid #808080; padding: 6px; background: #d4d0c8; 
            position: sticky; top: 0; font-size: 10px; text-transform: uppercase; z-index: 10;
        }
        td { border: 1px solid #f0f0f0; padding: 2px; }
        
        .footer-bar { 
            display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; padding: 5px 0; 
        }
        
        .btn-main { 
            padding: 4px 15px; background: #d4d0c8; border: 2px solid; 
            border-color: #fff #808080 #808080 #fff; font-weight: bold; cursor: pointer;
            min-width: 100px;
        }
        .btn-main:active { border-color: #808080 #fff #fff #808080; }

        .status-bar { 
            display: flex; flex-wrap: wrap; background: #c0c0c0; border-top: 1px solid #808080; 
        }
        .status-panel { 
            border: 1px inset #fff; padding: 4px 8px; flex: 1; 
            display: flex; justify-content: space-between; align-items: center; 
            min-width: 150px;
        }

        .w-small { flex-grow: 0; flex-basis: 60px; }
        .w-medium { flex-grow: 0; flex-basis: 110px; }
    </style>
</head>
<body>

<div class="desktop-wrapper">
    <div class="window">
        <div class="title-bar">
            <span>Financeiro - Lançamento [Morfo Engine]</span>
            <div style="display:flex; gap: 2px;">
                <button type="button" style="width:16px; height:14px; font-size:9px; background:#c0c0c0; border:1px solid #000;">_</button>
                <button type="button" style="width:16px; height:14px; font-size:9px; background:#c0c0c0; border:1px solid #000;">X</button>
            </div>
        </div>

        <form id="financeiroForm" class="content">
            <fieldset>
                <legend>Dados do Título</legend>
                
                <div class="header-row">
                    <div class="field-group w-small">
                        <label>Cód:</label>
                        <div class="input-search-group">
                            <input type="text" name="codigo" class="readonly" placeholder="AUTO" readonly>
                            <button type="button" class="btn-search">&#128269;</button>
                        </div>
                    </div>
                    <div class="field-group w-small">
                        <label>ID Part.:</label>
                        <input type="text" id="val_id_participante" placeholder="0">
                    </div>
                    <div class="field-group" style="flex-basis: 250px;">
                        <label>Nome do Participante (Fornecedor/Favorecido):</label>
                        <div class="input-search-group">
                            <input type="text" id="val_nome_participante">
                            <button type="button" class="btn-search" onclick="window.open('busca_rapida.php', 'Busca', 'width=550,height=450')">&#128269;</button>
                        </div>
                    </div>
                    <div class="field-group w-medium">
                        <label>Emitente:</label>
                        <select id="val_emitente">
                            <option value="0">0-Própria</option>
                            <option value="1" selected>1-Terceiros</option>
                        </select>
                    </div>
                </div>

                <div class="header-row">
                    <div class="field-group w-small">
                        <label>Tipo:</label>
                        <select id="val_tipo" onchange="atualizarDescricao()">
                            <option value="NF">NF</option>
                            <option value="DU">DUPL</option>
                            <option value="RC">RECIBO</option>
                        </select>
                    </div>
                    <div class="field-group w-medium">
                        <label>Nº Título:</label>
                        <div class="input-search-group">
                            <input type="text" id="val_numero" required oninput="atualizarDescricao()">
                            <button type="button" class="btn-search">&#128269;</button>
                        </div>
                    </div>
                    <div class="field-group w-medium">
                        <label>Pgto Padrão:</label>
                        <select id="val_meio_padrao">
                            <option value="BOLETO">BOLETO</option>
                            <option value="PIX">PIX</option>
                            <option value="DINHEIRO">DINHEIRO</option>
                        </select>
                    </div>
                    <div class="field-group w-medium">
                        <label>Data Lanc:</label>
                        <input type="date" value="2026-04-19">
                    </div>
                    <div class="field-group" style="flex-basis: 200px;">
                        <label>Descrição do Lançamento:</label>
                        <input type="text" id="val_desc">
                    </div>
                    <div class="field-group w-medium">
                        <label>Vlr. Bruto:</label>
                        <input type="text" id="val_bruto" class="money" onkeyup="mascaraMoeda(this)" oninput="atualizarTotais()">
                    </div>
                    <div class="field-group w-medium">
                        <label>Desconto:</label>
                        <input type="text" id="val_desc_v" class="money" onkeyup="mascaraMoeda(this)" oninput="atualizarTotais()">
                    </div>
                    <div class="field-group w-small">
                        <label>Parc:</label>
                        <input type="number" id="val_qtd" value="1" min="1">
                    </div>
                </div>
            </fieldset>

            <fieldset style="flex: 1; display: flex; flex-direction: column;">
                <legend>Grade de Parcelamento</legend>
                <div class="table-container">
                    <table id="tabelaParcelas">
                        <thead>
                            <tr>
                                <th width="150">Identificador</th>
                                <th width="60">Parc.</th>
                                <th width="130">Meio Pgto</th>
                                <th width="130">Vencimento</th>
                                <th>Valor (R$)</th>
                                <th width="40"></th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
                
                <div class="footer-bar">
                    <button type="button" class="btn-main" onclick="gerarParcelas()">GERAR GRADE</button>
                    <button type="button" class="btn-main" onclick="reajustarSoma()">AJUSTAR ÚLTIMA</button>
                    <button type="button" class="btn-main" style="background:#000080; color:white" onclick="alert('Gravando...')">GRAVAR</button>
                </div>
            </fieldset>
        </form>

        <div class="status-bar">
            <div class="status-panel">
                <span>LÍQUIDO: R$ <span id="display_liquido">0,00</span></span>
            </div>
            <div class="status-panel">
                <span style="color:#000080">GRADE: R$ <span id="display_soma">0,00</span></span>
            </div>
        </div>
    </div>
</div>

<script>
    document.getElementById('financeiroForm').addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            const target = e.target;
            if (target.tagName !== 'BUTTON') {
                e.preventDefault();
                gerarParcelas();
                target.blur();
            }
        }
    });

    function atualizarDescricao() {
        const t = document.getElementById('val_tipo').value;
        const n = document.getElementById('val_numero').value;
        document.getElementById('val_desc').value = n ? t + ' ' + n : "";
        atualizarGradeIds();
    }

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

    function fFloat(v) {
        if (!v) return 0;
        return parseFloat(v.replace("R$ ", "").replace(/\./g, "").replace(",", ".")) || 0;
    }

    function atualizarTotais() {
        const liq = fFloat(document.getElementById('val_bruto').value) - fFloat(document.getElementById('val_desc_v').value);
        document.getElementById('display_liquido').innerText = liq.toLocaleString('pt-BR', {minimumFractionDigits:2});
        return liq;
    }

function gerarParcelas() {
    const tipo = document.getElementById('val_tipo').value;
    const num = document.getElementById('val_numero').value;
    
    // 1. Calcula o líquido atualizado (Bruto - Desconto)
    const liq = atualizarTotais(); 
    
    let qtd = parseInt(document.getElementById('val_qtd').value) || 1;
    const tbody = document.querySelector("#tabelaParcelas tbody");

    // Validação básica para não gerar grid vazio ou negativo
    if (!num || liq <= 0) {
        tbody.innerHTML = "";
        validarGrade();
        return;
    }

    tbody.innerHTML = "";

    // 2. Cálculo das parcelas sobre o valor LÍQUIDO
    const vBase = Math.floor((liq / qtd) * 100) / 100; 
    const resto = parseFloat((liq - (vBase * qtd)).toFixed(2));

    for (let i = 1; i <= qtd; i++) {
        let dt = new Date();
        dt.setMonth(dt.getMonth() + (i - 1));
        
        // A última parcela absorve a diferença de centavos do líquido
        let vFinal = (i === qtd) ? (vBase + resto) : vBase;
        
        const row = tbody.insertRow();
        row.innerHTML = `
            <td class="col-id" style="font-weight:bold; color:#000080;">${tipo} ${num}/${i.toString().padStart(2, '0')}</td>
            <td style="text-align:center">${i}</td>
            <td>
                <select name="p_status[]" style="width:100%; border:none;">
                    <option value="A" selected>A - Aberto</option>
                    <option value="F">F - Pago</option>
                    <option value="P">P - Protesto</option>
                </select>
            </td>
            <td><select name="p_meio[]" style="width:100%; border:none;">
                <option value="BOLETO">BOLETO</option>
                <option value="PIX">PIX</option>
                <option value="DINHEIRO">DINHEIRO</option>
            </select></td>
            <td><input type="date" name="p_venc[]" value="${dt.toISOString().split('T')[0]}" style="width:100%; border:none;"></td>
            <td><input type="number" name="p_valor[]" class="p-valor" step="0.01" value="${vFinal.toFixed(2)}" style="width:100%; border:none; text-align:right; font-weight:bold;" oninput="validarGrade()"></td>
            <td style="text-align:center"><button type="button" onclick="this.closest('tr').remove(); validarGrade()" style="color:red; border:none; background:none; cursor:pointer">X</button></td>
        `;
    }
    validarGrade();
}
    function atualizarGradeIds() {
        const t = document.getElementById('val_tipo').value;
        const n = document.getElementById('val_numero').value;
        document.querySelectorAll("#tabelaParcelas tbody tr").forEach((tr, idx) => {
            let p = (idx + 1).toString().padStart(2, '0');
            tr.querySelector(".col-id").innerText = `${t} ${n}/${p}`;
        });
    }

    function validarGrade() {
        let soma = 0;
        document.querySelectorAll('.p-valor').forEach(i => soma += parseFloat(i.value || 0));
        const liq = atualizarTotais();
        const d = document.getElementById('display_soma');
        d.innerText = soma.toLocaleString('pt-BR', {minimumFractionDigits:2});
        d.style.color = (soma.toFixed(2) === liq.toFixed(2)) ? "#008000" : "#b00000";
    }

   
</script>
</body>
</html>