const Invoicing=(()=>{const t="/pos/api/invoicing";function e(){return localStorage.getItem("pos_token")||""}async function a(a,n={}){const o=await fetch(`${t}${a}`,{headers:{Authorization:`Bearer ${e()}`,"Content-Type":"application/json"},...n});if(!o.ok){const t=await o.json().catch((()=>({error:o.statusText})));throw new Error(t.error||"Request failed")}return o.json()}function n(t){return parseFloat(t||0).toLocaleString("es-MX",{minimumFractionDigits:2,maximumFractionDigits:2})}function o(t){document.querySelectorAll(".tab-btn").forEach((t=>{t.classList.remove("is-active"),t.setAttribute("aria-selected","false")})),document.querySelectorAll(".tab-panel").forEach((t=>t.classList.remove("is-active")));const e=document.querySelector(`.tab-btn[onclick*="'${t}'"]`)||document.getElementById(`tab-${t}`);e&&(e.classList.add("is-active"),e.setAttribute("aria-selected","true"));const a=document.getElementById(`panel-${t}`);a&&a.classList.add("is-active"),"facturas"===t&&r(),"notas"===t&&s(),"complementos"===t&&l(),"cancelaciones"===t&&i()}function c(t){const e={pending:{css:"badge--pendiente",label:"Pendiente"},pendiente:{css:"badge--pendiente",label:"Pendiente"},sending:{css:"badge--proceso",label:"Enviando"},stamped:{css:"badge--timbrada",label:"Timbrada"},timbrada:{css:"badge--timbrada",label:"Timbrada"},failed:{css:"badge--rechazada",label:"Fallido"},cancelled:{css:"badge--cancelada",label:"Cancelada"},cancelada:{css:"badge--cancelada",label:"Cancelada"},ppd:{css:"badge--ppd",label:"PPD"},proceso:{css:"badge--proceso",label:"En proceso"},aceptada:{css:"badge--aceptada",label:"Aceptada SAT"},rechazada:{css:"badge--rechazada",label:"Rechazada SAT"}}[t]||{css:"",label:t||""};return`${e.label}`}async function r(){const e=document.getElementById("panel-facturas");if(!e)return;const o=e.querySelector(".data-table tbody");if(o)try{const r=await a("/queue?per_page=50&type=Ingreso"),s=r.data||[];if(!s.length)return void(o.innerHTML='
No hay solicitudes de cancelacion.
');e.innerHTML=r.map((t=>{const e="cancelled"===t.status?"cancel-card--aceptada":"cancelling"===t.status?"cancel-card--proceso":!1===t.cancel_accepted?"cancel-card--rechazada":"cancel-card--proceso",a="cancelled"===t.status?c("aceptada"):!1===t.cancel_accepted?c("rechazada"):c("proceso");return`Error: ${t.message}
`}}function d(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}let p=null;function u(t){p=t;const e=document.getElementById("modalCancelOverlay");e&&(e.style.display="flex")}async function m(){if(!p)return;const t=document.getElementById("modalCancelOverlay");if(!t)return;const e=t.querySelector('input[name="motivo-sat"]:checked');if(!e)return void alert("Selecciona un motivo de cancelacion.");const n=e.value,o=t.querySelector('input[type="text"]'),c=o?o.value.trim():"";if("01"!==n||c){if(confirm("Confirmar cancelacion ante el SAT?"))try{const e={motive:n};c&&(e.replacement_uuid=c),await a(`/cancel/${p}`,{method:"POST",body:JSON.stringify(e)}),t.style.display="none",p=null,r(),alert("CFDI cancelado exitosamente.")}catch(t){alert("Error: "+t.message)}}else alert("UUID sustituto requerido para motivo 01.")}function v(){const t=document.getElementById("newInvoiceModalOverlay");if(!t)return;const e=t.querySelector("#invoiceSaleId");e&&(e.value=""),document.getElementById("invoiceResult").innerHTML="",t.style.display="flex"}function y(){const t=document.getElementById("newInvoiceModalOverlay");t&&(t.style.display="none")}async function g(){const t=parseInt(document.getElementById("invoiceSaleId").value),e=document.getElementById("invoiceResult");if(t)try{const n=await a("/invoice",{method:"POST",body:JSON.stringify({sale_id:t})});e.innerHTML='Factura generada: '+(n.provisional_folio||"CFDI-"+(n.id||""))+"",r(),setTimeout((()=>y()),1500)}catch(t){e.innerHTML='Error: '+t.message+""}else e.innerHTML='Ingrese un ID de venta valido.'}function f(){alert("Nota de credito: proximamente")}return document.addEventListener("DOMContentLoaded",(function(){(e()||(window.location.href="/pos/login",0))&&(!function(){const t=document.getElementById("live-clock");if(!t)return;const e=()=>{const e=new Date;t.textContent=e.toLocaleTimeString("es-MX",{hour:"2-digit",minute:"2-digit",second:"2-digit"})};e(),setInterval(e,1e3)}(),function(){const t=document.getElementById("modalDetalleOverlay");if(!t)return;const e=t.querySelector('button[onclick*="modalDetalleOverlay"]');e&&(e.onclick=()=>{t.style.display="none"})}(),function(){const t=document.getElementById("modalCancelOverlay");if(!t)return;const e=t.querySelectorAll("div:last-child button");e.length>=2&&(e[e.length-1].onclick=()=>m(),e[e.length-2].onclick=()=>{t.style.display="none",p=null})}(),r())})),window.switchTab=o,window.showNewInvoiceModal=v,window.closeNewInvoiceModal=y,window.submitNewInvoice=g,window.notaCreditoPlaceholder=f,{switchTab:o,loadFacturas:r,loadNotas:s,loadComplementos:l,loadCancelaciones:i,showDetail:async function(t){const e=document.getElementById("modalDetalleOverlay");if(e)try{const o=await a(`/queue/${t}`),c=e.querySelector(".modal-card");if(!c)return;const r=c.querySelector("div > div:first-child > div:first-child"),s=c.querySelector("div > div:first-child > div:nth-child(2)");r&&(r.textContent="Detalle de Factura"),s&&(s.textContent=`${o.provisional_folio||"CFDI-"+o.id} — ${"stamped"===o.status?"Timbrada":"cancelled"===o.status?"Cancelada":"pending"===o.status?"Pendiente":o.status||""}`);const l=c.querySelector("div:nth-child(2)");l&&(l.innerHTML=`\nError: ${d(o.error_message)}
`:""}\n ${o.xml_signed||o.xml_unsigned?`\n${d(o.xml_signed||o.xml_unsigned)}\n `:""}`);const i=c.querySelector("div:last-child button:last-child");i&&"stamped"===o.status?(i.style.display="",i.onclick=()=>{e.style.display="none",u(t)}):i&&(i.style.display="none"),e.dataset.cfdiId=t,e.dataset.saleId=o.sale_id||"",e.style.display="flex"}catch(t){alert("Error al cargar detalle: "+t.message)}},showCancelModal:u,confirmCancel:m,processQueue:async function(){if(confirm("Procesar todos los CFDIs pendientes?"))try{const t=await a("/queue/process",{method:"POST"});alert(`Procesados: ${t.processed}, Timbrados: ${t.stamped}, Fallidos: ${t.failed}`),r()}catch(t){alert("Error: "+t.message)}},showNewInvoiceModal:v,closeNewInvoiceModal:y,submitNewInvoice:g,notaCreditoPlaceholder:f}})();