import{M as P}from"./bootstrap.esm-Bb7dPm-H.js";import{g as B,r as T}from"./api-DZ3cXm1m.js";document.addEventListener("DOMContentLoaded",function(){const u=window.quoteFormConfig;if(!u)return;const h=document.getElementById("itemsBody"),M=document.getElementById("addCustomItemBtn"),F=document.getElementById("addProductBtn"),w=document.getElementById("itemsJson"),O=document.getElementById("quoteForm"),R=document.getElementById("noItemsMsg");if(!h||!w||!O)return;const j=u.items||[];let ue=0;function me(){return`grp_${++ue}`}be(),function(){if(!Array.isArray(u.currencies)||!u.currencies.length)return;const t=document.getElementById("currency_id"),n=document.getElementById("currencyDisplay");t&&n&&t.value&&(n.textContent=z(t.value))}();function pe(e={}){const t=document.createElement("tr"),n=e.taxable!==void 0&&e.taxable?"checked":"",o=e.taxable!==void 0&&!e.taxable?"disabled":"",c=e.description||"",a=Math.max(1,c.split(`
`).length);return t.innerHTML=`
            <td>
                <textarea
                       class="form-control form-control-sm item-description"
                       rows="${a}"
                       placeholder="${u.translations.description}"
                       required>${q(c)}</textarea>
            </td>
            <td>
                <input type="number"
                       class="form-control form-control-sm item-quantity"
                       value="${e.quantity||1}"
                       min="1"
                       step="1"
                       required>
            </td>
            <td>
                <input type="number"
                       class="form-control form-control-sm item-unit-price"
                       value="${e.unit_price||0}"
                       step="0.01"
                       min="0"
                       required>
            </td>
            <td>
                <input type="number"
                       class="form-control form-control-sm item-discount"
                       value="${e.discount||0}"
                       step="0.01"
                       min="0"
                       max="100">
            </td>
            <td class="text-center">
                <input type="checkbox"
                       class="form-check-input item-taxable"
                       ${n}
                       ${o}>
            </td>
            <td class="item-tax-amount align-middle text-end">0.00</td>
            <td class="item-total align-middle fw-bold text-end">0.00</td>
            <td>
                <button type="button" class="btn btn-sm btn-outline-danger remove-item-btn">
                    <i class="fas fa-times"></i>
                </button>
            </td>
        `,e.type&&(t.dataset.itemType=e.type),e.product_id&&(t.dataset.productId=e.product_id),e.billing_cycle&&(t.dataset.billingCycle=e.billing_cycle),e.tax_rate!==void 0&&(t.dataset.taxRate=e.tax_rate),e.tax_method&&(t.dataset.taxMethod=e.tax_method),e.domain_name&&(t.dataset.domainName=e.domain_name),e.tld_id&&(t.dataset.tldId=e.tld_id),e.domain_action&&(t.dataset.domainAction=e.domain_action),e.registration_period&&(t.dataset.registrationPeriod=e.registration_period),e.group&&(t.dataset.group=e.group),e.require_domain&&(t.dataset.requireDomain="1"),e.preexisting&&(t.dataset.preexisting="1"),e.config_options&&e.config_options.length&&(t.dataset.configOptions=JSON.stringify(e.config_options)),t}function q(e){const t=document.createElement("div");return t.appendChild(document.createTextNode(e)),t.innerHTML}function G(e,t,n){if(!t||t<=0)return{tax:0,base:e};if(n==="inclusive"){const c=Math.round(e/(1+t/100)*100)/100;return{tax:Math.round((e-c)*100)/100,base:c}}return{tax:Math.round(e*(t/100)*100)/100,base:e}}function L(e){const t=parseFloat(e.querySelector(".item-quantity").value)||0,n=parseFloat(e.querySelector(".item-unit-price").value)||0,o=parseFloat(e.querySelector(".item-discount").value)||0,c=e.querySelector(".item-taxable").checked,a=parseFloat(e.dataset.taxRate)||0,i=e.dataset.taxMethod||"exclusive",d=t*n*(1-o/100),r=(c?G(d,a,i):{tax:0}).tax,m=i==="inclusive"?d:d+r;e.querySelector(".item-tax-amount").textContent=r.toFixed(2),e.querySelector(".item-total").textContent=m.toFixed(2)}function _(){let e=0,t=0,n=0;h.querySelectorAll("tr").forEach(l=>{const d=parseFloat(l.querySelector(".item-quantity").value)||0,s=parseFloat(l.querySelector(".item-unit-price").value)||0,r=parseFloat(l.querySelector(".item-discount").value)||0,m=l.querySelector(".item-taxable").checked,v=parseFloat(l.dataset.taxRate)||0,g=l.dataset.taxMethod||"exclusive",y=d*s*(1-r/100),b=m?G(y,v,g):{tax:0,base:y},se=b.tax,re=g==="inclusive"?b.base:y,Ce=re+se;e+=re,t+=se,n+=Ce});const c=document.getElementById("subtotalDisplay"),a=document.getElementById("taxDisplay"),i=document.getElementById("grandTotalDisplay");c&&(c.textContent=e.toFixed(2)),a&&(a.textContent=t.toFixed(2)),i&&(i.textContent=n.toFixed(2)),fe()}function fe(){if(!R)return;const e=h.querySelectorAll("tr");R.classList.toggle("d-none",e.length>0)}function C(e={}){const t=pe(e);h.appendChild(t),L(t),_(),t.querySelectorAll('input[type="text"], input[type="number"]').forEach(n=>{n.addEventListener("input",function(){L(t),_()})}),t.querySelector(".item-taxable").addEventListener("change",function(){L(t),_()}),t.querySelector(".remove-item-btn").addEventListener("click",function(){const n=t.dataset.group;n&&t.dataset.itemType==="product"?h.querySelectorAll(`tr[data-group="${n}"]`).forEach(o=>o.remove()):t.remove(),_()})}function ye(){const e=h.querySelectorAll("tr"),t=[];return e.forEach(n=>{const o={type:n.dataset.itemType||"custom",product_id:n.dataset.productId||null,billing_cycle:n.dataset.billingCycle||null,description:n.querySelector(".item-description").value,quantity:parseInt(n.querySelector(".item-quantity").value)||1,unit_price:parseFloat(n.querySelector(".item-unit-price").value)||0,discount:parseFloat(n.querySelector(".item-discount").value)||0,taxable:n.querySelector(".item-taxable").checked,tax_rate:parseFloat(n.dataset.taxRate)||0};if(n.dataset.itemType==="domain"&&(o.domain_name=n.dataset.domainName||null,o.tld_id=n.dataset.tldId||null,o.domain_action=n.dataset.domainAction||null,o.registration_period=n.dataset.registrationPeriod||null),n.dataset.itemType==="product"&&n.dataset.configOptions)try{o.config_options=JSON.parse(n.dataset.configOptions)}catch{o.config_options=[]}t.push(o)}),t}function ge(){const e=document.getElementById("clientSelect");return e?e.value:null}async function E(e){const t=ge();try{const n=await fetch(u.routes.calculateTax,{method:"POST",headers:{Authorization:`Bearer ${B()}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({client_id:t,items:e})});return n.status===401?await T()?E(e):e.map(()=>({taxable:!1,rate:0,tax_method:"exclusive"})):(await n.json()).data||e.map(()=>({taxable:!1,rate:0,tax_method:"exclusive"}))}catch(n){return console.error("Tax calculation error:",n),e.map(()=>({taxable:!1,rate:0,tax_method:"exclusive"}))}}async function Q(){const e=h.querySelectorAll("tr");if(e.length===0)return;const t=[];e.forEach(o=>{t.push({type:o.dataset.itemType||"custom",product_id:o.dataset.productId||null})});const n=await E(t);e.forEach((o,c)=>{const a=n[c]||{taxable:!1,rate:0,tax_method:"exclusive"},i=o.querySelector(".item-taxable");o.dataset.taxRate=a.rate,o.dataset.taxMethod=a.tax_method||"exclusive",i&&(i.checked=a.taxable,i.disabled=!a.taxable),L(o)}),_()}M&&M.addEventListener("click",async function(){const t=(await E([{type:"custom"}]))[0]||{taxable:!1,rate:0,tax_method:"exclusive"};C({taxable:t.taxable,tax_rate:t.rate,tax_method:t.tax_method||"exclusive"})}),F&&F.addEventListener("click",function(){xe()});let D=null;function xe(){const e=document.getElementById("productModal");if(!e)return;const t=document.getElementById("productSelect"),n=document.getElementById("billingCycleGroup"),o=document.getElementById("productPriceDisplay"),c=document.getElementById("addProductToQuoteBtn"),a=A();t&&D!==a&&U(t,a),t&&(t.value=""),n&&n.classList.add("d-none"),o&&o.classList.add("d-none"),c&&(c.disabled=!0),f=null,p=null,new P(e).show()}function A(){const e=document.getElementById("currency_id");return e?e.value:null}function z(e){const t=(u.currencies||[]).find(n=>String(n.id)===String(e));return t?t.code+(t.symbol?` (${t.symbol})`:""):"—"}function H(e){const t=document.getElementById("currency_id"),n=document.getElementById("currencyDisplay");if(!t||!e)return;const o=String(t.value)!==String(e);t.value=e,n&&(n.textContent=z(e)),o&&(D=null,Q())}let f=null,p=null;const J=document.getElementById("productSelect");J&&J.addEventListener("change",function(){const e=this.options[this.selectedIndex];if(!e||!e.value){f=null,p=null;const t=document.getElementById("billingCycleGroup"),n=document.getElementById("productPriceDisplay"),o=document.getElementById("addProductToQuoteBtn");t&&t.classList.add("d-none"),n&&n.classList.add("d-none"),o&&(o.disabled=!0);return}V({id:parseInt(e.value),name:e.textContent,requireDomain:e.dataset.requireDomain==="1"})});async function U(e,t){try{let n=`${u.routes.productRecords}?get_products_with_groups=1`;t&&(n+=`&currency_id=${encodeURIComponent(t)}`);const o=await fetch(n,{headers:{Authorization:`Bearer ${B()}`,Accept:"application/json"}});if(o.status===401)return await T()?U(e,t):void 0;const a=(await o.json()).data||[],i=e.options[0];e.innerHTML="",e.appendChild(i),a.forEach(l=>{const d=document.createElement("optgroup");d.label=l.name,l.products.forEach(s=>{const r=document.createElement("option");r.value=s.id,r.textContent=s.name,r.dataset.requireDomain=s.require_domain?"1":"0",d.appendChild(r)}),e.appendChild(d)}),D=t}catch(n){console.error("Product load error:",n)}}async function V(e){f=e,p=null;const t=document.getElementById("billingCycleGroup"),n=document.getElementById("billingCycleSelect"),o=document.getElementById("productPriceDisplay");document.getElementById("productPriceText");const c=document.getElementById("addProductToQuoteBtn");if(!t||!n)return;o&&o.classList.add("d-none"),c&&(c.disabled=!0);const a=document.getElementById("productConfigOptions");a&&a.classList.add("d-none");try{const i=A(),l=await fetch(`${u.routes.productPricing}?product_id=${e.id}${i?"&currency_id="+i:""}`,{headers:{Authorization:`Bearer ${B()}`,Accept:"application/json"}});if(l.status===401)return await T()?V(e):void 0;const s=(await l.json()).data||[];if(s.length===0){t.classList.add("d-none"),p={price:0,cycle:null},c&&(c.disabled=!1);return}n.innerHTML="",s.forEach(r=>{const m=r.cycle||r.period||"",v=r.cycle_label||r.period||m,g=r.price!==void 0?r.price:r.amount!==void 0?r.amount:0,x=document.createElement("option");x.value=m,x.textContent=`${v} - ${parseFloat(g).toFixed(2)}`,x.dataset.price=g,x.dataset.setupAmount=r.setup_amount||0,n.appendChild(x)}),t.classList.remove("d-none"),s.length>0&&(n.selectedIndex=0,Y())}catch(i){console.error("Product pricing error:",i)}}const W=document.getElementById("billingCycleSelect");W&&W.addEventListener("change",Y);function Y(){const e=document.getElementById("billingCycleSelect"),t=document.getElementById("productPriceDisplay"),n=document.getElementById("productPriceText");if(document.getElementById("addProductToQuoteBtn"),!e)return;const o=e.options[e.selectedIndex];if(!o)return;const c=parseFloat(o.dataset.price)||0;p={price:c,cycle:o.value},t&&n&&(n.textContent=c.toFixed(2),t.classList.remove("d-none")),he(),N()}let K=0;async function he(){const e=document.getElementById("productConfigOptions"),t=document.getElementById("productConfigOptionsBody");if(!e||!t||!f||!p)return;const n=++K;t.innerHTML="",e.classList.add("d-none");const o=parseInt(p.cycle),c=A();if(!(!o||!c))try{const a=`${u.routes.productConfigOptions}?product_id=${f.id}&currency_id=${encodeURIComponent(c)}&period=${o}`;let i=await fetch(a,{headers:{Authorization:`Bearer ${B()}`,Accept:"application/json"}});if(i.status===401){const s=await T();if(!s)return;i=await fetch(a,{headers:{Authorization:`Bearer ${s}`,Accept:"application/json"}})}const l=await i.json();if(n!==K)return;const d=l.data||[];Ie(d,t),d.length>0&&e.classList.remove("d-none")}catch(a){console.error("Config options load error:",a)}}function Ie(e,t){e.forEach(n=>{const o=document.createElement("div");o.className="mb-2";const c=document.createElement("div");c.className="small text-muted fw-bold mb-1",c.textContent=n.name||"",o.appendChild(c),n.options.forEach(a=>{const i=document.createElement("div");i.className="mb-2 config-option",i.dataset.optionId=a.id,i.dataset.optionType=a.type,i.dataset.required=a.is_required?"1":"0",i.dataset.optionName=a.name;const l=document.createElement("label");if(l.className="form-label small mb-1",l.innerHTML=q(a.name)+(a.is_required?' <span class="text-danger">*</span>':""),i.appendChild(l),a.type==="select"){const d=document.createElement("select");if(d.className="form-select form-select-sm config-option-input",!a.is_required){const s=document.createElement("option");s.value="",s.textContent=u.translations.config_option_select_placeholder||"Select...",d.appendChild(s)}(a.config_values||[]).forEach((s,r)=>{const m=document.createElement("option");m.value=s.id,m.dataset.price=s.pricing.price,m.dataset.valueName=s.value,m.dataset.valueId=s.id,m.textContent=`${s.value} (+${parseFloat(s.pricing.price).toFixed(2)})`,a.is_required&&r===0&&(m.selected=!0),d.appendChild(m)}),d.addEventListener("change",N),i.appendChild(d)}else a.type==="checkboxgroup"&&(a.config_values||[]).forEach(d=>{const s=document.createElement("div");s.className="form-check";const r=document.createElement("input");r.type="checkbox",r.className="form-check-input config-option-input",r.value=d.id,r.dataset.price=d.pricing.price,r.dataset.valueName=d.value,r.dataset.valueId=d.id,r.addEventListener("change",N);const m=document.createElement("label");m.className="form-check-label small",m.textContent=`${d.value} (+${parseFloat(d.pricing.price).toFixed(2)})`,s.appendChild(r),s.appendChild(m),i.appendChild(s)});o.appendChild(i)}),t.appendChild(o)})}function X(){const e=document.getElementById("productConfigOptionsBody");if(!e)return!0;let t=!0;return e.querySelectorAll(".config-option").forEach(n=>{if(n.dataset.required==="1")if(n.dataset.optionType==="select"){const o=n.querySelector("select");(!o||!o.value)&&(t=!1)}else n.dataset.optionType==="checkboxgroup"&&(n.querySelector('input[type="checkbox"]:checked')||(t=!1))}),t}function N(){const e=document.getElementById("addProductToQuoteBtn");e&&(e.disabled=!(f&&p&&X()))}function ve(){const e=document.getElementById("productConfigOptionsBody"),t=[];return e&&e.querySelectorAll(".config-option").forEach(n=>{const o=parseInt(n.dataset.optionId)||null,c=n.dataset.optionName||"";if(n.dataset.optionType==="select"){const a=n.querySelector("select");if(a&&a.value){const i=a.options[a.selectedIndex];t.push({option_id:o,value_id:parseInt(i.dataset.valueId)||null,optionName:c,valueName:i.dataset.valueName,price:parseFloat(i.dataset.price)||0})}}else n.dataset.optionType==="checkboxgroup"&&n.querySelectorAll('input[type="checkbox"]:checked').forEach(a=>{t.push({option_id:o,value_id:parseInt(a.dataset.valueId)||null,optionName:c,valueName:a.dataset.valueName,price:parseFloat(a.dataset.price)||0})})}),t}const Z=document.getElementById("addProductToQuoteBtn");Z&&Z.addEventListener("click",async function(){if(!f||!p||!X())return;const e=me(),t=ve(),n=t.reduce((d,s)=>d+(s.price||0),0),o=p.price+n;let c=f.name+(p.cycle?` (${p.cycle})`:"");t.length>0&&(c+=`
`+t.map(d=>`${d.optionName}: ${d.valueName}`).join(`
`));const i=(await E([{type:"product",product_id:f.id}]))[0]||{taxable:!1,rate:0,tax_method:"exclusive"};C({type:"product",product_id:f.id,billing_cycle:p.cycle,description:c,quantity:1,unit_price:o,discount:0,taxable:i.taxable,tax_rate:i.rate,tax_method:i.tax_method||"exclusive",group:e,require_domain:!!f.requireDomain,config_options:t.map(d=>({option_id:d.option_id,value_id:d.value_id,value_name:d.valueName,price:d.price}))});const l=document.getElementById("productModal");if(l){const d=P.getInstance(l);d&&d.hide()}f.requireDomain&&(k=e,setTimeout(()=>ne(),300))});const ee=document.getElementById("addDomainBtn");ee&&ee.addEventListener("click",function(){ne()});let I=null,k=null,S=null,te=null;function ne(){const e=document.getElementById("domainModal");if(!e)return;const t=document.getElementById("domainNameInput"),n=document.getElementById("domainActionSelect"),o=document.getElementById("domainPeriodGroup"),c=document.getElementById("domainPriceDisplay"),a=document.getElementById("domainNoPricing"),i=document.getElementById("domainResolvedTldGroup"),l=document.getElementById("addDomainToQuoteBtn");t&&(t.value=""),n&&(n.selectedIndex=0),o&&o.classList.add("d-none"),c&&c.classList.add("d-none"),a&&a.classList.add("d-none"),i&&i.classList.add("d-none"),l&&(l.disabled=!0),S=null,I=null,new P(e).show()}const oe=document.getElementById("domainNameInput"),ae=document.getElementById("domainActionSelect");oe&&oe.addEventListener("input",function(){clearTimeout(te),te=setTimeout(ce,400)}),ae&&ae.addEventListener("change",ce);async function ce(){const e=document.getElementById("domainNameInput"),t=document.getElementById("domainActionSelect"),n=document.getElementById("domainPeriodGroup"),o=document.getElementById("domainPeriodSelect"),c=document.getElementById("domainPriceDisplay"),a=document.getElementById("domainNoPricing"),i=document.getElementById("domainResolvedTldGroup"),l=document.getElementById("domainResolvedTld"),d=document.getElementById("addDomainToQuoteBtn"),s=((e==null?void 0:e.value)||"").trim().toLowerCase(),r=t?t.value:"register";if(S=null,I=null,n&&n.classList.add("d-none"),c&&c.classList.add("d-none"),i&&i.classList.add("d-none"),a&&a.classList.add("d-none"),d&&(d.disabled=!0),!(!s||s.indexOf(".")===-1))try{const m=`${u.routes.domainPricing}?domain=${encodeURIComponent(s)}&action=${r}`;let v=await fetch(m,{headers:{Authorization:`Bearer ${B()}`,Accept:"application/json"}});if(v.status===401){const y=await T();if(!y)return;v=await fetch(m,{headers:{Authorization:`Bearer ${y}`,Accept:"application/json"}})}const g=await v.json();if(!g.matched){a&&a.classList.remove("d-none");return}S=g.tld_id,l&&(l.textContent=g.tld),i&&i.classList.remove("d-none");const x=g.data||[];o&&(o.innerHTML="",x.forEach(y=>{const b=document.createElement("option");b.value=y.period,b.textContent=`${y.period} ${y.period===1?"Year":"Years"} - ${y.amount_formatted}`,b.dataset.price=y.price,o.appendChild(b)})),n&&n.classList.remove("d-none"),x.length>0&&o&&(o.selectedIndex=0,de())}catch(m){console.error("Domain resolve error:",m)}}const ie=document.getElementById("domainPeriodSelect");ie&&ie.addEventListener("change",de);function de(){const e=document.getElementById("domainPeriodSelect"),t=document.getElementById("domainPriceDisplay"),n=document.getElementById("domainPriceText"),o=document.getElementById("addDomainToQuoteBtn");if(!e)return;const c=e.options[e.selectedIndex];if(!c)return;const a=parseFloat(c.dataset.price)||0,i=parseInt(c.value)||1;I={price:a,period:i},t&&n&&(n.textContent=a.toFixed(2),t.classList.remove("d-none")),o&&(o.disabled=!1)}const le=document.getElementById("addDomainToQuoteBtn");le&&le.addEventListener("click",async function(){const e=document.getElementById("domainNameInput"),t=document.getElementById("domainActionSelect");if(!S||!I)return;const n=e?e.value.trim():"",o=t?t.value:"register",c=t?t.options[t.selectedIndex].textContent:"Register",a=`${n} (${c} - ${I.period}yr)`,l=(await E([{type:"domain"}]))[0]||{taxable:!1,rate:0,tax_method:"exclusive"};C({type:"domain",domain_name:n,tld_id:S,domain_action:o,registration_period:I.period,description:a,quantity:1,unit_price:I.price,discount:0,taxable:l.taxable,tax_rate:l.rate,tax_method:l.tax_method||"exclusive",group:k||null}),k=null;const d=document.getElementById("domainModal");if(d){const s=P.getInstance(d);s&&s.hide()}}),O.addEventListener("submit",function(e){var o;const t=ye();if(t.length===0){e.preventDefault(),alert(u.translations.items_required||"At least one item is required");return}const n=Array.from(h.querySelectorAll("tr"));for(const c of n){if(c.dataset.itemType!=="product"||c.dataset.requireDomain!=="1"||c.dataset.preexisting==="1")continue;const a=c.dataset.group;if(!(a&&n.some(l=>l.dataset.itemType==="domain"&&l.dataset.group===a))){e.preventDefault();const l=(((o=c.querySelector(".item-description"))==null?void 0:o.value)||"").replace(/\s*\(.*\)\s*$/,""),d=u.translations.domain_required_for_product||"A domain is required for ':product'";alert(d.replace(":product",l));return}}w.value=JSON.stringify(t)});function be(){document.getElementById("clientSelect")&&Ee()}function Ee(){const e=$("#clientSelect");if(!e.length)return;const t={placeholder:u.translations.select_client||u.translations.search_client||"Select a client...",allowClear:!0,ajax:{url:u.routes.clientSearch,dataType:"json",delay:250,headers:{Authorization:`Bearer ${B()}`,Accept:"application/json"},data:function(n){return{q:n.term}},processResults:function(n){return{results:n.results.map(function(o){return{id:o.id,text:o.text,name:o.name||o.text.split(" (")[0],email:o.email||(o.text.match(/\((.*?)\)/)||[])[1],currency_id:o.currency_id}})}},cache:!0},templateResult:Be,templateSelection:_e,minimumInputLength:2};if(u.clientId&&(t.minimumInputLength=0),e.select2(t),e.on("change",function(){const n=e.select2("data"),o=n&&n[0];o&&o.currency_id?H(o.currency_id):Q()}),u.clientId&&u.clientName){const n=new Option(u.clientName,u.clientId,!0,!0);e.append(n).trigger("change"),u.clientCurrencyId&&H(u.clientCurrencyId)}}function Be(e){if(e.loading)return e.text;const t=e.name||e.text.split(" (")[0]||"",n=e.email||(e.text.match(/\((.*?)\)/)||[])[1]||"",o=document.createElement("div");return o.className="select2-client-result",o.innerHTML=`
            <div class="select2-client-name">${q(t)}</div>
            <div class="select2-client-email text-muted small">${q(n)}</div>
        `,$(o)}function _e(e){const t=e.name||$(e.element).data("name")||e.text.split(" (")[0]||"",n=e.email||$(e.element).data("email")||(e.text.match(/\((.*?)\)/)||[])[1]||"";return t+(n?` (${n})`:"")}j.length>0?j.forEach(e=>C({...e,preexisting:!0})):(async()=>{const t=(await E([{type:"custom"}]))[0]||{taxable:!1,rate:0,tax_method:"exclusive"};C({taxable:t.taxable,tax_rate:t.rate,tax_method:t.tax_method||"exclusive"})})()});
