<?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; }
        
        /* AJUSTE PARA LINHA ÚNICA CONFORME FOTO */
        .grid-aba1 { 
            grid-template-columns: 70px 25px 150px 35px 80px 25px 80px 60px 60px 70px 60px 80px; 
            align-items: end;
        }

        .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; }
		
        .tabs-grid-footer { background: #c0c0c0; border: 1px solid #808080; flex-shrink: 0; margin-top: 5px; }
        .tabs-header { display: flex; border-bottom: 1px solid #808080; background: #d4d0c8; padding: 2px 2px 0 2px; }
        .tab-btn { padding: 4px 12px; cursor: pointer; border: 1px solid #808080; border-bottom: none; background: #b0b0b0; font-weight: bold; margin-right: 2px; }
        .tab-btn.active { background: #c0c0c0; border-top: 2px solid #fff; border-left: 2px solid #fff; margin-bottom: -1px; }
        .tab-content { display: none; padding: 5px; background: #c0c0c0; border: 2px inset #fff; }
        .tab-content.active { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 5px; }
        .total-box { border: 1px dotted #808080; padding: 2px 5px; font-size: 10px; }
        .total-box span { color: #000080; font-weight: bold; display: block; }
    </style>
</head>
<body>
<div class="desktop-wrapper">
    <div class="window">
        <div class="title-bar">
            <span>ped - 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="pedForm" action="processar_orcamento.php" method="POST" class="content" onsubmit="event.preventDefault(); salvarped();">
            <fieldset>
                <legend>Cabeçalho</legend>
                <div class="form-grid">
                    <div class="field-group"><label>Nº ped:</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="buscarped()">🔍</button>
                            <input type="text" name="ped_cab_cod_part" id="val_ped_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_ped_cab_nome" name="ped_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="ped_cab_c_v" id="val_ped_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" name="ped_cab_status" id="val_status" value="P" readonly maxlength="1" style="text-align:center"></div>
                </div>
            </fieldset>

<div class="field-group">
    <label>Bem Terc. (Cód/Desc):</label>
    <div class="search-group">
        <input type="text" name="ped_cab_cod_veiculo" id="val_ped_cab_cod_veiculo"   style="width: 90px;">
        <input type="text" id="val_ped_cab_desc_veiculo" name="ped_cab_desc_veiculo"  style="flex: 1;" >
        <button type="button" onclick="buscarVeiculo()">🔍</button>
    </div>
</div> 
            <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="tabs-grid-footer">
                    <div class="tabs-header">
                        <div class="tab-btn active" onclick="mudarAba(event, 'aba-valores')">Valores Gerais</div>
                    
                    </div>

                    <div id="aba-valores" class="tab-content active">
					<div class="total-box" style="background-color: #f8d7da; font-weight: bold;">
                        TOTAL DA NOTA<span>R$ <span id="grand_total_aba">0,00</span></span>
                    </div>
                        <div class="total-box">MERCADORIAS<span>R$ <span id="tot_merc">0,00</span></span></div>
                        <div class="total-box">FRETE<span>R$ <span id="tot_frete">0,00</span></span></div>
                        <div class="total-box">SEGURO<span>R$ <span id="tot_seguro">0,00</span></span></div>
                        <div class="total-box">OUTRAS DESP.<span>R$ <span id="tot_outros">0,00</span></span></div>
                        <div class="total-box">DESCONTO TOTAL<span>R$ <span id="tot_desc">0,00</span></span></div>
                  
                    </div>

                </div>

                <div class="footer-bar">
                    <button type="button" class="btn-main" style="background: #000080; color: white;" onclick="abrirConversao()">CONVERTER ORÇAMENTO</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 PEDIDO</button>
                    <button type="button" class="btn-main" onclick="imprimirped()">Imprimir</button>
           
                </div>
            </fieldset>
        </form>

        <div class="status-bar">
            <div class="status-panel"><span>TOTAL ped: 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_ped_cab_cod_part').value = cab.ped_cab_cod_part;
    document.getElementById('val_ped_cab_nome').value = cab.reg_0150_nome;
    document.getElementById('val_ped_cab_c_v').value = cab.ped_cab_c_v;
    document.getElementById('val_status').value = cab.ped_cab_status.toUpperCase();
	    document.getElementById('val_ped_cab_cod_veiculo').value = cab.ped_cab_cod_veiculo.toUpperCase();
    document.getElementById('val_ped_cab_desc_veiculo').value = cab.ped_cab_desc_veiculo.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>
                
                <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.ped_itens_cod_item:''}" 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.ped_itens_descr_item:''}"></div>
                    <div class="mini-field"><label>UN</label><input type="text" name="item_unid[]" value="${item?item.ped_itens_unid:'UN'}" readonly></div>
                    
                    <div class="mini-field"><label>Marca</label><input type="text" name="ped_itens_marca_item[]" value="${item?item.ped_itens_marca_item:''}"></div>
                    <div class="mini-field"><label>Tipo</label><input type="text" name="ped_itens_tipo_item[]" value="${item?item.ped_itens_tipo_item:''}"></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>
        </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');
    // Troca vírgula por ponto antes de converter para número
    const getVal = (name) => parseFloat(row.querySelector(`[name="${name}"]`).value.replace(',', '.')) || 0;

    const qtd = getVal('item_qtd[]');
    const vlUnit = getVal('item_vl[]');
    const desc = getVal('item_desc[]');
    
    const total = ((qtd * vlUnit) - desc).toFixed(2);
    row.querySelector('.item-total').value = total.replace('.', ','); // Exibe com vírgula se desejar
    atualizarTotalGeral();
}

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 buscarped() { window.open('busca_ped.php', 'Busca', 'width=850,height=600'); }
function buscarParticipante() { window.open('busca_participante.php', 'Busca', 'width=750,height=550'); }
function buscarNatureza(idCampoAlvo) {
    const tipoOperacao = document.getElementById('val_ped_cab_c_v').value;
    const url = 'busca_natureza.php?target=' + idCampoAlvo + '&tipo=' + tipoOperacao;
    window.open(url, 'BuscaNat', 'width=400,height=450,left=300,top=150,scrollbars=yes');
}

function salvarped() {
    const form = document.getElementById('pedForm');
    if(!form.checkValidity()){ form.reportValidity(); return; }

    const btn = document.getElementById('btnSalvar');
    const campoCodigo = document.getElementById('val_codigo');
    
    btn.innerText = "Gravando...";
    btn.disabled = true;

    const formData = new FormData(form);
    
    fetch('processar_ped.php', { method: 'POST', body: formData })
    .then(r => r.text())
    .then(idGerado => {
        const novoId = idGerado.trim();
        if(novoId !== "" && !isNaN(novoId)) {
            campoCodigo.value = novoId;
            alert("Sucesso! Orçamento nº " + novoId);
        } else {
            alert("Resposta do servidor: " + idGerado);
        }
        btn.innerText = "GRAVAR PEDIDO";
        btn.disabled = false;
    })
    .catch(e => {
        alert("Erro técnico ao salvar.");
        btn.innerText = "GRAVAR PEDIDO";
        btn.disabled = false;
    });
}

function abrirConversao() {
    window.open('../ped/orcamento_pedido.php', 'winConversao', `width=900,height=600,scrollbars=yes,resizable=yes`);
}

function imprimirped() {
    const id = document.getElementById('val_codigo').value;
    if (id === 'AUTO' || id === '' || id === 'NOVO') { alert("Grave 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_ped_cab_cod_part').value;
    const nomePart = document.getElementById('val_ped_cab_nome').value;
    const operacao = document.getElementById('val_ped_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 win = window.open('../faturamento/index.php', 'Faturamento', `width=850,height=650,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);
    }
}

function mudarAba(evt, abaId) {
    let i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tab-content");
    for (i = 0; i < tabcontent.length; i++) { tabcontent[i].classList.remove("active"); }
    tablinks = document.getElementsByClassName("tab-btn");
    for (i = 0; i < tablinks.length; i++) { tablinks[i].classList.remove("active"); }
    document.getElementById(abaId).classList.add("active");
    evt.currentTarget.classList.add("active");
}

function atualizarTotalGeral() {
    let s = { merc: 0, desc: 0, frete: 0, seg: 0, out: 0, ipi: 0, vicms: 0, vst: 0, vpis: 0, vcof: 0, vpisst: 0, vcofst: 0, bicms: 0, bst: 0, bpis: 0, bcof: 0 };

    document.querySelectorAll("#tabelaItens tbody tr").forEach(row => {
        const qtd = parseFloat(row.querySelector('[name="item_qtd[]"]')?.value) || 0;
        const vlr = parseFloat(row.querySelector('[name="item_vl[]"]')?.value) || 0;
        const dsc = parseFloat(row.querySelector('[name="item_desc[]"]')?.value) || 0;
        s.merc += (qtd * vlr);
        s.desc += dsc;
        s.vicms += parseFloat(row.querySelector('[name="tax_valor_icms[]"]')?.value) || 0;
        s.vst += parseFloat(row.querySelector('[name="tax_valor_st[]"]')?.value) || 0;
        s.vpis += parseFloat(row.querySelector('[name="tax_valor_pis[]"]')?.value) || 0;
        s.vcof += parseFloat(row.querySelector('[name="tax_valor_cofins[]"]')?.value) || 0;
        s.vpisst += parseFloat(row.querySelector('[name="tax_valor_pisst[]"]')?.value) || 0;
        s.vcofst += parseFloat(row.querySelector('[name="tax_valor_cofinsst[]"]')?.value) || 0;
        s.frete += parseFloat(row.querySelector('[name="tax_frete[]"]')?.value) || 0;
        s.out += parseFloat(row.querySelector('[name="tax_outros[]"]')?.value) || 0;
    });

    const grandTotal = (s.merc - s.desc) + s.vst + s.ipi + s.vpisst + s.vcofst + s.frete + s.out;
    const fmt = (val) => val.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

    document.getElementById('tot_merc').innerText = fmt(s.merc);
    document.getElementById('tot_desc').innerText = fmt(s.desc);
    document.getElementById('grand_total').innerText = fmt(grandTotal);
    if(document.getElementById('grand_total_aba')) document.getElementById('grand_total_aba').innerText = fmt(grandTotal);
}

function buscarVeiculo() {
    // Define a largura e altura da janela
    const largura = 750;
    const altura = 550;

    // Calcula a posição para centralizar
    const esquerda = (screen.width - largura) / 2;
    const topo = (screen.height - altura) / 2;

    // Abre a janela com as posições calculadas
    window.open(
        'busca_veiculo.php', 
        'Busca', 
        `width=${largura},height=${altura},left=${esquerda},top=${topo},scrollbars=yes,resizable=yes`
    );
}
</script>
</body>
</html>