<?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 - Gestão de Impostos por Item</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; overflow: hidden; }
        .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; flex-shrink: 0; }
        .content { padding: 8px; flex: 1; display: flex; flex-direction: column; gap: 8px; overflow: hidden; }
        fieldset { border: 2px inset #fff; padding: 10px; margin: 0; flex-shrink: 0; }
        legend { font-weight: bold; padding: 0 5px; }
        #itens-fieldset { flex: 1; display: flex; flex-direction: column; min-height: 0; }
        .form-grid { display: grid; grid-template-columns: 80px 120px 1fr 120px 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: 20px; background: #c0c0c0; border: 2px solid; border-color: #fff #808080 #808080 #fff; cursor: pointer; display: flex; align-items: center; justify-content: center; }
        .table-container { flex: 1; background: #fff; border: 2px solid; border-color: #808080 #fff #fff #808080; overflow-y: scroll; }
        table { width: 100%; border-collapse: collapse; }
        th { border: 1px solid #808080; padding: 4px; background: #d4d0c8; position: sticky; top: 0; font-size: 10px; z-index: 10; }
        td { border: 1px solid #808080; padding: 4px; vertical-align: top; background: #c0c0c0; }
        .row-tabs-container { display: flex; flex-direction: column; background: #c0c0c0; border: 1px solid #808080; width: 100%; }
        .row-tabs-header { display: flex; background: #d4d0c8; padding: 2px 2px 0 2px; gap: 2px; }
        .row-tab-btn { padding: 2px 6px; cursor: pointer; border: 1px solid #808080; border-bottom: none; background: #b0b0b0; font-size: 9px; font-weight: bold; }
        .row-tab-btn.active { background: #c0c0c0; border-top: 1px solid #fff; border-left: 1px solid #fff; margin-bottom: -1px; z-index: 2; }
        .row-tab-content { display: none; padding: 5px; border: 1px inset #fff; gap: 5px; }
        .row-tab-content.active { display: grid; }
        .mini-field { display: flex; flex-direction: column; }
        .mini-field label { font-size: 9px; margin-bottom: 1px; }
        .mini-field input { height: 18px; font-size: 10px; padding: 1px 3px; }
        .grid-aba1 { grid-template-columns: 80px 25px 180px 40px 100px 70px 90px 70px 90px; }
        .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 Itens (Compacto)</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;" onclick="location.reload()">X</button>
            </div>
        </div>

        <form id="orcForm" action="processar_nf.php" method="POST" class="content">
            <fieldset>
                <legend>Cabeçalho</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">Saída</option>
                            <option value="E">Entrada</option>
                        </select>
                    </div>
                    <div class="field-group"><label>Status:</label><input type="text" id="val_status" value="P" readonly maxlength="1" style="text-align:center"></div>
                </div>
            </fieldset>

            <fieldset id="itens-fieldset">
                <legend>Itens</legend>
                <div class="table-container">
                    <table id="tabelaItens">
                        <thead>
                            <tr>
                                <th width="25">X</th>
                                <th>Dados do Item e Impostos</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>

                <div class="footer-bar">
                    <button type="button" class="btn-main" onclick="adicionarLinha()">+ INSERIR ITEM</button>
                    <button type="button" id="btnSalvar" class="btn-main" style="background: #008000; color: white;" onclick="salvarNF()">GRAVAR NF</button>
                </div>
            </fieldset>
        </form>

        <div class="status-bar">
            <div class="status-panel"><span>TOTAL NF: R$ <span id="grand_total" style="font-weight:bold; color:#b00000;">0,00</span></span></div>
        </div>
    </div>
</div>

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

function carregarDadosDoBanco(dados) {
    const cab = dados.cabecalho;
    const itens = dados.itens;

    document.getElementById('val_codigo').value = cab.codigo;
    document.getElementById('val_nf_cab_cod_part').value = cab.nf_cab_cod_part;
    document.getElementById('val_nf_cab_nome').value = cab.reg_0150_nome;
    document.getElementById('val_nf_cab_c_v').value = cab.nf_cab_c_v;
    document.getElementById('val_status').value = cab.nf_cab_status.toUpperCase();

    const tbody = document.querySelector("#tabelaItens tbody");
    tbody.innerHTML = "";
    rowCount = 0;

    itens.forEach(item => {
        adicionarLinha(item);
    });
    atualizarTotalGeral();
}

function adicionarLinha(item = null) {
    rowCount++;
    const tbody = document.querySelector("#tabelaItens tbody");
    const row = tbody.insertRow();
    const id = rowCount;
    
    row.innerHTML = `
        <td align="center">
            <button type="button" style="color:red; font-weight:bold; height:18px; border:1px solid #808080;" onclick="removerLinha(this)">X</button>
        </td>
        <td>
            <div class="row-tabs-container">
                <div class="row-tabs-header">
                    <div class="row-tab-btn active" onclick="mudarTabInterna(this, 'dados_${id}')">1. Dados</div>
                    <div class="row-tab-btn" onclick="mudarTabInterna(this, 'icms_${id}')">2. ICMS</div>
                    <div class="row-tab-btn" onclick="mudarTabInterna(this, 'pis_${id}')">3. PIS</div>
                    <div class="row-tab-btn" onclick="mudarTabInterna(this, 'cofins_${id}')">4. COFINS</div>
                    <div class="row-tab-btn" onclick="mudarTabInterna(this, 'outros_${id}')">5. OUTROS</div>
                </div>
                
                <div id="dados_${id}" class="row-tab-content active grid-aba1">
                    <div class="mini-field"><label>Código</label><input type="text" name="item_cod[]" id="value_prod_${id}" value="${item?item.nf_itens_cod_item:'0.00'}" required></div>
                    <div class="mini-field"><label>&nbsp;</label><button type="button" class="btn-search" onclick="buscarProduto('prod_${id}')">🔍</button></div>
                    <div class="mini-field"><label>Descrição</label><input type="text" name="item_descr[]" id="display_prod_${id}" readonly value="${item?item.nf_itens_descr_item:''}"></div>
                    <div class="mini-field"><label>UN</label><input type="text" name="item_unid[]" value="${item?item.nf_itens_unid:'UN'}" readonly></div>
                    <div class="mini-field"><label>Nat. Op</label><input type="text" name="nfe_itens_nat_oper[]" value="${item?item.nfe_itens_nat_oper:'VENDA'}"></div>
                    <div class="mini-field"><label>Qtd</label><input type="number" name="item_qtd[]" step="0.001" oninput="calcular(this)" value="${item?item.item_qtd:'1.000'}"></div>
                    <div class="mini-field"><label>Vlr. Unit</label><input type="number" name="item_vl[]" step="0.01" oninput="calcular(this)" value="${item?item.item_vl:'0.00'}"></div>
                    <div class="mini-field"><label>Desc.</label><input type="number" name="item_desc[]" step="0.01" oninput="calcular(this)" value="${item?item.item_desc:'0.00'}"></div>
                    <div class="mini-field"><label>Total Item</label><input type="text" name="item_tot[]" class="item-total" readonly value="${item?item.item_tot:'0.00'}" style="background:#eee"></div>
                </div>

                <div id="icms_${id}" class="row-tab-content" style="grid-template-columns: repeat(7, 1fr);">
                    <div class="mini-field"><label>Base ICMS</label><input type="number" name="tax_base_icms[]" step="0.01" value="${  item?item.tax_base_icms:'0.00'}"></div>
                    <div class="mini-field"><label>% ICMS</label><input type="number" name="tax_aliq_icms[]" step="0.01" value="${     item?item.tax_aliq_icms:'0.00'}"></div>
                    <div class="mini-field"><label>Valor ICMS</label><input type="number" name="tax_valor_icms[]" step="0.01" value="${item?item.tax_valor_icms:'0.00'}"></div>
                    <div class="mini-field"><label>Base ST</label><input type="number" name="tax_base_st[]" step="0.01" value="${      item?item.tax_base_st:'0.00'}"></div>
                    <div class="mini-field"><label>% ST</label><input type="number" name="tax_base_st[]" step="0.01" value="${item?    item.tax_aliq_st:'0.00'}"></div>
                    <div class="mini-field"><label>IVA/MVA</label><input type="number" name="tax_ivaicms_st[]" step="0.01" value="${   item?item.tax_iva_st:'0.00'}"></div>
                    <div class="mini-field"><label>Valor ST</label><input type="number" name="tax_valor_st[]" step="0.01" value="${    item?item.tax_valor_st:'0.00'}"></div>
                </div>

                <div id="pis_${id}" class="row-tab-content" style="grid-template-columns: repeat(6, 1fr);">
				
				
				
                    <div class="mini-field"><label>BASE PIS</label><input type="number" name="tax_base_pis[]" value="${item?item.tax_base_pis:'0.00'"></div>
                    <div class="mini-field"><label>% PIS</label><input type="number" name="tax_aliquota_pis[]" value="${item?item.tax_aliq_pis:'0.00'"></div>
                    <div class="mini-field"><label>Valor PIS</label><input type="number" name="tax_valor_pis[]" value="${item?item.tax_valor_pis:'0.00'"></div>
                    <div class="mini-field"><label>BASE PIS ST</label><input type="number" name="tax_base_pisst[]" value="${item?item.tax_valor_st:'0.00'"></div>
                    <div class="mini-field"><label>% PIS ST</label><input type="number" name="tax_aliquota_pisst[]" value="${item?item.tax_valor_st:'0.00'"></div>
                    <div class="mini-field"><label>Valor PIS ST</label><input type="number" name="tax_valor_pisst[]" value="${item?item.tax_valor_st:'0.00'"></div>
                </div>
				
                <div id="cofins_${id}" class="row-tab-content" style="grid-template-columns: repeat(6, 1fr);">
                    <div class="mini-field"><label>Base COFINS</label><input type="number" name="tax_base_cofins[]" value="${item?item.tax_valor_st:'0.00'"></div>
                    <div class="mini-field"><label>% COFINS</label><input type="number" name="tax_aliquotas_cofins[]" value="${item?item.tax_valor_st:'0.00'"></div>
                    <div class="mini-field"><label>Valor COFINS</label><input type="number" name="tax_valor_cofins[]" value="${item?item.tax_valor_st:'0.00'"></div>
                    <div class="mini-field"><label>Base COFINSST</label><input type="number" name="tax_base_cofinsst[]" value="${item?item.tax_valor_st:'0.00'"></div>
                    <div class="mini-field"><label>% COFINS ST</label><input type="number" name="tax_aliquotta_cofinsst[]" value="${item?item.tax_valor_st:'0.00'"></div>
                    <div class="mini-field"><label>Valor COFINS ST</label><input type="number" name="tax_valor_cofinsst[]" value="${item?item.tax_valor_st:'0.00'"></div>
                   </div>
				
                <div id="outros_${id}" class="row-tab-content" style="grid-template-columns: repeat(3, 1fr);">
                    <div class="mini-field"><label>CFOP</label><input type="text" name="tax_CFOP[]" value=""></div>
                    <div class="mini-field"><label>Frete Item</label><input type="number" name="tax_frete[]" value="0.00"></div>
                    <div class="mini-field"><label>Outros</label><input type="number" name="tax_outros[]" value="0.00"></div>
                </div>

            </div>
        </td>
    `;
}

function mudarTabInterna(btn, contentId) {
    const container = btn.closest('.row-tabs-container');
    container.querySelectorAll('.row-tab-btn').forEach(b => b.classList.remove('active'));
    container.querySelectorAll('.row-tab-content').forEach(c => c.classList.remove('active'));
    btn.classList.add('active');
    document.getElementById(contentId).classList.add('active');
}

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 grand = 0;
    document.querySelectorAll('.item-total').forEach(input => { grand += parseFloat(input.value) || 0; });
    document.getElementById('grand_total').innerText = grand.toLocaleString('pt-BR', { minimumFractionDigits: 2 });
}

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

function buscarProduto(id) { window.open('busca_produto.php?target=' + id, 'BuscaProd', 'width=600,height=500'); }
function buscarnf() { window.open('busca_nf.php', 'Busca', 'width=850,height=600'); }
function buscarParticipante() { window.open('busca_participante.php', 'Busca', 'width=750,height=550'); }

function salvarNF() {
    const btn = document.getElementById('btnSalvar');
    btn.innerText = "Gravando...";
    const formData = new FormData(document.getElementById('orcForm'));
    fetch('processar_nf.php', { method: 'POST', body: formData })
    .then(r => r.text())
    .then(() => { alert("Registro Salvo!"); location.reload(); })
    .catch(() => alert("Erro ao salvar."));
}
</script>
</body>
</html>