import{f as g,d as f}from"./vendor-zLyX4B24.js";import"./tooltip-manager-D9RaGGY4.js";import{d as y}from"./datatables-I6jthWPb.js";import{T as S}from"./bootstrap.esm-Bb7dPm-H.js";import{g as m,r as D}from"./api-DZ3cXm1m.js";import{t as b}from"./tr-CHCA6xOE.js";import{T as k}from"./tom-select.complete.min-C5GVmztk.js";import"./datatables-Bo82YvhT.js";/* empty css                                  */const x="modulepreload",E=function(p){return"/build/"+p},w={},C=function(e,a,i){let t=Promise.resolve();if(a&&a.length>0){document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),o=(s==null?void 0:s.nonce)||(s==null?void 0:s.getAttribute("nonce"));t=Promise.allSettled(a.map(r=>{if(r=E(r),r in w)return;w[r]=!0;const d=r.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${r}"]${u}`))return;const l=document.createElement("link");if(l.rel=d?"stylesheet":x,d||(l.as="script"),l.crossOrigin="",l.href=r,o&&l.setAttribute("nonce",o),document.head.appendChild(l),d)return new Promise((c,v)=>{l.addEventListener("load",c),l.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${r}`)))})}))}function n(s){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=s,window.dispatchEvent(o),!o.defaultPrevented)throw s}return t.then(s=>{for(const o of s||[])o.status==="rejected"&&n(o.reason);return e().catch(n)})},h=document.documentElement.lang;h==="tr"&&g.localize(b.Turkish);class T{constructor(){if(this.table=document.getElementById("clients-table"),this.searchInput=document.getElementById("clients-tableSearch"),this.selectAll=document.getElementById("selectAll"),this.searchTimer=null,this.showDeleted=!1,this.bulkDeleteBtn=document.getElementById("bulkDeleteBtn"),this.bulkDeleteCount=document.getElementById("bulkDeleteCount"),this.showDeletedToggle=document.getElementById("showDeletedToggle"),this.flatpickrInstance=null,this.phoneInput=null,this.statusSelect=null,this.toggleAdvancedSearch=document.getElementById("clients-tableToggleFilters"),this.advancedSearchContainer=document.getElementById("clients-tableFilters"),this.resetAdvancedSearch=document.getElementById("resetAdvancedSearch"),this.applyAdvancedSearch=document.getElementById("applyAdvancedSearch"),this.advPhone=document.getElementById("advPhone"),this.advStatus=document.getElementById("advStatus"),this.advDateRange=document.getElementById("advDateRange"),this.advBrand=document.getElementById("advBrand"),!this.table){console.error("Clients table not found");return}this.initializePhoneInput(),this.initializeDateRangePicker(),this.initializeStatusSelect(),this.initializeDataTable(),this.initializeEventListeners()}initializePhoneInput(){this.advPhone&&(this.phoneInput=window.intlTelInput(this.advPhone,{initialCountry:"tr",preferredCountries:["tr","us","gb","de"],separateDialCode:!0,loadUtils:()=>C(()=>import("./utils-3P6Si2Fo.js"),[]),localizedCountries:{tr:h==="tr"?"Türkiye":"Turkey"},customPlaceholder:(e,a)=>h==="tr"?"Telefon Numarası":"Phone Number"}))}initializeDateRangePicker(){if(this.advDateRange){const e=new Date,a=new Date(e.getFullYear(),e.getMonth(),1),i=new Date(e.getFullYear(),e.getMonth()+1,0);this.flatpickrInstance=g(this.advDateRange,{mode:"range",dateFormat:"Y-m-d",locale:h==="tr"?b.Turkish:"default",allowInput:!0,showMonths:2,defaultHour:0,appendTo:document.body,onChange:s=>{this.handleSearch()},onReady:function(s,o,r){const d=document.createElement("div");d.className="flatpickr-predefined d-flex gap-1 mb-2",[{label:h==="tr"?"Bugün":"Today",fn:()=>{r.setDate([e,e])}},{label:h==="tr"?"Bu Hafta":"This Week",fn:()=>{const l=new Date(e);l.setDate(e.getDate()-e.getDay());const c=new Date(e);c.setDate(e.getDate()+(6-e.getDay())),r.setDate([l,c])}},{label:h==="tr"?"Bu Ay":"This Month",fn:()=>{r.setDate([a,i])}},{label:h==="tr"?"Bu Yıl":"This Year",fn:()=>{const l=new Date(e.getFullYear(),0,1),c=new Date(e.getFullYear(),11,31);r.setDate([l,c])}}].forEach(l=>{const c=document.createElement("button");c.type="button",c.className="btn btn-sm btn-outline-secondary",c.textContent=l.label,c.addEventListener("click",l.fn),d.appendChild(c)}),r.calendarContainer&&r.calendarContainer.insertBefore(d,r.calendarContainer.firstChild)}});const t=this.advDateRange.parentElement.querySelector("[data-toggle]"),n=this.advDateRange.parentElement.querySelector("[data-clear]");t&&t.addEventListener("click",()=>{this.flatpickrInstance.toggle()}),n&&n.addEventListener("click",()=>{this.flatpickrInstance.clear()})}}initializeStatusSelect(){this.advStatus&&(this.statusSelect=new k(this.advStatus,{plugins:["remove_button"],placeholder:h==="tr"?"Durum seçiniz":"Select status",allowEmptyOption:!0,render:{item:function(e,a){const i=e.value;return`<div class="d-flex align-items-center">
                                    <span class="badge bg-${{active:"success",inactive:"secondary"}[i]||"secondary"} rounded-pill me-2">
                                        ${window.translations["status_"+i]||i}
                                    </span>
                                </div>`},option:function(e,a){const i=e.value;return`<div class="d-flex align-items-center p-2">
                                    <span class="badge bg-${{active:"success",inactive:"secondary"}[i]||"secondary"} rounded-pill me-2">
                                        ${window.translations["status_"+i]||i}
                                    </span>
                                </div>`}},onChange:()=>{this.handleSearch()}}))}initializeDataTable(){const e=y.getDefaultConfig(),a={url:this.table.dataset.recordsUrl,type:"POST",data:t=>{const n={...t};if(n.search=this.searchInput.value,n.show_deleted=this.showDeleted?1:0,this.isAdvancedSearchVisible()){const s=this.flatpickrInstance?this.flatpickrInstance.selectedDates:[];n.advanced={phone:this.advPhone.value?`+${this.phoneInput.getSelectedCountryData().dialCode}${this.advPhone.value}`:"",status:this.statusSelect?this.statusSelect.getValue():[],created_start:s.length>0?f(s[0]).format("YYYY-MM-DD"):"",created_end:s.length>1?f(s[1]).format("YYYY-MM-DD"):"",brand_id:this.advBrand?this.advBrand.value:""}}return n},beforeSend:t=>{t.setRequestHeader("Authorization",`Bearer ${m()}`)},error:async(t,n,s)=>{t.status===401&&(await D()?this.dataTable.ajax.reload():(window.showAlert?showAlert("error",window.translations.messages.token_error):window.bootstrap&&window.bootstrap.Toast?new bootstrap.Toast(document.getElementById("errorToast")).show():window.showError(window.translations.messages.token_error),window.location.reload()))}},i={...e,pageLength:15,dom:'<"row"<"col-sm-12"tr>><"row align-items-center mt-2 px-3 py-2"<"col-sm-12 col-md-5 d-flex align-items-center small"l<"ms-2 text-muted"i>><"col-sm-12 col-md-7 d-flex justify-content-end"p>>',language:{...e.language,lengthMenu:'<span class="small">_MENU_</span>',processing:'<div class="spinner-border spinner-border-sm text-primary" role="status"></div>',paginate:{previous:'<i class="fas fa-chevron-left small"></i>',next:'<i class="fas fa-chevron-right small"></i>'}},ajax:{...e.ajax,...a},columns:[{data:null,orderable:!1,searchable:!1,className:"ps-4",render:(t,n,s)=>`<input type="checkbox" class="form-check-input record-checkbox" data-id="${s.id}">`},{data:"id",name:"id",className:"text-muted small",render:(t,n,s)=>{var o,r;return(r=(o=window.permissions)==null?void 0:o.clients)!=null&&r.update?`<a href="${window.routes.clients.overview.replace(":id",t)}" class="text-decoration-none text-primary fw-semibold">#${t}</a>`:`<span class="text-muted">#${t}</span>`}},{data:"full_name",name:"full_name",render:(t,n,s)=>`<div class="d-flex align-items-center">${s.type==="individual"?`<i class="fas fa-user text-primary me-2" data-bs-toggle="tooltip" title="${window.translations.type.individual}"></i>`:`<i class="fas fa-building text-info me-2" data-bs-toggle="tooltip" title="${window.translations.type.company}"></i>`}<span class="fw-medium">${t}</span></div>`},{data:"company_name",name:"company_name",render:t=>t?`<span class="text-muted">${t}</span>`:'<span class="text-muted">-</span>'},{data:"brand",name:"brand",orderable:!1,render:t=>t?`<span class="badge bg-info-subtle text-info-emphasis">${t}</span>`:'<span class="text-muted small">-</span>'},{data:"email",name:"email",render:(t,n,s)=>s.email_verified?`<span class="text-muted small">${t}</span>`:`<div class="d-flex align-items-center">
                                        <i class="fas fa-exclamation-triangle text-warning me-2" data-bs-toggle="tooltip" title="${window.translations.messages.email_not_verified}"></i>
                                        <span class="text-muted small">${t}</span>
                                    </div>`},{data:"phone",name:"phone",render:(t,n,s)=>t?s.phone_verified?`<span class="text-muted small">${t}</span>`:`<div class="d-flex align-items-center">
                                        <i class="fas fa-exclamation-triangle text-warning me-2" data-bs-toggle="tooltip" title="${window.translations.messages.phone_not_verified}"></i>
                                        <span class="text-muted small">${t}</span>
                                    </div>`:'<span class="text-muted">-</span>'},{data:"services",name:"services",className:"text-center",render:t=>this.renderServices(t)},{data:"created_at",name:"created_at",render:t=>`<span class="text-muted small">${this.formatDate(t)}</span>`},{data:"status",name:"status",className:"text-center",render:t=>this.renderStatus(t)},{data:null,orderable:!1,searchable:!1,className:"text-end pe-4",render:(t,n,s)=>{var r,d,u,l;const o=[];return(d=(r=window.permissions)==null?void 0:r.clients)!=null&&d.update&&o.push(`
                                <a href="${window.routes.clients.overview.replace(":id",s.id)}"
                                   class="btn btn-sm btn-light border d-inline-flex align-items-center justify-content-center"
                                   style="width: 32px; height: 32px;"
                                   data-bs-toggle="tooltip"
                                   title="${window.translations.buttons.edit}">
                                    <i class="fas fa-eye text-primary"></i>
                                </a>`),(l=(u=window.permissions)==null?void 0:u.clients)!=null&&l.delete&&(this.showDeleted?o.push(`
                                <button type="button"
                                        class="btn btn-sm btn-light border d-inline-flex align-items-center justify-content-center ms-1 restore-record"
                                        style="width: 32px; height: 32px;"
                                        data-id="${s.id}"
                                        data-bs-toggle="tooltip"
                                        title="${window.translations.clients.restore}">
                                    <i class="fas fa-trash-restore text-success"></i>
                                </button>`):o.push(`
                                <button type="button"
                                        class="btn btn-sm btn-light border d-inline-flex align-items-center justify-content-center ms-1 delete-record"
                                        style="width: 32px; height: 32px;"
                                        data-id="${s.id}"
                                        data-bs-toggle="tooltip"
                                        title="${window.translations.buttons.delete}">
                                    <i class="fas fa-trash text-danger"></i>
                                </button>`)),`<div class="d-inline-flex gap-1">${o.join("")}</div>`}}],order:[[1,"desc"]],drawCallback:()=>{this.initializeTooltips(),this.initializeDeleteButtons(),this.initializeRestoreButtons(),this.initializeRowCheckboxes(),this.selectAll&&(this.selectAll.checked=!1),this.updateBulkDeleteBar()}};this.dataTable=$(this.table).DataTable(i)}formatDate(e){return f(e).format("DD/MM/YYYY")}renderServices(e){var i,t,n,s,o,r,d,u;if(!e||!e.length)return"-";const a=[];if(e[0]>0){const l=((s=(n=(t=(i=window.translations)==null?void 0:i.admin)==null?void 0:t.clients)==null?void 0:n.fields)==null?void 0:s.domains)||"Domains";a.push(`
                <span class="text domains" data-bs-toggle="tooltip" data-bs-placement="top" title="${l}">
                    <i class="fas fa-globe me-1"></i>${e[0]}
                </span>
            `)}if(e[1]>0){const l=((u=(d=(r=(o=window.translations)==null?void 0:o.admin)==null?void 0:r.clients)==null?void 0:d.fields)==null?void 0:u.products)||"Products";a.push(`
                <span class="text text-services" data-bs-toggle="tooltip" data-bs-placement="top" title="${l}">
                    <i class="fas fa-server me-1"></i>${e[1]}
                </span>
            `)}return a.length>0?a.join(" "):"-"}renderStatus(e){return`<span class="badge bg-${{active:"success",inactive:"secondary",suspended:"warning",terminated:"danger",expired:"danger",transferred:"info"}[e]||"secondary"} rounded-pill">${window.translations["status_"+e]||e}</span>`}initializeEventListeners(){this.searchInput&&this.searchInput.addEventListener("keyup",()=>{clearTimeout(this.searchTimer),this.searchTimer=setTimeout(()=>{this.handleSearch()},500)}),this.selectAll.addEventListener("change",e=>this.handleSelectAll(e)),this.showDeletedToggle&&this.showDeletedToggle.addEventListener("change",e=>{this.showDeleted=e.target.checked,this.dataTable.ajax.reload()}),this.bulkDeleteBtn&&this.bulkDeleteBtn.addEventListener("click",()=>this.handleBulkDelete()),this.toggleAdvancedSearch.addEventListener("click",()=>this.toggleAdvancedSearchContainer()),this.resetAdvancedSearch.addEventListener("click",()=>this.handleAdvancedSearchReset()),this.applyAdvancedSearch.addEventListener("click",()=>this.handleSearch()),[this.advPhone,this.advDateRange].forEach(e=>{e&&e.addEventListener("keypress",a=>{a.key==="Enter"&&(a.preventDefault(),this.handleSearch())})}),[this.advStatus].forEach(e=>{e&&e.addEventListener("change",()=>this.handleSearch())})}handleSearch(){this.dataTable.ajax.reload()}handleSelectAll(e){document.querySelectorAll(".record-checkbox").forEach(i=>{i.checked=e.target.checked}),this.updateBulkDeleteBar()}getSelectedIds(){return Array.from(document.querySelectorAll(".record-checkbox:checked")).map(e=>e.dataset.id).filter(Boolean)}initializeRowCheckboxes(){document.querySelectorAll(".record-checkbox").forEach(e=>{e.addEventListener("change",()=>this.updateBulkDeleteBar())})}updateBulkDeleteBar(){if(!this.bulkDeleteBtn)return;const e=this.getSelectedIds().length;this.bulkDeleteCount&&(this.bulkDeleteCount.textContent=e),this.bulkDeleteBtn.classList.toggle("d-none",e===0||this.showDeleted)}async handleBulkDelete(){const e=this.getSelectedIds();if(e.length===0)return;const a=(window.translations.clients.confirm_bulk_delete||"").replace(":count",e.length);if(await window.showConfirm(a,{title:window.translations.clients.bulk_delete,confirmText:window.translations.clients.bulk_delete,confirmClass:"btn-danger",icon:"fas fa-trash text-danger"}))try{const t=await window.apiRequest(window.routes.clients.bulkDelete,{method:"POST",headers:{Authorization:`Bearer ${m()}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({ids:e})}),n=await t.json();t.ok?(window.showSuccess?window.showSuccess(n.message):alert(n.message),this.dataTable.ajax.reload()):window.showError?window.showError(n.error):alert(n.error)}catch(t){console.error("Bulk delete error",t)}}initializeRestoreButtons(){document.querySelectorAll(".restore-record").forEach(e=>{e.addEventListener("click",async()=>{const a=e.dataset.id;if(await window.showConfirm(window.translations.clients.confirm_restore,{title:window.translations.clients.restore,confirmText:window.translations.clients.restore,confirmClass:"btn-success",icon:"fas fa-trash-restore text-success"}))try{const t=await window.apiRequest(window.routes.clients.restore.replace(":id",a),{method:"POST",headers:{Authorization:`Bearer ${m()}`,Accept:"application/json"}}),n=await t.json();t.ok?(window.showSuccess?window.showSuccess(n.message):alert(n.message),this.dataTable.ajax.reload()):window.showError?window.showError(n.error):alert(n.error)}catch(t){console.error("Restore error",t)}})})}toggleAdvancedSearchContainer(){if(this.advancedSearchContainer){const e=this.isAdvancedSearchVisible();e?(this.advancedSearchContainer.classList.remove("show"),setTimeout(()=>{this.advancedSearchContainer.style.display="none"},300)):(this.advancedSearchContainer.style.display="block",this.advancedSearchContainer.offsetHeight,this.advancedSearchContainer.classList.add("show")),this.toggleAdvancedSearch.classList.toggle("active",!e)}}isAdvancedSearchVisible(){return this.advancedSearchContainer&&this.advancedSearchContainer.style.display!=="none"&&this.advancedSearchContainer.classList.contains("show")}handleAdvancedSearchReset(){this.phoneInput&&(this.phoneInput.setCountry("tr"),this.advPhone.value=""),this.statusSelect&&this.statusSelect.clear(),this.flatpickrInstance&&this.flatpickrInstance.clear(),this.advBrand&&(this.advBrand.value=""),this.handleSearch()}initializeTooltips(){document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(a=>{new S(a)})}initializeDeleteButtons(){document.querySelectorAll(".delete-record").forEach(e=>{e.addEventListener("click",async a=>{const i=a.currentTarget.dataset.id;await window.showConfirm(window.translations.messages.delete_confirm,{title:"Onay",confirmText:"Onayla",confirmClass:"btn-danger"})&&this.deleteRecord(i)})})}async deleteRecord(e){try{const a=await window.apiRequest(window.routes.clients.delete.replace(":id",e),{method:"DELETE",headers:{Authorization:`Bearer ${m()}`}});if(!a.ok)throw new Error("Network response was not ok");const i=await a.json();i.message&&(this.dataTable.ajax.reload(),window.showAlert?showAlert("success",i.message):window.showSuccess(i.message))}catch(a){console.error("Error:",a),window.showAlert?showAlert("error",window.translations.messages.delete_error):window.showError(window.translations.messages.delete_error)}}}document.addEventListener("DOMContentLoaded",()=>{new T});
