import e from"jquery";import{d as A}from"./datatables-CdFC5o1t.js";import{r as l,g as u}from"./api-DZ3cXm1m.js";import"./bootstrap.esm-Bb7dPm-H.js";import"./datatables-bbQliV7G.js";/* empty css                                  */e(document).ready(function(){const r=window.pricingConfig;let y=null,s=null,d=null,m=null;F(),e("#itemType").on("change",function(){_()}),e("#itemSearch").on("input",function(){const t=e(this).val().trim(),n=e("#itemType").val();if(t.length<2){p();return}clearTimeout(y),y=setTimeout(()=>{g(t,n)},300)}),e(document).on("click",function(t){e(t.target).closest("#itemSearch, #itemSearchResults").length||p()}),e("#fetchPricingBtn").on("click",function(){if(!s){o("warning",r.translations.selectItem);return}const t=e("#currencyId").val(),n=e("#periodType").val(),i=e("#period").val();if(!t||!n||!i){o("warning","Please select currency and period");return}v()}),e('input[name="pricing_method"]').on("change",function(){const t=e(this).val();w(t),f()}),e("#customPrice, #discountPercentage, #discountAmount, #customSetupFee").on("input",function(){f()}),e("#pricingForm").on("submit",function(t){t.preventDefault(),S()}),e("#resetFormBtn").on("click",function(){b()}),e('input[name="edit_pricing_method"]').on("change",function(){const t=e(this).val();P(t)}),e("#updatePricingBtn").on("click",function(){T()}),e(document).on("click",".delete-pricing",async function(){const t=e(this).data("id");await window.showConfirm(r.translations.confirmDelete,{title:"Onay",confirmText:"Onayla",confirmClass:"btn-danger"})&&k(t)}),e(document).on("click",".edit-pricing",function(){e(this).data("id");const t=e(this).data("pricing");C(t)});function F(){m=e("#pricingTable").DataTable({...A.getDefaultConfig(),ajax:{url:r.routes.records,type:"POST",beforeSend:function(t){t.setRequestHeader("Authorization",`Bearer ${u()}`)},error:async function(t){t.status===401&&await l()&&m.ajax.reload()}},columns:[{data:"item_type",name:"item_type"},{data:"item_name",name:"item_name"},{data:"period",name:"period"},{data:"currency",name:"currency"},{data:"standard_price",name:"standard_price"},{data:"final_price",name:"final_price"},{data:"method",name:"method",orderable:!1},{data:"status",name:"status",orderable:!1},{data:"actions",name:"actions",orderable:!1,searchable:!1,className:"text-end"}],order:[[2,"desc"]]})}async function g(t,n){try{const i=await fetch(`${r.routes.getItems}?search=${encodeURIComponent(t)}&item_type=${n}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u()}`}});if(i.status===401&&await l())return g(t,n);if(!i.ok)throw new Error("Search failed");const a=await i.json();x(a.items)}catch(i){console.error("Search error:",i),o("danger",r.translations.error)}}function x(t){const n=e("#itemSearchResults");n.empty(),t.length===0?n.append(`
                <div class="list-group-item text-muted">
                    ${r.translations.searchNoResults}
                </div>
            `):t.forEach(i=>{n.append(`
                    <a href="#" class="list-group-item list-group-item-action search-result-item"
                       data-id="${i.id}"
                       data-name="${i.name}"
                       data-type="${i.type}">
                        <strong>${i.name}</strong>
                        <br><small class="text-muted">${i.description}</small>
                    </a>
                `)}),n.show()}e(document).on("click",".search-result-item",function(t){t.preventDefault(),s={id:e(this).data("id"),name:e(this).data("name"),type:e(this).data("type")},e("#itemId").val(s.id),e("#itemSearch").val(s.name),e("#selectedItemName").text(`Selected: ${s.name}`),p()});function p(){e("#itemSearchResults").hide()}function _(){s=null,e("#itemId").val(""),e("#itemSearch").val(""),e("#selectedItemName").text(""),p()}async function v(){const t={item_type:e("#itemType").val(),item_id:s.id,currency_id:e("#currencyId").val(),period_type:e("#periodType").val(),period:e("#period").val()};try{const n=await fetch(r.routes.getCurrentPricing,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u()}`},body:JSON.stringify(t)});if(n.status===401&&await l())return v();const i=await n.json();n.ok&&i.found?(d=i,D(i),I()):(o("warning",i.error||"No pricing found"),d=null,e("#standardPricingDisplay").hide())}catch(n){console.error("Fetch pricing error:",n),o("danger",r.translations.error)}}function D(t){e("#displayItemName").text(t.item_name),e("#displayStandardPrice").text(`${t.currency_code} ${t.standard_price.toFixed(2)}`),e("#displayStandardSetup").text(`${t.currency_code} ${t.standard_setup_fee.toFixed(2)}`),e("#standardPricingDisplay").show(),f()}function I(){const n=e("#currencyId option:selected").data("symbol")||"";e("#currencySymbolPrice, #currencySymbolDiscount, #currencySymbolSetup").text(n)}function w(t){e(".pricing-method-fields").hide(),t==="override"?e("#overrideFields").show():t==="discount_percentage"?e("#discountPercentFields").show():t==="discount_fixed"&&e("#discountFixedFields").show()}function P(t){e(".edit-pricing-method-fields").hide(),t==="override"?e("#editOverrideFields").show():t==="discount_percentage"?e("#editDiscountPercentFields").show():t==="discount_fixed"&&e("#editDiscountFixedFields").show()}function f(){if(!d)return;const t=e('input[name="pricing_method"]:checked').val(),n=d.standard_price,i=d.standard_setup_fee,a=d.currency_code;let c=n,$=parseFloat(e("#customSetupFee").val())||i;if(t==="override")c=parseFloat(e("#customPrice").val())||n;else if(t==="discount_percentage"){const h=parseFloat(e("#discountPercentage").val())||0;c=n*(1-h/100)}else if(t==="discount_fixed"){const h=parseFloat(e("#discountAmount").val())||0;c=Math.max(0,n-h)}e("#finalPricePreview").text(`${a} ${c.toFixed(2)}`),e("#finalSetupPreview").text(`${a} ${$.toFixed(2)}`)}async function S(){if(!d){o("warning",r.translations.fetchFirst);return}const t={item_type:e("#itemType").val(),item_id:s.id,currency_id:e("#currencyId").val(),period_type:e("#periodType").val(),period:e("#period").val(),pricing_method:e('input[name="pricing_method"]:checked').val(),custom_price:e("#customPrice").val()||null,custom_setup_fee:e("#customSetupFee").val()||null,discount_percentage:e("#discountPercentage").val()||null,discount_amount:e("#discountAmount").val()||null,is_active:e("#isActive").is(":checked")};try{const n=await fetch(r.routes.store,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u()}`},body:JSON.stringify(t)});if(n.status===401&&await l())return S();const i=await n.json();n.ok?(o("success",r.translations.priceCreated),b(),m.ajax.reload()):o("danger",i.error||r.translations.error)}catch(n){console.error("Save pricing error:",n),o("danger",r.translations.error)}}function C(t){var a,c;e("#editPricingId").val(t.id),e("#editItemInfo").html(`
            <strong>${t.item_type}:</strong> ${t.item_name||"Unknown"} -
            ${t.period} ${t.period_type} (${((a=t.currency)==null?void 0:a.code)||""})
        `);const n=((c=t.currency)==null?void 0:c.symbol)||"";e("#editCurrencySymbolPrice, #editCurrencySymbolDiscount, #editCurrencySymbolSetup").text(n);let i="override";t.custom_price!==null?(i="override",e("#editCustomPrice").val(t.custom_price)):t.discount_percentage!==null?(i="discount_percentage",e("#editDiscountPercentage").val(t.discount_percentage)):t.discount_amount!==null&&(i="discount_fixed",e("#editDiscountAmount").val(t.discount_amount)),e(`input[name="edit_pricing_method"][value="${i}"]`).prop("checked",!0),P(i),e("#editCustomSetupFee").val(t.custom_setup_fee||""),e("#editIsActive").prop("checked",t.is_active),e("#editPricingModal").modal("show")}async function T(){const t=e("#editPricingId").val(),n={pricing_method:e('input[name="edit_pricing_method"]:checked').val(),custom_price:e("#editCustomPrice").val()||null,custom_setup_fee:e("#editCustomSetupFee").val()||null,discount_percentage:e("#editDiscountPercentage").val()||null,discount_amount:e("#editDiscountAmount").val()||null,is_active:e("#editIsActive").is(":checked")};try{const i=r.routes.update.replace(":id",t),a=await fetch(i,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u()}`},body:JSON.stringify(n)});if(a.status===401&&await l())return T();const c=await a.json();a.ok?(o("success",r.translations.priceUpdated),e("#editPricingModal").modal("hide"),m.ajax.reload()):o("danger",c.error||r.translations.error)}catch(i){console.error("Update pricing error:",i),o("danger",r.translations.error)}}async function k(t){try{const n=r.routes.destroy.replace(":id",t),i=await fetch(n,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u()}`}});if(i.status===401&&await l())return k(t);const a=await i.json();i.ok?(o("success",r.translations.priceDeleted),m.ajax.reload()):o("danger",a.error||r.translations.error)}catch(n){console.error("Delete pricing error:",n),o("danger",r.translations.error)}}function b(){e("#pricingForm")[0].reset(),_(),d=null,e("#standardPricingDisplay").hide(),w("override"),e('input[name="pricing_method"][value="override"]').prop("checked",!0)}function o(t,n){const i=`
            <div class="alert alert-${t} alert-dismissible fade show" role="alert">
                ${n}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;e(".container-fluid .alert").remove(),e(".container-fluid").prepend(i),setTimeout(()=>{e(".alert").alert("close")},5e3)}});
