<?php
session_start();
if (!isset($_SESSION['id'])) { header("Location: ../index/index.php"); exit(); }

include '../config.php';
include '../configuracao/modelo.php';

if (!isset($mysqli) || $mysqli->connect_error) {
    die("Erro de conexão.");
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>NF - Meu Mec</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; overflow: hidden; }
        .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; }
        .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: hidden; }
        fieldset { border: 2px inset #fff; padding: 10px; margin: 0; }
        legend { font-weight: bold; padding: 0 5px; }
        .form-grid { display: grid; grid-template-columns: 100px 150px 1fr 140px 60px; gap: 8px; }
        .field-group { display: flex; flex-direction: column; }
        label { margin-bottom: 2px; font-weight: bold; }
        input, select { padding: 3px; border: 2px inset #fff; background: #fff; font-family: "Tahoma", sans-serif; font-size: 11px; height: 22px; }
        input[readonly] { background: #d4d0c8; color: #404040; cursor: not-allowed; }
        .search-group { display: flex; align-items: center; }
        .btn-search { width: 22px; height: 22px; background: #c0c0c0; border: 2px solid; border-color: #fff #808080 #808080 #fff; cursor: pointer; display: flex; align-items: center; justify-content: center; margin: 0 1px; }
        .table-container { flex: 1; background: #fff; border: 2px solid; border-color: #808080 #fff #fff #808080; overflow-y: auto; }
        table { width: 100%; border-collapse: collapse; }
        th { border: 1px solid #808080; padding: 6px; background: #d4d0c8; position: sticky; top: 0; font-size: 10px; text-transform: uppercase; }
        td { border: 1px solid #f0f0f0; padding: 2px; }
        .totalizador-tipos-linha { background: #f0f0f0; border-top: 2px solid #808080; padding: 5px; font-weight: bold; font-size: 10px; display: flex; gap: 10px; min-height: 25px; }
        .tipo-tag { background: #d4d0c8; border: 1px inset #fff; padding: 2px 5px; color: #000080; }
        .footer-bar { display: flex; justify-content: flex-end; gap: 10px; padding: 5px 0; }
        .btn-main { padding: 6px 20px; background: #d4d0c8; border: 2px solid; border-color: #fff #808080 #808080 #fff; font-weight: bold; cursor: pointer; }
        .status-bar { display: flex; padding: 2px; background: #c0c0c0; border-top: 1px solid #808080; height: 28px; }
        .status-panel { border: 1px inset #fff; padding: 2px 8px; flex: 1; display: flex; justify-content: space-between; align-items: center; }
    </style>
</head>

<body>
<div class="desktop-wrapper">
    <div class="window">
        <div class="title-bar">
            <span>NF - Gestão de Notas Fiscais</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="orcForm" action="processar_nf.php" method="POST" class="content">
            <fieldset>
                <legend>Cabeçalho do NF</legend>
                <div class="form-grid">
                    <div class="field-group"><label>Nº NF:</label><input type="text" name="codigo" id="val_codigo" readonly placeholder="NOVO"></div>
                    <div class="field-group">
                        <label>Cód. Cliente:</label>
                        <div class="search-group">
                            <button type="button" class="btn-search" onclick="buscarnf()">🔍</button>
                            <input type="text" name="nf_cab_cod_part" id="val_nf_cab_cod_part" required >
                        </div>
                    </div>
                    <div class="field-group">
                        <label>Nome / Razão Social:</label>
                        <div class="search-group">
                            <input type="text" id="val_nf_cab_nome" name="nf_cab_nome" style="flex: 1;" required >
                            <button type="button" class="btn-search" onclick="buscarParticipante()">🔍</button>
                        </div>
                    </div>
                    <div class="field-group">
                        <label>Operação:</label>
                        <select name="nf_cab_c_v" id="val_nf_cab_c_v">
                            <option value="S" selected>Saída</option>
                            <option value="E">Entrada</option>
                        </select>
                    </div>
                    <div class="field-group"><label>Status:</label><input type="text" name="nf_cab_status" id="val_nf_cab_status" value="P" readonly maxlength="1" style="text-align:center"></div>
                </div>
                <div style="display: flex; gap: 8px; margin-top: 8px;">
                    <div class="field-group" style="width: 150px;"><label>Emissão:</label><input type="date" readonly name="nf_cab_dt_emi" id="val_nf_cab_dt_emi" value="<?= date('Y-m-d') ?>"></div>
                    <div class="field-group" style="flex: 1;">
                        <label>Bem Terc. (Cód/Desc):</label>
                        <div class="search-group">
                            <input type="text" name="nf_cab_cod_veiculo" id="val_nf_cab_cod_veiculo" style="width: 80px;">
                            <input type="text" id="val_nf_cab_desc_veiculo" name="nf_cab_desc_veiculo" style="flex: 1;">
                        </div>
                    </div>
                </div>
            </fieldset>

            <fieldset style="flex: 1; display: flex; flex-direction: column;">
                <legend>Itens</legend>
                <div class="table-container">
                    <table id="tabelaItens">
                        <thead>
                            <tr>
                                <th width="110">Código</th>
                                <th>Descrição do Produto</th>
                                <th width="90">Marca</th>
                                <th width="40">UN</th>
                                <th width="40">Tipo</th>
                                <th width="140">Nat. Operação</th>
                                <th width="70">Qtd</th>
                                <th width="90">Unitário</th>
                                <th width="70">Desc.</th>
                                <th width="90">Total</th>
                                <th width="30"></th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
                <div class="totalizador-tipos-linha" id="linha_totais_tipos"></div>
                <div class="footer-bar">
                    <button type="button" class="btn-main" style="background: #000080; color: white;" onclick="abrirConversao()">CONVERTER PEDIDO</button>
                    <button type="button" class="btn-main" onclick="adicionarLinha()">+ INSERIR ITEM</button>
                    <button type="submit" id="btnSalvar" class="btn-main" style="background: #008000; color: white;">GRAVAR NF</button>
                    <button type="button" class="btn-main" onclick="imprimirnf()">Imprimir</button>
                    <button type="button" class="btn-main" onclick="abrirFaturamento()">Financeiro</button>
                </div>
            </fieldset>
        </form>
        <div class="status-bar">
            <div class="status-panel"><span>Pronto | Conectado à trib_cont</span></div>
            <div class="status-panel">
                <span style="color:#000080">TOTAL: R$ </span><span id="grand_total" style="font-size: 14px; color: #b00000; font-weight: bold;">0,00</span>
                <input type="hidden" name="nf_cab_tot_nf" id="val_nf_cab_tot_nf" value="0.00">
            </div>
        </div>
    </div>
</div>

<script>
let rowCount = 0;
window.onload = () => { if(rowCount === 0) adicionarLinha(); };

function adicionarLinha(item = null) {
    rowCount++;
    const tbody = document.querySelector("#tabelaItens tbody");
    const row = tbody.insertRow();
    const idRow = 'prod_' + rowCount;
    
    const natSel = item ? (item.nf_itens_nat_oper || 'VENDA') : 'VENDA';

    row.innerHTML = `
        <td>
            <div class="search-group">
                <input type="text" name="item_cod[]" id="value_${idRow}" style="flex:1" value="${item ? item.nf_itens_cod_item : ''}" required>
                <button type="button" class="btn-search" onclick="buscarProduto('busca_produto.php?target=${idRow}', 'BuscaProd')">🔍</button>
            </div>
        </td>
        <td><input type="text" name="item_descr[]" id="display_${idRow}" style="width:100%" readonly value="${item ? item.nf_itens_descr_item : ''}"></td>
        <td><input type="text" name="item_marca[]" id="marca_${idRow}" style="width:100%" readonly value="${item ? item.nf_itens_marca_item : ''}"></td>
        <td><input type="text" name="item_unid[]" id="unid_${idRow}" style="width:100%; text-align:center;" readonly value="${item ? item.nf_itens_unid : ''}"></td>
        <td><input type="text" name="item_tipo[]" id="tipo_${idRow}" style="width:100%; text-align:center;" readonly value="${item ? item.nf_itens_tipo_item : ''}"></td>
        
        <td>
            <div class="search-group">
                <input type="text" name="nfe_itens_nat_oper[]" id="nat_${idRow}" style="flex:1" value="${natSel}" required>
                <button type="button" class="btn-search" onclick="buscarNatureza('${idRow}')">🔍</button>
            </div>
        </td>
        
        <td><input type="number" name="item_qtd[]" style="width:100%" step="0.001" oninput="calcular(this)" value="${item ? (item.nf_itens_qtd_item || item.item_qtd) : '1.000'}" required></td>
        <td><input type="number" name="item_vl[]" id="vl_${idRow}" style="width:100%" step="0.01" oninput="calcular(this)" value="${item ? (item.nf_itens_vl_item || item.item_vl) : '0.00'}" required></td>
        <td><input type="number" name="item_desc[]" style="width:100%" step="0.01" oninput="calcular(this)" value="${item ? (item.nf_itens_desc_item_vl || 0) : '0.00'}" required></td>
        <td><input type="text" name="item_tot[]" class="item-total" style="width:100%" readonly value="${item ? (item.nf_itens_tot_item || 0) : '0.00'}"></td>
        <td><button type="button" style="color:red; cursor:pointer; background:none; border:none; font-weight:bold;" onclick="removerLinha(this)">X</button></td>
    `;
    if(item) calcular(row.querySelector('[name="item_qtd[]"]'));
}

function buscarNatureza(id) {
    // 1. Pegamos o valor do select 'val_nf_cab_c_v' (S ou E)
    const tipoOperacao = document.getElementById('val_nf_cab_c_v').value;
    
    // 2. Passamos 'target' E 'tipo' na URL
    const url = 'busca_natureza.php?target=' + id + '&tipo=' + tipoOperacao;
    
    window.open(url, 'BuscaNat', 'width=400,height=450,left=300,top=150,scrollbars=yes');
}

function calcular(el) {
    const row = el.closest('tr');
    const qtd = parseFloat(row.querySelector('[name="item_qtd[]"]').value) || 0;
    const vlUnit = parseFloat(row.querySelector('[name="item_vl[]"]').value) || 0;
    const desc = parseFloat(row.querySelector('[name="item_desc[]"]').value) || 0;
    const total = ((qtd * vlUnit) - desc).toFixed(2);
    row.querySelector('.item-total').value = total;
    atualizarTotalGeral();
}

function atualizarTotalGeral() {
    let somaTotal = 0;
    let totaisPorTipo = {};
    document.querySelectorAll("#tabelaItens tbody tr").forEach(row => {
        const totalItem = parseFloat(row.querySelector('.item-total').value) || 0;
        const tipoField = row.querySelector('[name="item_tipo[]"]');
        const tipo = tipoField ? tipoField.value : '??';
        somaTotal += totalItem;
        if (totalItem > 0) totaisPorTipo[tipo] = (totaisPorTipo[tipo] || 0) + totalItem;
    });
    document.getElementById('grand_total').innerText = somaTotal.toLocaleString('pt-BR', { minimumFractionDigits: 2 });
    document.getElementById('val_nf_cab_tot_nf').value = somaTotal.toFixed(2);
    
    let html = "";
    for (const [t, v] of Object.entries(totaisPorTipo)) {
        html += `<div class="tipo-tag">TIPO ${t}: R$ ${v.toLocaleString('pt-BR', {minimumFractionDigits:2})}</div>`;
    }
    document.getElementById('linha_totais_tipos').innerHTML = html;
}

function removerLinha(btn) {
    if(document.querySelectorAll("#tabelaItens tbody tr").length > 1) {
        btn.closest('tr').remove();
        atualizarTotalGeral();
    }
}

function carregarDadosDoBanco(dados) {
    document.querySelector("#tabelaItens tbody").innerHTML = "";
    rowCount = 0;
    if(dados.cabecalho) {
        Object.keys(dados.cabecalho).forEach(key => {
            const el = document.getElementById('val_' + key);
            if(el) el.value = dados.cabecalho[key];
        });
        const status = dados.cabecalho.nf_cab_status;
        const btnSalvar = document.getElementById('btnSalvar');
        if (status === 'F' || status === 'M') {
            btnSalvar.disabled = true;
            btnSalvar.innerText = "NF BLOQUEADA";
            btnSalvar.style.background = "#808080";
        }
    }
    if(dados.itens) dados.itens.forEach(i => adicionarLinha(i));
    atualizarTotalGeral();
}

function buscarnf() { window.open('busca_nf.php', 'Busca', 'width=750,height=550,left=100,top=100,scrollbars=yes'); }
function buscarParticipante() { window.open('busca_participante.php', 'Busca', 'width=750,height=550,left=100,top=100,scrollbars=yes'); }
function buscarProduto(url, titulo) { window.open(url, titulo, 'width=600,height=500,left=100,top=100,scrollbars=yes'); }
function abrirConversao() { window.open('../nf/pedido_nf.php', 'winConversao', 'width=900,height=600,scrollbars=yes'); }

function imprimirnf() {
    const id = document.getElementById('val_codigo').value;
    if (id === 'AUTO' || id === '' || id === 'NOVO') {
        alert("Grave a NF antes de imprimir.");
        return;
    }
    window.open('imprime_consulta.php?id=' + id, '_blank');
}

function abrirFaturamento() {
    const idOrcamento = document.getElementById('val_codigo').value;
    const idPart = document.getElementById('val_nf_cab_cod_part').value;
    const nomePart = document.getElementById('val_nf_cab_nome').value;
    const operacao = document.getElementById('val_nf_cab_c_v').value;

    if (idOrcamento === 'AUTO' || idOrcamento === '' || idOrcamento === 'NOVO') {
        alert("⚠️ Grave o orçamento antes de faturar.");
        return;
    }

    const temi = (operacao === 'S') ? '0' : '1';
    const largura = 850;
    const altura = 650;
    const esquerda = (screen.width - largura) / 2;
    const topo = (screen.height - altura) / 2;

    const win = window.open('../faturamento/index.php', 'Faturamento', 
                `width=${largura},height=${altura},left=${esquerda},top=${topo},scrollbars=yes,resizable=yes`);

    if (win) {
        const checkLoad = setInterval(() => {
            try {
                if (win.document.readyState === 'complete') {
                    clearInterval(checkLoad);
                    if (win.document.getElementById('val_numero')) win.document.getElementById('val_numero').value = idOrcamento;
                    if (win.document.getElementById('val_id_participante')) win.document.getElementById('val_id_participante').value = idPart;
                    if (win.document.getElementById('val_nome_participante')) win.document.getElementById('val_nome_participante').value = nomePart;
                    if (win.document.getElementById('val_reg_c140_ind_emit')) win.document.getElementById('val_reg_c140_ind_emit').value = temi;
                    if (typeof win.atualizarDescricao === 'function') win.atualizarDescricao();
                }
            } catch (e) {}
        }, 500);
    }
}
</script>
</body>
</html>