PageSourceSearch

https://www.findeks.com/src/js/SaleModule.DazYV_51.js

js findeks.com collected 2026-10-01 12:37:00 UTC 76,470 bytes, 1 lines download raw bytes

1import{a as e,A as t}from"./appService.CRk85P-N.js";import{I as a}from"./vendor.DuxOljS7.js";class i{constructor(e){this.apiClient=e,this.currentStep=null,this.stepData=null,this.init()}init(){this.loadStepData(),this.setupEventListeners()}loadStepData(){const e=document.getElementById("sale-step-data");if(e)try{this.stepData=JSON.parse(e.textContent),this.currentStep=this.stepData.currentStep}catch(t){}}setupEventListeners(){document.addEventListener("submit",async e=>{const t=e.target;if(t.hasAttribute("data-step")){if("PhoneVerification"===t.getAttribute("data-step"))return;e.preventDefault(),await this.handleStepSubmit(t)}}),window.addEventListener("popstate",e=>{})}async handleStepSubmit(e){const t=e.getAttribute("data-step");if(await this.validateStep(t,e))try{const a=await this.submitStep(t,e);a.success&&a.data?.nextStepUrl?window.location.href=a.data.nextStepUrl:a.success}catch(a){}finally{this.setLoadingState(e,!1)}}async validateStep(e,t){const a=new CustomEvent("sale:validate-step",{detail:{stepName:e,form:t},cancelable:!0});return document.dispatchEvent(a)}async submitStep(t,a){const i=this.extractFormData(t,a),s=this.getApiEndpoint(t);return await e.post(s,i,{showErrorModal:!0})}extractFormData(e,t){const a=new CustomEvent("sale:extract-form-data",{detail:{stepName:e,form:t,formData:null},cancelable:!1});return document.dispatchEvent(a),null!==a.detail.formData?a.detail.formData:this.extractDefaultFormData(t)}extractDefaultFormData(e){const t=new FormData(e),a={};for(const[i,s]of t.entries())a[i]=s;return a}getApiEndpoint(e){return{CardVerification:"/satis/kart-dogrulama",PhoneVerification:"/satis/otp-dogrulama",PackageSelection:"/satis/paket-secimi",Payment:"/satis/odeme",Confirmation:"/satis/onay"}[e]||"/satis/api/unknown"}setLoadingState(e,t){const a=e.querySelector('button[type="submit"]');if(a)if(t){a.disabled=!0;const e=a.querySelector("span");e&&(e.dataset.originalText=e.textContent)}else{a.disabled=!1;const e=a.querySelector("span");e&&e.dataset.originalText&&(e.textContent=e.dataset.originalText)}}updateProgress(e){document.querySelectorAll("[data-step]").forEach(t=>{t.getAttribute("data-step")===e&&(t.setAttribute("data-status","Completed"),this.updateStepStyle(t,"Completed"))})}updateStepStyle(e,t){const a=e.querySelector("span"),i=e.querySelector("div");a&&i&&(a.classList.remove("text-greenPrimary","text-bluePrimary","text-grayPrimary"),i.classList.remove("bg-greenPrimary","bg-bluePrimary","bg-grayPrimary"),"Completed"===t?(a.classList.add("text-greenPrimary"),i.classList.add("bg-greenPrimary")):"Active"===t?(a.classList.add("text-bluePrimary"),i.classList.add("bg-bluePrimary")):(a.classList.add("text-grayPrimary"),i.classList.add("bg-grayPrimary")))}getCurrentStep(){return this.currentStep}getStepData(){return this.stepData}}class s{constructor(){this.errorClass="error"}showFieldError(e,t){const a=this.getFormGroup(e);if(!a)return;a.classList.add(this.errorClass);const i=a.querySelector("p");i&&t&&(i.textContent=t,i.classList.remove("hidden"))}clearFieldError(e){const t=this.getFormGroup(e);if(!t)return;t.classList.remove(this.errorClass);const a=t.querySelector("p");a&&a.classList.add("hidden")}showDropdownError(e,t){if(!e)return;e.classList.add(this.errorClass);const a=e.querySelector("p");a&&t&&(a.textContent=t,a.classList.remove("hidden"))}clearDropdownError(e){if(!e)return;e.classList.remove(this.errorClass);const t=e.querySelector("p");t&&t.classList.add("hidden")}clearAllErrors(e){e.querySelectorAll(".form-group").forEach(e=>{e.classList.remove(this.errorClass);const t=e.querySelector("p");t&&t.classList.add("hidden")}),e.querySelectorAll(".custom-select-container").forEach(e=>{e.classList.remove(this.errorClass);const t=e.querySelector("p");t&&t.classList.add("hidden")})}applyValidationResults(e,t){this.clearAllErrors(e);for(const[a,i]of Object.entries(t)){if("cityCode"===a||"districtCode"===a){const t="cityCode"===a?"city":"district",s=e.querySelector(`[data-address-type="${t}"]`);i.isValid?this.clearDropdownError(s):this.showDropdownError(s,i.message);continue}const t=e.elements[a];
1t&&(i.isValid?this.clearFieldError(t):this.showFieldError(t,i.message))}}getFormGroup(e){return e?.closest(".form-group")}setButtonLoading(e,t){e&&(t?(e.disabled=!0,e.setAttribute("aria-busy","true"),e.dataset.originalContent||(e.dataset.originalContent=e.innerHTML),e.innerHTML='\n                <svg class="animate-spin h-5 w-5 mx-auto" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">\n                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>\n                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>\n                </svg>\n            '):(e.disabled=!1,e.removeAttribute("aria-busy"),e.dataset.originalContent&&(e.innerHTML=e.dataset.originalContent,delete e.dataset.originalContent)))}toggleLoadingSpinner(e){let t=document.getElementById("loading-spinner");e&&!t?(t=this.createLoadingSpinner(),document.body.appendChild(t)):!e&&t&&t.remove()}createLoadingSpinner(){const e=document.createElement("div");return e.id="loading-spinner",e.className="fixed inset-0 bg-black/50 flex items-center justify-center z-[9999]",e.innerHTML='\n            <div class="bg-white rounded-lg p-6 flex flex-col items-center gap-4">\n                <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-bluePrimary"></div>\n                <p class="text-base">İşleniyor...</p>\n            </div>\n        ',e}}const r="Geçerli bir T.C. Kimlik Numarası giriniz.",n="Geçerli bir cep telefonu numarası giriniz.",o="Geçerli bir e-posta adresi giriniz.",l="Geçerli bir doğum tarihi giriniz.",d="18 yaşını doldurmuş olmanız gerekmektedir.",c="Geçerli bir güvenlik kodu giriniz.",u=e=>null==e||("string"==typeof e?0===e.trim().length:Array.isArray(e)?0===e.length:"object"==typeof e&&0===Object.keys(e).length),h=e=>e?e.replace(/\D/g,"").slice(0,11):"",m=e=>11===h(e).length,p=e=>{const t=e.replace(/\D/g,"");return 8===t.length&&/^\d{8}$/.test(t)},E=e=>{const t=e.replace(/\D/g,"");return 4===t.length&&/^\d{4}$/.test(t)};class g{validateField(e,t){switch(e){case"tcKimlikNo":return(e=>{const t=h(e),a=11===t.length&&(e=>{if(!/^[1-9][0-9]{10}$/.test(e))return!1;const t=e.split("").map(e=>parseInt(e,10));return(7*(t[0]+t[2]+t[4]+t[6]+t[8])-(t[1]+t[3]+t[5]+t[7]))%10===t[9]&&t.slice(0,10).reduce((e,t)=>e+t,0)%10===t[10]})(t);return{isValid:a,message:a?"":r}})(t);case"cepTelefonu":return(e=>{const t=(e=>e?e.replace(/\D/g,"").slice(0,11):"")(e),a=e&&11===t.length&&/^05\d{9}$/.test(t)&&!/^0?(\d)\1+$/.test(t);return{isValid:a,message:a?"":n}})(t);case"email":return(e=>{if(!e||0===e.trim().length)return{isValid:!1,message:o};const t=e.trim();return t.length>254||1!==(t.match(/@/g)||[]).length?{isValid:!1,message:o}:/^[a-zA-Z0-9._-]{1,64}@[a-zA-Z0-9.-]{1,253}\.[a-zA-Z]{2,}(\.[a-zA-Z]{2,})*$/.test(t)?{isValid:!0,message:""}:{isValid:!1,message:o}})(t);case"birthDate":return(e=>{if(!e)return{isValid:!1,message:l};const t=(e=>e?e.toString().trim().replace(/[.\- ]/g,"/"):"")(e);if(!/^\d{2}\/\d{2}\/\d{4}$/.test(t))return{isValid:!1,message:l};const[a,i,s]=t.split("/"),r=parseInt(a,10),n=parseInt(i,10),o=parseInt(s,10);if(n<1||n>12||r<1||r>31||o<1900)return{isValid:!1,message:l};const c=new Date(o,n-1,r);if(c.getFullYear()!==o||c.getMonth()!==n-1||c.getDate()!==r)return{isValid:!1,message:l};const u=new Date;let h=u.getFullYear()-o;const m=u.getMonth()-(n-1),p=u.getDate()-r;return(m<0||0===m&&p<0)&&h--,h<18?{isValid:!1,message:d}:h>100?{isValid:!1,message:l}:{isValid:!0,message:""}})(t);case"kvkk":return((e,t=null)=>{const a=!0===e||"true"===e||"on"===e;return{isValid:a,message:a?"":t||"Bu alanı onaylamanız gerekmektedir"}})(t);case"captcha":return(e=>{const t=4===e.length;return{isValid:t,message:t?"":c}})(t);default:return{isValid:!0}}}validateAll(e){const t={};let a=!0;const i=this.validateField("tcKimlikNo",e.tcKimlikNo);t.tcKimlikNo=i,i.isValid||(a=!1);const s=this.validateField("cepTelefonu",e.cepTelefonu);t.cepTelefonu=s,s.isValid||(a=!1);const r=this.validateField("email",e.email);t.email=r,r.isValid||(a=!1);const n=this.validateField("captcha",e.captcha);t.captcha=n,n.isValid||(a=!1);const o=this.validateField("birthDate",e.birthDate);t.birthDate=o,o.isValid||(a=!1);const l=this.validateField("kvkk",e.kvkk);return t.kvkk=l,l.isValid||(a=!1),{isValid:a,fieldResults:t}}extractFormData(e){new FormData(e);const t={};return t.tcKimlikNo=e.elements.tcKimlikNo?.value||"",t.cepTelefonu=e.elements.cepTelefonu?.value||"",t.birthDate=e.elements.birthDate?.value||"",t.email=e.elements.email?.value||"",t.packageCode=e.elements.packageCode?.value||"",t.packageName=e.elements.packageName?.value||"",t.packagePrice=e.elements.packagePrice?.value||"",t.captcha=e.elements.captcha?.value||"",t.kvkk=e.elements.kvkk?.checked||!1,t}}class y{constructor(e){this.apiClient=e,this.globalModalController=null,this.uiHandler=new s,this.contractTypeMapping={kvkk:"3",preContract:"2",serviceAgreement:"1"},this.init()}init(){this.globalModalController=window.modalController,this.globalModalController&&(this.setupContentModalTriggers(),this.setupModalCloseHandlers(),this.setupCheckboxPdfHandlers())}setupContentModalTriggers(){window.__contentModalTriggerAdded||(document.addEventListener("click",async e=>{const t=e.target.closest("button[data-contract-modal]");if(t){const a=t.closest("label"),i=t.getAttribute("data-contract-modal");if(a&&"kvkk"!==i)return e.preventDefault(),e.stopPropagation(),void e.stopImmediatePropagation();e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();const s=t.getAttribute("data-modal-target");await this.loadAndShowContract(i,s)}},!0),window.__contentModalTriggerAdded=!0)}setupModalCloseHandlers(){const e=document.querySelectorAll("[data-contract-modal]"),t=new Set;
1e.forEach(e=>{const a=e.getAttribute("data-modal-target");a&&t.add(a)}),t.forEach(e=>{const t=document.getElementById(e);if(!t)return;const a=t.querySelector(".modal-close");a&&a.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),this.closeModal(t)},!0),t.querySelectorAll('.modal-action-btn, button[data-action="close"]').forEach(e=>{e.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),this.closeModal(t)},!0)}),t.addEventListener("click",e=>{e.target===t&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),this.closeModal(t))},!0)})}setupCheckboxPdfHandlers(){if(window.__checkboxPdfHandlersAdded)return;const e=document.getElementById("preContractInfo");e&&e.addEventListener("change",async e=>{if(e.target.checked){if(!this.validateAddressDetail())return void(e.target.checked=!1);await this.downloadContractPdf("preContract","Sozlesme_Oncesi_Bilgi_Formu")}});const t=document.getElementById("serviceAgreement");t&&t.addEventListener("change",async e=>{if(e.target.checked){if(!this.validateAddressDetail())return void(e.target.checked=!1);await this.downloadContractPdf("serviceAgreement","Hizmet_Sozlesmesi")}}),window.__checkboxPdfHandlersAdded=!0}validateAddressDetail(){const e=document.getElementById("billingAddress");if(!e)return!0;const t=e.value?.trim();return this.uiHandler.clearFieldError(e),t?t.length<10?(this.showAddressDetailError(e,"Lütfen geçerli bir fatura adresi giriniz (10-512 karakter arası)."),e.focus(),!1):!(t.length>512&&(this.showAddressDetailError(e,"Fatura adresi en fazla 512 karakter olabilir."),e.focus(),1)):(this.showAddressDetailError(e,"Lütfen geçerli bir fatura adresi giriniz (10-512 karakter arası).."),e.focus(),!1)}showAddressDetailError(e,t="Lütfen geçerli bir fatura adresi giriniz (10-512 karakter arası)."){this.uiHandler.showFieldError(e,t)}async downloadContractPdf(e,t){try{const a=await this.fetchContractContent(e);if(a&&a.contractContentPdf)await this.downloadPdfFromBase64(a.contractContentPdf,t);else{const t="preContract"===e?"sozlesme-bilgi-formu-modal":"hizmet-sozlesmesi-modal";await this.loadAndShowContract(e,t)}}catch(a){const t="preContract"===e?"sozlesme-bilgi-formu-modal":"hizmet-sozlesmesi-modal";await this.loadAndShowContract(e,t)}}async downloadPdfFromBase64(e,t){try{if(!e||"string"!=typeof e)throw new Error("Geçersiz PDF içeriği: Base64 string bulunamadı");const i=e.replace(/\s/g,"").replace(/\n/g,"").replace(/\r/g,"").replace(/\t/g,"").trim();if(!i||0===i.length)throw new Error("Base64 string boş veya geçersiz");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(i))throw new Error("Base64 string geçersiz karakterler içeriyor");const s=window.atob(i),r=new Uint8Array(s.length);for(let e=0;e<s.length;e++)r[e]=s.charCodeAt(e);const n=new Blob([r],{type:"application/pdf"}),o=`${t}.pdf`,l=navigator.userAgent,d=/iPhone|iPod/i.test(l),c=/iPad/i.test(l)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1||/Macintosh/i.test(l)&&navigator.maxTouchPoints>1;if(d||c){const e=new File([n],o,{type:"application/pdf"});if(navigator.share&&navigator.canShare&&navigator.canShare({files:[e]}))try{await navigator.share({files:[e],title:o})}catch(a){"AbortError"!==a.name&&this.fallbackDownload(n,o)}else this.fallbackDownload(n,o)}else this.fallbackDownload(n,o);return!0}catch(i){throw i}}fallbackDownload(e,t){const a=window.URL.createObjectURL(e),i=document.createElement("a");i.href=a,i.download=t,i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(()=>{window.URL.revokeObjectURL(a)},6e4)}async loadAndShowContract(e,t){const a=document.getElementById(t);if(a){this.showLoadingState(a);try{const t=await this.fetchContractContent(e);t?(this.globalModalController.open(a),this.updateModalContent(a,t)):this.showErrorState(a,"İçerik yüklenemedi")}catch(i){this.showErrorState(a,"İçerik yüklenirken bir hata oluştu. Lütfen tekrar deneyiniz.")}}}async fetchContractContent(t){const a=this.contractTypeMapping[t];if(!a)return null;const i="kvkk"===t?"/uye/sozlesme-formu":"/satis/sozlesme-formu",s={ContractType:a};if("kvkk"!==t){const e=this.getAddressData();e&&(s.BillingAddress=e.billingAddress,s.CityCode=e.cityCode,s.DistrictCode=e.districtCode)}const r=await e.post(i,s,{showErrorModal:!0});return r.success&&r.data?r.data:null}getAddressData(){const e=document.getElementById("cityCode"),t=document.getElementById("districtCode"),a=document.getElementById("billingAddress");return e&&t&&a?{cityCode:e.value,districtCode:t.value,billingAddress:a.value?.trim()}:null}updateModalContent(e,t){const a=e.querySelector("h3"),i=e.querySelector(".overflow-auto");a&&t.title&&(a.textContent=t.title),i&&t.content&&(i.innerHTML=t.content,i.classList.remove("opacity-50"),i.scrollTop=0)}showLoadingState(e){const t=e.querySelector(".overflow-auto");t&&(t.innerHTML='\n                <div class="flex items-center justify-center py-12">\n                    <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-bluePrimary"></div>\n                </div>\n            ',t.classList.add("opacity-50"))}showErrorState(e,t){const a=e.querySelector("h3"),i=e.querySelector(".overflow-auto");a&&(a.textContent="Hata"),i&&(i.innerHTML=`\n                <div class="flex flex-col items-center justify-center py-12 text-center">\n                    <svg class="w-16 h-16 text-redPrimary mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">\n                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>\n                    </svg>\n                    <p class="text-gray-600">${t}</p>\n                </div>\n            `,i.classList.remove("opacity-50"))}closeModal(e){this.globalModalController.close(e)}destroy(){}}function v(){const e=navigator.userAgent.toLowerCase();return/iphone|ipad|ipod/.test(e)}class f{static pushEcommerceEvent(e,t){try{const a=this.getListNameFromUrl(),i=document.referrer||window.location.href,s={item_id:t.id,item_name:t.name,price:t.price,quantity:t.quantity||1,item_category:t.category||"Bireysel",item_category2:t.category2||(t.name&&t.name.toLowerCase().includes("paket")?"Paket":"Ürün"),item_list_name:a,previous_page:i};t.category4&&(s.item_category4=t.category4);const r={event:e,ecommerce:{currencyCode:"TRY",items:[s]}};window.dataLayer=window.dataLayer||[],window.dataLayer.push(r)}catch(a){}}static pushPaymentEvent(e,t){try{const a=this.getListNameFromUrl(),i=document.referrer||window.location.href,s={event:e,ecommerce:{currencyCode:"TRY",items:[{item_id:t.id,item_name:t.name,price:t.price,quantity:t.quantity||1,item_category:t.category||"Bireysel",item_category2:t.category2||(t.name&&t.name.toLowerCase().includes("paket")?"Paket":"Ürün"),item_list_name:a,payment_type:t.paymentType||"Kredi Kartı",previous_page:i}]}};window.dataLayer=window.dataLayer||[],window.dataLayer.push(s)}catch(a){}}static getListNameFromUrl(){if("undefined"==typeof window)return"Anasayfa";const e=window.location.pathname.toLowerCase();return"/"===e||e.includes("/anasayfa")?"Commercial"===this.getCookie("HeaderType")||e.includes("ticari")?"Ticari Anasayfa":"Bireysel Anasayfa":e.includes("/ticari")?e.includes("paketler")?"Ticari Paketler":"Ticari Anasayfa":e.includes("/urunler")||e.includes("/bireysel-urunler")||e.includes("/ticari-urunler")?e.includes("/bireysel-urunler")?"Bireysel Ürünler":e.includes("/ticari-urunler")||"Commercial"===this.getCookie("HeaderType")?"Ticari Ürünler":"Bireysel Ürünler":e.includes("/bireysel-paketler")?"Bireysel Paketler":e.includes("/ticari-paketler")?"Ticari Paketler":e.includes("/hesaplama-araclari")||e.includes("/kira-artis-orani")||e.includes("/kmh-hesaplama")||e.includes("/kredi-karti-asgari-odeme")||e.includes("/kredi-hesaplama")?"Hesaplama Araçları":e.includes("/kampanyalar")||e.includes("/kampanya/")?"Kampanyalar":e.includes("/findeksakademi")?"Findeks Akademi":e.includes("/kurumsal-hizmetler")||e.includes("/cek-kayit-sistemi")||e.includes("/finansal-saglik-hizmetleri")?"Kurumsal Hizmetler":"Anasayfa"}static getCookie(e){if("undefined"==typeof document)return"";const t=`; ${document.cookie}`.split(`; ${e}=`);return 2===t.length?t.pop().split(";").shift():""}}class S{static ELEMENT_IDS={FORM:"sale-info-form",MODAL:"sale-modal",CAPTCHA_IMG:"captcha-img",CAPTCHA_INPUT:"captcha",CAPTCHA_REFRESH_BTN:"captcha-refresh-btn",PACKAGE_PRICE:"packagePrice",PACKAGE_CODE:"packageCode",PACKAGE_NAME:"packageName",SELECTED_PACKAGE_PRICE:"selected-package-price",SELECTED_PACKAGE_NAME:"selected-package-name",SUBMIT_BTN:"info-submit-btn",MEMBERSHIP_MODAL:"uye-ol-modal"};
1static SELECTORS={MODAL_HEADER_TITLE:".checkout-modal-header__title",MODAL_CONTENT:".modal-content",FORM_GROUP:".form-group",INPUT_TEXT_TEL:'input[type="text"], input[type="tel"]',INPUT_TEXT_TEL_EMAIL_DATE:'input[type="text"], input[type="tel"], input[type="email"], input[type="date"]',INPUT_CHECKBOX:'input[type="checkbox"]',INPUT_ALL:"input",DATA_ACTION_CLOSE:'[data-action="close"]'};static API_ENDPOINTS={CAPTCHA_CREATE:"/captcha/create",MEMBERSHIP_CHECK:"/uye/uyelik-kontrol",PACKAGE_PRICE:"/uye/paket-fiyat"};static ERROR_MESSAGES={RELOAD_PAGE:"Lütfen sayfayı yenileyin.",TRY_AGAIN:"Lütfen tekrar deneyin.",RELOAD_AND_TRY_AGAIN:"Lütfen sayfayı yenileyin ve tekrar deneyin.",CAPTCHA_NOT_LOADED:"Güvenlik doğrulaması yapılamadı.",PRICE_NOT_LOADED:"Ürün fiyat bilgisi alınamadı.",PURCHASE_CANNOT_START:"Satın alma işlemi başlatılamadı.",ENTER_SECURITY_CODE:"Lütfen güvenlik kodunu giriniz.",PRICE_INFO_NOT_RECEIVED:"Fiyat bilgisi alınamadı.",PRICE_INFO_INVALID:"Fiyat bilgisi geçersiz.",PRODUCT_INFO_MISSING:"Ürün bilgisi eksik.",SERVER_RESPONSE_NOT_RECEIVED:"Sunucu yanıtı alınamadı.",OPERATION_FAILED:"İşlem başarısız oldu. Lütfen bilgilerinizi kontrol edip tekrar deneyin.",REDIRECT_INFO_NOT_RECEIVED:"Yönlendirme bilgisi alınamadı.",UNEXPECTED_ERROR:"Beklenmeyen bir hata oluştu.",SECURITY_CODE_REFRESH_FAILED:"Güvenlik kodu yenilenemedi.",MEMBERSHIP_MODAL_NOT_FOUND:"Üye olma modalı bulunamadı"};static MODAL_TITLES={RISK_REPORT:"Risk Raporu Al",CREDIT_SCORE:"Kredi Notunu Öğren"};static ATTRIBUTES={MAX_LENGTH:"maxlength",ORIGINAL_TEXT:"originalText",MEMBERSHIP_MODAL_LISTENER_ADDED:"membershipModalListenerAdded",IS_CLOSING:"isClosing"};static CSS_CLASSES={ERROR:"error",BORDER_RED_PRIMARY:"border-redPrimary",BORDER_RED_500:"border-red-500",ANIMATE_PULSE:"animate-pulse",OPACITY_0:"opacity-0",OPACITY_100:"opacity-100",INVISIBLE:"invisible",SCALE_95:"scale-95",SCALE_100:"scale-100"};static FIELD_NAMES={TC_KIMLIK_NO:"tcKimlikNo",CEP_TELEFONU:"cepTelefonu",BIRTH_DATE:"birthDate",EMAIL:"email",KVKK:"kvkk"};static KEYWORDS={RISK_REPORT:"risk raporu",CREDIT_SCORE:"kredi notu"};static LIMITS={CAPTCHA_MAX_LENGTH:4,EMAIL_MAX_LENGTH:64,CHAR_CODE_CONTROL_KEY:31};static REGEX={DIGIT:/^\d$/,NON_DIGIT:/\D/g,EMAIL_ALLOWED_CHARS:/^[a-zA-Z0-9@._-]$/,EMAIL_CLEAN:/[^a-zA-Z0-9@._-]/g};constructor(e,t,a,i){this.apiClient=e,this.productId=t,this.productName=a,this.category=i,this.validator=new g,this.uiHandler=new s,this.contentModalHandler=new y(e),this.form=null,this.modal=null,this.packageCode=null,this.packageName=null,this.modalOpenClass="checkout-modal--open",this.submitHandler=null,this.isCaptchaReady=!1,this.isPriceReady=!1,this.isModalOpenAllowed=!1,this.isSubmitting=!1,this.modalSettledClass="checkout-modal--settled",this.iosBodyClass="ios-device",this.scrollPosition=0,this.listeners=[],this.init()}
1async init(){if(this.form=document.getElementById(S.ELEMENT_IDS.FORM),this.modal=document.getElementById(S.ELEMENT_IDS.MODAL),!this.form||!this.modal)return;this.updateModalTitle(),this.setupValidation(),this.setupSubmitHandler();const t=this.modal.querySelector(S.SELECTORS.DATA_ACTION_CLOSE);t&&t.addEventListener("click",e=>{this.removeSubmitHandler(),this.destroy(),e.preventDefault(),this.modal.classList.remove(this.modalSettledClass),setTimeout(()=>{this.modal.classList.remove(this.modalOpenClass),v()&&(document.body.classList.remove(this.iosBodyClass),document.body.style.top="",window.scrollTo(0,this.scrollPosition),this.scrollPosition=0),document.dispatchEvent(new CustomEvent("checkout-modal:closed",{detail:{modalId:this.modal.id}}))},10)}),this.clearFormBeforeOpen(),await this.setupCaptchaWithValidation(),this.updateSelectedPackage(this.productName);const a=await this.fetchAndDisplayPrice(this.productId);if(this.isCaptchaReady&&this.isPriceReady&&a)this.isModalOpenAllowed=!0,this.openModal(this.productId,this.productName);else{this.isModalOpenAllowed=!1;let t=`${S.ERROR_MESSAGES.PURCHASE_CANNOT_START} `;this.isCaptchaReady||(t+=`${S.ERROR_MESSAGES.CAPTCHA_NOT_LOADED} `),this.isPriceReady||(t+=`${S.ERROR_MESSAGES.PRICE_NOT_LOADED} `),t+=S.ERROR_MESSAGES.RELOAD_AND_TRY_AGAIN,e.showError(t)}}updateModalTitle(){const e=this.modal.querySelector(S.SELECTORS.MODAL_HEADER_TITLE);e&&(this.productName&&this.productName.toLowerCase().includes(S.KEYWORDS.RISK_REPORT)?e.textContent=S.MODAL_TITLES.RISK_REPORT:(this.productName&&this.productName.toLowerCase().includes(S.KEYWORDS.CREDIT_SCORE),e.textContent=S.MODAL_TITLES.CREDIT_SCORE))}async fetchAndDisplayPrice(e){const t=document.getElementById(S.ELEMENT_IDS.SELECTED_PACKAGE_PRICE),a=document.getElementById(S.ELEMENT_IDS.PACKAGE_PRICE);if(!t||!e)return this.isPriceReady=!1,!1;try{t.textContent="Yükleniyor...",t.classList.add(S.CSS_CLASSES.ANIMATE_PULSE);const i=await fetch(`${S.API_ENDPOINTS.PACKAGE_PRICE}/${e}`);if(!i.ok)throw new Error(`HTTP Error: ${i.status}`);const s=await i.json();if(s.isSuccess&&s.data&&s.data.price){const e=`${s.data.price.toFixed()} TL`;return t.textContent=e,a&&(a.value=s.data.price),this.isPriceReady=!0,!0}return t.textContent="Fiyat bilgisi alınamadı",this.isPriceReady=!1,!1}catch(i){return t.textContent="Fiyat alınamadı",this.isPriceReady=!1,!1}finally{t.classList.remove(S.CSS_CLASSES.ANIMATE_PULSE)}}openModal(e,t){this.packageCode=e,this.packageName=t;const a=this.form.querySelector(`#${S.ELEMENT_IDS.PACKAGE_CODE}`);a&&(a.value=e);const i=this.form.querySelector(`#${S.ELEMENT_IDS.PACKAGE_NAME}`);i&&(i.value=t),this.sendBeginCheckoutEvent(),v()&&(this.scrollPosition=window.pageYOffset||document.documentElement.scrollTop,document.body.style.top=`-${this.scrollPosition}px`,document.body.classList.add(this.iosBodyClass)),this.modal.classList.add(this.modalOpenClass),setTimeout(()=>{this.modal.classList.add(this.modalSettledClass),v()?(this.modal.offsetHeight,setTimeout(()=>{this.focusFirstInput(this.modal)},150)):this.focusFirstInput(this.modal)},300),window.modalController?window.modalController.open(this.modal):(this.modal.classList.remove(S.CSS_CLASSES.OPACITY_0,S.CSS_CLASSES.INVISIBLE),this.modal.querySelector(S.SELECTORS.MODAL_CONTENT).classList.remove(S.CSS_CLASSES.SCALE_95),document.body.style.overflow="hidden")}focusFirstInput(e){const t=e.querySelectorAll('input:not([type="hidden"]):not([disabled]), textarea:not([disabled])');if(t.length>0){const e=t[0];e.focus(),v()&&setTimeout(()=>{e.scrollIntoView({behavior:"smooth",block:"center"})},100)}}updateSelectedPackage(e){e&&(document.getElementById(S.ELEMENT_IDS.SELECTED_PACKAGE_NAME).textContent=e)}sendBeginCheckoutEvent(){try{const e=document.getElementById(S.ELEMENT_IDS.PACKAGE_PRICE),t=e&&e.value||"0";let a="Bireysel";"Ticari"===this.category&&(a="Ticari"),f.pushEcommerceEvent("begin_checkout",{id:this.packageCode,name:this.productName,price:parseFloat(t)+" TL",category:a})}catch(e){}}closeModal(){window.modalController?window.modalController.close(this.modal):(this.modal.classList.add(S.CSS_CLASSES.OPACITY_0,S.CSS_CLASSES.INVISIBLE),this.modal.querySelector(S.SELECTORS.MODAL_CONTENT).classList.add(S.CSS_CLASSES.SCALE_95),document.body.style.overflow="",this.onModalClose())}onModalClose(){this.removeSubmitHandler(),this.clearAllErrors(),this.packageCode=null}setupValidation(){[S.FIELD_NAMES.TC_KIMLIK_NO,S.FIELD_NAMES.CEP_TELEFONU,S.FIELD_NAMES.BIRTH_DATE,S.FIELD_NAMES.EMAIL].forEac
1h(e=>{const t=this.form.elements[e];if(!t)return;if(e===S.FIELD_NAMES.TC_KIMLIK_NO){const e=e=>{const t=e.which||e.keyCode,a=String.fromCharCode(t);return!(!S.REGEX.DIGIT.test(a)&&t>S.LIMITS.CHAR_CODE_CONTROL_KEY&&(e.preventDefault(),1))};t.addEventListener("keypress",e),this.listeners.push({element:t,event:"keypress",handler:e});const a=e=>{const a=e.target.value,i=a.replace(S.REGEX.NON_DIGIT,"");a!==i&&(e.target.value=i),this.uiHandler.clearFieldError(t)};t.addEventListener("input",a),this.listeners.push({element:t,event:"input",handler:a})}else if(e===S.FIELD_NAMES.EMAIL){const e=e=>{const t=e.which||e.keyCode,a=String.fromCharCode(t);return e.target.value.length>=S.LIMITS.EMAIL_MAX_LENGTH&&t>S.LIMITS.CHAR_CODE_CONTROL_KEY?(e.preventDefault(),!1):!(!S.REGEX.EMAIL_ALLOWED_CHARS.test(a)&&t>S.LIMITS.CHAR_CODE_CONTROL_KEY&&(e.preventDefault(),1))};t.addEventListener("keypress",e),this.listeners.push({element:t,event:"keypress",handler:e});const a=e=>{const a=e.target.value;a.length>S.LIMITS.EMAIL_MAX_LENGTH&&(e.target.value=a.substring(0,S.LIMITS.EMAIL_MAX_LENGTH));const i=e.target.value.replace(S.REGEX.EMAIL_CLEAN,"");e.target.value!==i&&(e.target.value=i),this.uiHandler.clearFieldError(t)};t.addEventListener("input",a),this.listeners.push({element:t,event:"input",handler:a})}else{const e=()=>{this.uiHandler.clearFieldError(t)};t.addEventListener("input",e),this.listeners.push({element:t,event:"input",handler:e})}const a=()=>{this.validateField(e,t)};t.addEventListener("blur",a),this.listeners.push({element:t,event:"blur",handler:a})});const e=this.form.elements[S.FIELD_NAMES.KVKK];if(e){const t=()=>{this.uiHandler.clearFieldError(e)};e.addEventListener("change",t),this.listeners.push({element:e,event:"change",handler:t})}}validateField(e,t){const a=t.value,i=this.validator.validateField(e,a);return i.isValid?this.uiHandler.clearFieldError(t):this.uiHandler.showFieldError(t,i.message),i.isValid}setupSubmitHandler(){this.submitHandler=async e=>{e.preventDefault(),await this.handleSubmit()},this.form.addEventListener("submit",this.submitHandler)}async handleSubmit(){if(this.isSubmitting)return;if(!this.validateForm())return;const t=document.getElementById(S.ELEMENT_IDS.CAPTCHA_INPUT);if(!t||!t.value.trim())return void e.showError(S.ERROR_MESSAGES.ENTER_SECURITY_CODE);const a=document.getElementById(S.ELEMENT_IDS.PACKAGE_PRICE);if(!a||null===a.value||void 0===a.value||""===a.value)return void e.showError(`${S.ERROR_MESSAGES.PRICE_INFO_NOT_RECEIVED} ${S.ERROR_MESSAGES.RELOAD_PAGE}`);const i=parseFloat(a.value);if(isNaN(i)||i<0)e.showError(`${S.ERROR_MESSAGES.PRICE_INFO_INVALID} ${S.ERROR_MESSAGES.RELOAD_PAGE}`);else if(this.packageCode&&this.packageName){this.isSubmitting=!0,this.setLoadingState(!0);try{const i=this.validator.extractFormData(this.form);i.packageCode=this.packageCode,i.packageName=this.packageName,i.captchaCode=t.value.trim();const s=parseFloat(a.value);i.packagePrice=`${s.toLocaleString("tr-TR",{minimumFractionDigits:0,maximumFractionDigits:0})} TL`,i.returnUrl=window.location.pathname||"/";const r=await e.post(S.API_ENDPOINTS.MEMBERSHIP_CHECK,i,{showErrorModal:!1});if(!r||void 0===r.success)return await this.fetchCaptcha(),t.value="",void e.showError(`${S.ERROR_MESSAGES.SERVER_RESPONSE_NOT_RECEIVED} ${S.ERROR_MESSAGES.TRY_AGAIN}`);if(!0!==r.success){if(this.isUserNotMember(r))return void(await this.showMembershipModal());await this.fetchCaptcha(),t.value="",t.focus();const a=r.message||r.error||S.ERROR_MESSAGES.OPERATION_FAILED;return void e.showError(a)}if(!r.data||!r.data.nextStepUrl)return await this.fetchCaptcha(),t.value="",t.focus(),void e.showError(`${S.ERROR_MESSAGES.REDIRECT_INFO_NOT_RECEIVED} ${S.ERROR_MESSAGES.TRY_AGAIN}`);this.closeModal(),window.location.href=r.data.nextStepUrl}catch(s){await this.fetchCaptcha(),t.value="",t.focus();const a=s.message||`${S.ERROR_MESSAGES.UNEXPECTED_ERROR} ${S.ERROR_MESSAGES.TRY_AGAIN}`;e.showError(a)}finally{this.isSubmitting=!1,this.setLoadingState(!1)}}else e.showError(`${S.ERROR_MESSAGES.PRODUCT_INFO_MISSING} ${S.ERROR_MESSAGES.RELOAD_PAGE}`)}validateForm(){const e=this.validator.extractFormData(this.form),t=this.validator.validateAll(e);return this.uiHandler.applyValidationResults(this.form,t.fieldResults),t.isValid}setLoadingState(e){const t=this.form.querySelector(`#${S.ELEMENT_IDS.SUBMIT_BTN}`);if(t)if(e){t.disabled=!0;const e=t.querySelector("span");e&&(e.dataset[S.ATTRIBUTES.ORIGINAL_TEXT]=e.textContent)}else{t.disabled=!1;const e=t.querySelector("span");e&&e.dataset[S.ATTRIBUTES.ORIGINAL_TEXT]&&(e.textContent=e.dataset[S.ATTRIBUTES.ORIGINAL_TEXT])}}clearAllErrors(){this.form&&(this.form.querySelectorAll(S.SELECTORS.FORM_GROUP).forEach(e
1=>{e.classList.remove(S.CSS_CLASSES.ERROR)}),this.form.querySelectorAll(S.SELECTORS.INPUT_ALL).forEach(e=>{e.classList.remove(S.CSS_CLASSES.BORDER_RED_PRIMARY,S.CSS_CLASSES.BORDER_RED_500,S.CSS_CLASSES.ERROR),this.uiHandler&&this.uiHandler.clearFieldError(e)}))}clearFormBeforeOpen(){this.form&&(this.form.reset(),this.form.querySelectorAll(S.SELECTORS.INPUT_TEXT_TEL).forEach(e=>{e.value=""}),this.form.querySelectorAll(S.SELECTORS.INPUT_CHECKBOX).forEach(e=>{e.checked=!1})),this.clearAllErrors()}async fetchCaptcha(){try{const t=await e.post(S.API_ENDPOINTS.CAPTCHA_CREATE,{},{showErrorModal:!0}),a=document.getElementById(S.ELEMENT_IDS.CAPTCHA_IMG);return a&&(a.src=t.data),!0}catch(t){return!1}}async setupCaptchaWithValidation(){const t=document.getElementById(S.ELEMENT_IDS.CAPTCHA_IMG),a=document.getElementById(S.ELEMENT_IDS.CAPTCHA_INPUT),i=document.getElementById(S.ELEMENT_IDS.CAPTCHA_REFRESH_BTN);if(t&&a)try{const s=await e.post(S.API_ENDPOINTS.CAPTCHA_CREATE,{},{showErrorModal:!0});if(t.src=s.data,a.value="",i){const s=async()=>{try{const i=await e.post(S.API_ENDPOINTS.CAPTCHA_CREATE,{},{showErrorModal:!0});t.src=i.data,a.value=""}catch(i){e.showError(`${S.ERROR_MESSAGES.SECURITY_CODE_REFRESH_FAILED} ${S.ERROR_MESSAGES.TRY_AGAIN}`)}};i.addEventListener("click",s),this.listeners.push({element:i,event:"click",handler:s})}a.setAttribute(S.ATTRIBUTES.MAX_LENGTH,String(S.LIMITS.CAPTCHA_MAX_LENGTH));const r=e=>{e.target.value.length>S.LIMITS.CAPTCHA_MAX_LENGTH&&(e.target.value=e.target.value.slice(0,S.LIMITS.CAPTCHA_MAX_LENGTH))};a.addEventListener("input",r),this.listeners.push({element:a,event:"input",handler:r}),this.isCaptchaReady=!0}catch(s){this.isCaptchaReady=!1}else this.isCaptchaReady=!1}isUserNotMember(e){const t=(e.message||e.error||"").toLowerCase(),a=t.includes("üye")||t.includes("uye")||t.includes("üyelik")||t.includes("uyelik")||t.includes("kayıt olun")||t.includes("kayit olun"),i=!0===e.isNotMember||!0===e.notMember;return a||i}async showMembershipModal(){const e=document.getElementById(S.ELEMENT_IDS.MEMBERSHIP_MODAL);if(!e)return;this.setLoadingState(!1);if(e.dataset[S.ATTRIBUTES.MEMBERSHIP_MODAL_LISTENER_ADDED]||(e.addEventListener("modal:close",async t=>{t.detail&&t.detail.modal&&t.detail.modal.id===S.ELEMENT_IDS.MEMBERSHIP_MODAL&&(await this.handleMembershipModalClose(),delete e.dataset[S.ATTRIBUTES.MEMBERSHIP_MODAL_LISTENER_ADDED])}),e.dataset[S.ATTRIBUTES.MEMBERSHIP_MODAL_LISTENER_ADDED]="true"),window.modalController)window.modalController.open(e);else{e.classList.remove(S.CSS_CLASSES.OPACITY_0,S.CSS_CLASSES.INVISIBLE),e.classList.add(S.CSS_CLASSES.OPACITY_100);const t=e.querySelector(S.SELECTORS.MODAL_CONTENT);t&&(t.classList.remove(S.CSS_CLASSES.SCALE_95),t.classList.add(S.CSS_CLASSES.SCALE_100))}}async handleMembershipModalClose(){const e=document.getElementById(S.ELEMENT_IDS.MEMBERSHIP_MODAL);if(e&&"true"!==e.dataset[S.ATTRIBUTES.IS_CLOSING]){e.dataset[S.ATTRIBUTES.IS_CLOSING]="true";try{if(this.form){this.form.reset(),this.form.querySelectorAll(S.SELECTORS.INPUT_TEXT_TEL_EMAIL_DATE).forEach(e=>{e.value=""}),this.form.querySelectorAll(S.SELECTORS.INPUT_CHECKBOX).forEach(e=>{e.checked=!1});const e=this.form.querySelector(`#${S.ELEMENT_IDS.PACKAGE_CODE}`);e&&(e.value="")}this.clearAllErrors();const e=document.getElementById(S.ELEMENT_IDS.CAPTCHA_INPUT);await this.fetchCaptcha(),e&&(e.value="")}finally{setTimeout(()=>{delete e.dataset[S.ATTRIBUTES.IS_CLOSING]},500)}}}removeSubmitHandler(){this.submitHandler&&(this.form.removeEventListener("submit",this.submitHandler),this.submitHandler=null)}destroy(){this.contentModalHandler&&this.contentModalHandler.destroy(),this.removeSubmitHandler(),this.listeners.forEach(({element:e,event:t,handler:a})=>{e&&a&&e.removeEventListener(t,a)}),this.listeners=[]}}class C{constructor(){this.rules=new Map,this.errorMessages=new Map,this.initializeRules()}initializeRules(){}addRule(e,t,a){this.rules.set(e,t),this.errorMessages.set(e,a)}validateField(e,t,a=null){const i=this.rules.get(e);if(!i)return{isValid:!0,message:""};const s=i(t,a);return{isValid:s,message:s?"":this.errorMessages.get(e)}}validateAll(e){const t={};let a=!0;for(const[i,s]of Object.entries(e)){if("elements"===i)continue;const r=e.elements?.[i],n=this.validateField(i,s,r);t[i]=n,n.isValid||(a=!1)}return{isValid:a,fieldResults:t}}extractFormData(e){const t=new FormData(e),a={elements:{}};for(const[i,s]of t.entries())a[i]=s,a.elements[i]=e.elements[i];return a}}class k extends C{initializeRules(){this.addRule("firstEightDigit",p,"Kartınızın ilk 8 hanesini doğru şekilde giriniz"),this.addRule("lastFourDigits",E,"Kartınızın son 4 hanesini doğru şekilde giriniz"),this.addRule("tcKimlikNo",m,"Geçerli bir T.C. Kimlik Numarası giriniz")}}class w{constructor(e){this.apiClient=e,this.validator=new k,this.uiHandler=new s,this.form=null,this.init()}init(){this.form=document.getElementById("card-verify-form"),this.form&&(this.setupValidation(),this.setupSubmitHandler())}setupValidation(){["firstEightDigit","lastFourDigits","tcKimlikNo"].forEach(e
1=>{const t=this.form.elements[e];t&&(t.addEventListener("input",e=>{e.target.value=e.target.value.replace(/\D/g,"");const a=t.getAttribute("maxlength");a&&e.target.value.length>parseInt(a)&&(e.target.value=e.target.value.slice(0,parseInt(a))),this.uiHandler.clearFieldError(t)}),t.addEventListener("blur",()=>{this.validateField(e,t)}))})}validateField(e,t){const a=t.value,i=this.validator.validateField(e,a,t);return i.isValid?this.uiHandler.clearFieldError(t):this.uiHandler.showFieldError(t,i.message),i.isValid}setupSubmitHandler(){document.addEventListener("sale:validate-step",e=>{"CardVerification"===e.detail.stepName&&(this.validateForm()||e.preventDefault())}),document.addEventListener("sale:extract-form-data",e=>{if("CardVerification"===e.detail.stepName){const t=this.validator.extractFormData(this.form);e.detail.formData=t}})}validateForm(){const e=this.validator.extractFormData(this.form),t=this.validator.validateAll(e);return this.uiHandler.applyValidationResults(this.form,t.fieldResults),t.isValid}destroy(){}}class A{constructor(e){this.apiClient=e,this.uiHandler=new s,this.form=null,this.otpInputs=[],this.timerInterval=null,this.remainingTime=120,this.isSubmitting=!1,this.init()}init(){this.form=document.getElementById("phone-verify-form"),this.form&&(this.loadOtpDataFromSession(),this.setupOtpInputs(),this.setupTimer(),this.setupResendButton(),this.setupSubmitHandler(),this.startTimer(),this.sendAddToCartEvent())}sendAddToCartEvent(){try{const e=document.getElementById("package-code")?.value,t=document.getElementById("package-name")?.value,a=document.getElementById("package-price")?.value,i=document.getElementById("sales-category")?.value||"Bireysel";if(!e)return;const s=parseFloat(a||"0");f.pushEcommerceEvent("add_to_cart",{id:e,name:t,price:s+" TL",category:i})}catch(e){}}loadOtpDataFromSession(){const e=document.getElementById("otp-validity-duration");if(e){const t=parseInt(e.value,10);this.remainingTime=isNaN(t)?180:t}else this.remainingTime=120}updateMaskedPhone(e){const t=document.getElementById("masked-phone-display");t&&e&&(t.textContent=e)}setupOtpInputs(){this.otpInputs=document.querySelectorAll(".otp-input"),this.otpInputs.forEach((e,t)=>{e.addEventListener("paste",e=>{const t=(e.clipboardData||window.clipboardData).getData("text").replace(/\D/g,"").slice(0,6);t&&(e.preventDefault(),this.fillOtp(t))}),e.addEventListener("focus",e=>{e.target.select()}),e.addEventListener("input",a=>{const i=a.target.value;if(/^\d*$/.test(i)){if(i.length>1){if(2===i.length){const e=a.data&&/\d/.test(a.data)?a.data:i.slice(-1);return a.target.value=e,void(t<this.otpInputs.length-1?this.otpInputs[t+1].focus():this.otpInputs[t].blur())}const s=i.split("");let r=t;s.forEach((e,t)=>{/\d/.test(e)&&r<this.otpInputs.length&&(this.otpInputs[r].value=e,r++)}),this.otpInputs[t].value.length>1&&(this.otpInputs[t].value=this.otpInputs[t].value.substring(0,1));const n=Math.min(r,this.otpInputs.length-1),o=r>=this.otpInputs.length;return void requestAnimationFrame(()=>{e.blur(),o?this.otpInputs[this.otpInputs.length-1].blur():this.otpInputs[n].focus()})}1===i.length&&(t<this.otpInputs.length-1?this.otpInputs[t+1].focus():this.otpInputs[t].blur())}else a.target.value=i.replace(/\D/g,"")}),e.addEventListener("keydown",e=>{"Backspace"!==e.key||e.target.value||t>0&&this.otpInputs[t-1].focus()})}),this.otpInputs&&this.otpInputs.length>0&&this.otpInputs[0]&&setTimeout(()=>{this.otpInputs[0]&&"function"==typeof this.otpInputs[0].focus&&this.otpInputs[0].focus()},100)}fillOtp(e){const t=e.replace(/\D/g,"").slice(0,6).split("");this.otpInputs.forEach((e,a)=>{t[a]&&(e.value=t[a])});let a=t.length;a<this.otpInputs.length?this.otpInputs[a].focus():this.otpInputs[this.otpInputs.length-1].blur()}setupTimer(){this.timerElement=document.getElementById("otp-timer")}startTimer(){this.updateTimerDisplay(),this.timerInterval=setInterval(()=>{this.remainingTime--,this.updateTimerDisplay(),this.remainingTime<=0&&(this.stopTimer(),this.enableResendButton())},1e3)}stopTimer(){this.timerInterval&&(clearInterval(this.timerInterval),this.timerInterval=null)}
1updateTimerDisplay(){if(!this.timerElement)return;const e=Math.floor(this.remainingTime/60),t=this.remainingTime%60;this.timerElement.textContent=`${String(e).padStart(2,"0")}:${String(t).padStart(2,"0")}`}setupResendButton(){this.resendButton=document.getElementById("resend-sms-btn"),this.resendButton&&this.resendButton.addEventListener("click",async()=>{await this.resendOtp()})}enableResendButton(){this.resendButton&&(this.resendButton.disabled=!1)}async resendOtp(){this.uiHandler.toggleLoadingSpinner(!0);try{const t=await e.post("/satis/otp-gonder",{},{showErrorModal:!0});t.success&&(this.clearOtpInputs(),this.resendButton.disabled=!0,this.remainingTime=t.data.timeout||120,t.data?.maskedPhone&&this.updateMaskedPhone(t.data.maskedPhone),this.startTimer())}catch(t){}finally{this.uiHandler.toggleLoadingSpinner(!1)}}setupSubmitHandler(){document.addEventListener("sale:validate-step",e=>{"PhoneVerification"===e.detail.stepName&&(this.validateForm()||e.preventDefault())}),document.addEventListener("sale:extract-form-data",e=>{if("PhoneVerification"===e.detail.stepName){const t=this.getOtpCode();e.detail.formData={OtpCode:t}}}),this.form.addEventListener("submit",async e=>{if(e.preventDefault(),!this.isSubmitting&&this.validateForm()){this.isSubmitting=!0;try{const e=this.getOtpCode(),t=await this.apiClient.post("/satis/otp-dogrulama",{OtpCode:e},{showErrorModal:!0});t.success&&t.data?.nextStepUrl?window.location.href=t.data.nextStepUrl:(t.success,this.clearOtpInputsOnError())}catch(t){this.clearOtpInputsOnError()}finally{this.isSubmitting=!1}}})}validateForm(){if(!(()=>{const e=this.getOtpCode().replace(/\D/g,"");return 6===e.length&&/^\d{6}$/.test(e)})()){const e=this.form.querySelector("#otp-container"),t=e?.closest(".form-group");return t&&t.classList.add("error"),!1}return!0}getOtpCode(){let e="";for(let t=0;t<this.otpInputs.length;t++)e+=this.otpInputs[t].value;return e}clearOtpInputs(){this.otpInputs.forEach(e=>{e.value=""}),this.otpInputs.length>0&&this.otpInputs[0]&&this.otpInputs[0].focus()}clearOtpInputsOnError(){this.otpInputs.forEach(e=>{e.value="",e.classList.add("border-redPrimary"),setTimeout(()=>{e.classList.remove("border-redPrimary")},2e3)});const e=this.form.querySelector("#otp-container"),t=e?.closest(".form-group");t&&(t.classList.add("error"),setTimeout(()=>{t.classList.remove("error")},2e3)),this.otpInputs.length>0&&this.otpInputs[0].focus()}destroy(){this.stopTimer()}}class I{constructor(e){this.apiClient=e,this.uiHandler=new s,this.form=null,this.packages=[],this.init()}init(){this.form=document.getElementById("product-selection-form"),this.form&&(this.loadPackages(),this.setupSubmitHandler())}async loadPackages(){try{const e=await this.apiClient.post("/satis/paket-listesi",{});if(e.success&&e.data){const t=document.getElementById("package-list-container");t&&(t.innerHTML=e.data,this.setupProductSelection(),this.setInitialSummary())}else window.appService&&"function"==typeof window.appService.showError&&window.appService.showError(e.message||"Paket listesi alınamadı.")}catch(e){window.appService&&"function"==typeof window.appService.showError&&window.appService.showError("Paket listesi yüklenirken bir hata oluştu.")}}setInitialSummary(){const e=this.form.querySelector('input[name="product"]:checked');if(e){const t=parseFloat(e.dataset.price)||0,a=e.nextElementSibling?.textContent||"";this.updateSummary(a.trim(),t)}}setupProductSelection(){this.form.querySelectorAll('input[name="product"]').forEach(e=>{e.addEventListener("change",e=>{const t=parseFloat(e.target.dataset.price)||0,a=e.target.nextElementSibling?.textContent||"";this.updateSummary(a.trim(),t),this.uiHandler.clearFieldError(e.target)})})}updateSummary(e,t){const a=document.getElementById("summary-package-name"),i=document.getElementById("summary-package-price");a&&(a.textContent=e),i&&(i.textContent=`${t.toFixed()} TL`)}setupSubmitHandler(){document.addEventListener("sale:validate-step",e=>{"PackageSelection"===e.detail.stepName&&(this.validateForm()||e.preventDefault())}),document.addEventListener("sale:extract-form-data",e=>{if("PackageSelection"===e.detail.stepName){const t=this.form.querySelector('input[name="product"]:checked');e.detail.formData={PackageCode:t?t.value:null,ProductId:t?parseInt(t.dataset.productId):0}}})}validateForm(){const e=null!==this.form.querySelector('input[name="product"]:checked');return e||this.form.querySelectorAll('input[name="product"]').forEach(e
1=>{const t=e.closest(".form-group");t&&t.classList.add("error")}),e}destroy(){}}class L extends C{cleanMaskValue(e){return e?e.replace(/[_\s/]/g,""):""}validateField(e,t){switch(e){case"CreditCardNo":case"creditCardNo":return this.validateCreditCardNo(t);case"NameOnCard":case"nameOnCard":return this.validateNameOnCard(t);case"ExpiryDate":case"expiryDate":return this.validateExpiryDate(t);case"Cvv":case"cvv":return this.validateCvv(t);default:return{isValid:!0,message:""}}}validateCreditCardNo(e){if(!e)return{isValid:!1,message:"Kart numarası boş bırakılamaz"};const t=this.cleanMaskValue(e);if(0===t.length)return{isValid:!1,message:"Kart numarası boş bırakılamaz"};if(16!==t.length)return{isValid:!1,message:"Kart numarası 16 haneli olmalıdır"};const a=(e=>{const t=e.replace(/\D/g,"");if(t.length<13||t.length>19)return!1;let a=0,i=!1;for(let s=t.length-1;s>=0;s--){let e=parseInt(t[s]);i&&(e*=2,e>9&&(e-=9)),a+=e,i=!i}return a%10==0})(t);return{isValid:a,message:a?"":"Geçerli bir kart numarası giriniz"}}validateNameOnCard(e){if(!e)return{isValid:!1,message:"Kart üzerindeki isim boş bırakılamaz"};if(e.trim()!==e)return{isValid:!1,message:"Kart üzerindeki isim sonunda boşluk içeremez"};if(e.includes("  "))return{isValid:!1,message:"Kart üzerindeki isimde birden fazla boşluk olamaz"};const t=e.trim();if(t.length<2)return{isValid:!1,message:"Kart üzerindeki isim en az 2 karakter olmalıdır"};if(t.length>80)return{isValid:!1,message:"Kart üzerindeki isim en fazla 80 karakter olabilir"};const a=/^[a-zA-ZçğıöşüÇĞIİÖŞÜ\s]*$/.test(t)&&!t.includes("  ");return{isValid:a,message:a?"":"Kart üzerindeki isim sadece harf içermelidir"}}validateExpiryDate(e){if(!e)return{isValid:!1,message:"Son kullanma tarihi boş bırakılamaz"};const t=this.cleanMaskValue(e);if(0===t.length)return{isValid:!1,message:"Son kullanma tarihi boş bırakılamaz"};if(4!==t.length)return{isValid:!1,message:"Son kullanma tarihi AA/YY formatında olmalıdır"};const a=(e=>{if(!/^\d{2}\/\d{2}$/.test(e))return!1;const[t,a]=e.split("/").map(Number);if(t<1||t>12)return!1;const i=new Date,s=i.getFullYear()%100,r=i.getMonth()+1;return!(a<s||a===s&&t<r||a>s+10)})(`${t.substring(0,2)}/${t.substring(2,4)}`);return{isValid:a,message:a?"":"Geçersiz son kullanma tarihi (AA/YY)"}}validateCvv(e){if(!e)return{isValid:!1,message:"CVV boş bırakılamaz"};const t=this.cleanMaskValue(e);if(0===t.length)return{isValid:!1,message:"CVV boş bırakılamaz"};const a=3===t.length;return{isValid:a,message:a?"":"CVV 3 haneli olmalıdır"}}validateAll(e){const t={};let a=!0;const i=this.validateField("CreditCardNo",e.CreditCardNo);t.CreditCardNo=i,i.isValid||(a=!1);const s=this.validateField("NameOnCard",e.NameOnCard);t.NameOnCard=s,s.isValid||(a=!1);const r=this.validateField("ExpiryDate",e.ExpiryDate);t.ExpiryDate=r,r.isValid||(a=!1);const n=this.validateField("Cvv",e.Cvv);return t.Cvv=n,n.isValid||(a=!1),{isValid:a,fieldResults:t}}isCardNumberComplete(e){if(!e)return!1;const t=this.cleanMaskValue(e);return 16===t.length&&/^\d{16}$/.test(t)}extractFormData(e){const t=e.querySelector("#securePayment"),a=(e.elements.creditCardNo?.value||"").replace(/[_\s]/g,""),i=(e.elements.expiryDate?.value||"").replace(/[_\s/]/g,""),s=(e.elements.cvv?.value||"").replace(/[_\s]/g,"");let r="";return 4===i.length?r=`${i.substring(0,2)}/${i.substring(2,4)}`:i.length>0&&(r=e.elements.expiryDate?.value||""),{CreditCardNo:a,NameOnCard:e.elements.nameOnCard?.value||"",ExpiryDate:r,Cvv:s,IsThreeDSecureSelected:!!t&&t.checked}}}class T{constructor(){this.maskInputSelector="[data-mask]",this.init()}init(){this.maskInputs=Array.from(document.querySelectorAll(this.maskInputSelector)),this.maskInputs.forEach(e=>{this.createMask(e)})}createMask(e){const t=e.getAttribute("data-mask");if(!t)return;const i="false"!==e.getAttribute("data-mask-lazy");a(e,"Number"===t?{mask:Number,lazy:i}:{mask:t,lazy:i})}}class b{constructor(e,t){this.apiClient=e,this.maskHandler=t,this.validator=new L,this.uiHandler=new s,this.form=null,this.paymentData=null,this.init()}
1async init(){this.form=document.getElementById("payment-form"),this.form&&(new T,this.clearFormFields(),await this.loadPaymentData(),this.setupValidation(),this.setupSubmitHandler())}async loadPaymentData(){try{const e=await this.apiClient.post("/satis/odeme-yukle",{});e.success&&e.data?(this.paymentData=e.data,this.handle3DSecureCheckbox(e.data.isThreeDSecureAvailable),e.data.selectedPackage&&this.updateSummary(e.data.selectedPackage)):window.appService&&"function"==typeof window.appService.showError&&window.appService.showError(e.message||"Ödeme bilgileri yüklenirken hata oluştu.")}catch(e){this.handle3DSecureCheckbox(!1),window.appService&&"function"==typeof window.appService.showError&&window.appService.showError("Ödeme bilgileri yüklenirken bir hata oluştu.")}}handle3DSecureCheckbox(e){const t=this.form.querySelector("#securePayment")?.closest(".form-group");if(t)if(e)t.style.display="";else{t.style.display="none";const e=this.form.querySelector("#securePayment");e&&(e.checked=!1)}}updateSummary(e){const t=document.getElementById("summary-package-name"),a=document.getElementById("summary-package-price");t&&e.packageDisplayName&&(t.textContent=e.packageDisplayName),a&&e.transactionAmount&&(a.textContent=`${e.transactionAmount.toFixed()} TL`)}setupValidation(){this.setupCvvMasking(),["creditCardNo","nameOnCard","expiryDate","cvv"].forEach(e=>{const t=this.form.elements[e];t&&(t.addEventListener("blur",()=>{this.validateField(e,t),"creditCardNo"===e&&16===t.value.replace(/[_\s]/g,"").length&&this.checkCardForThreeDMandatory(t.value)}),t.addEventListener("input",()=>{if("creditCardNo"===e){if(this.uiHandler.clearFieldError(t),0===t.value.replace(/[_\s]/g,"").length)return void this.reset3DSecureCheckbox()}else"nameOnCard"===e?(t.value=t.value.replace(/[^a-zA-ZçğıöşüÇĞIİÖŞÜ\s]/g,""),t.value=t.value.replace(/\s+/g," "),this.uiHandler.clearFieldError(t)):this.uiHandler.clearFieldError(t)}),"nameOnCard"===e&&(t.addEventListener("keypress",e=>{const a=e.which||e.keyCode,i=String.fromCharCode(a);if(![8,9,13,27,37,38,39,40,46].includes(a))return/^[a-zA-ZçğıöşüÇĞIİÖŞÜ\s]$/.test(i)?" "===i&&0===t.selectionStart?(e.preventDefault(),!1):void 0:(e.preventDefault(),!1)}),t.addEventListener("paste",e=>{const t=e.clipboardData.getData("text");if(/[^a-zA-ZçğıöşüÇĞIİÖŞÜ\s]/.test(t))return e.preventDefault(),!1})))})}validateField(e,t){let a=t.value;if("cvv"===e&&void 0!==this.realCvvValue&&(a=this.realCvvValue),0===a.replace(/[_\s/●]/g,"").length)return this.uiHandler.clearFieldError(t),!1;const i=e.charAt(0).toUpperCase()+e.slice(1),s=this.validator.validateField(i,a);return s.isValid?this.uiHandler.clearFieldError(t):this.uiHandler.showFieldError(t,s.message),s.isValid}setupSubmitHandler(){document.addEventListener("sale:validate-step",e=>{"Payment"===e.detail.stepName&&(this.validateForm()||e.preventDefault())}),document.addEventListener("sale:extract-form-data",e=>{if("Payment"===e.detail.stepName){const t=this.extractFormData();e.detail.formData=t}})}extractFormData(){const e=this.validator.extractFormData(this.form);return this.realCvvValue&&(e.Cvv=this.realCvvValue),e}validateForm(){const e=this.extractFormData(),t=this.validator.validateAll(e),a={CreditCardNo:"creditCardNo",NameOnCard:"nameOnCard",ExpiryDate:"expiryDate",Cvv:"cvv"};return Object.keys(t.fieldResults).forEach(e=>{const i=a[e]||e,s=this.form.elements[i],r=t.fieldResults[e];s&&(r.isValid?this.uiHandler.clearFieldError(s):this.uiHandler.showFieldError(s,r.message))}),t.isValid}async checkCardForThreeDMandatory(e){const t=e.replace(/[_\s]/g,"");if(0!==t.length&&16===t.length&&this.validator.isCardNumberComplete(e))try{const e=await this.apiClient.post("/satis/odeme-kart-kontrol",{CreditCardNo:t},{showErrorModal:!0});e.success&&e.data&&this.handle3DSecureMandatory(e.data.isThreeDSecureMandatory)}catch(a){this.handle3DSecureMandatory(!1)}}handle3DSecureMandatory(e){const t=this.form.querySelector("#securePayment"),a=t?.closest(".form-group");if((!a||"none"!==a.style.display)&&t)if(e){t.checked=!0,t.disabled=!0;const e=this.form.querySelector('label[for="securePayment"]');
1e&&(e.style.opacity="0.6",e.style.cursor="not-allowed")}else{t.disabled=!1;const e=this.form.querySelector('label[for="securePayment"]');e&&(e.style.opacity="1",e.style.cursor="pointer")}}reset3DSecureCheckbox(){const e=this.form.querySelector("#securePayment");if(e){e.checked=!1,e.disabled=!1;const t=this.form.querySelector('label[for="securePayment"]');t&&(t.style.opacity="1",t.style.cursor="pointer")}}clearFormFields(){if(!this.form)return;this.realCvvValue="",["creditCardNo","nameOnCard","expiryDate","cvv"].forEach(e=>{const t=this.form.elements[e];t&&(t.value="",this.uiHandler.clearFieldError(t),this.maskHandler&&this.maskHandler.applyMask(t),"false"===t.getAttribute("data-mask-lazy")&&t.dispatchEvent(new Event("input",{bubbles:!0})))});const e=this.form.querySelector("#securePayment");if(e){e.checked=!1,e.disabled=!1;const t=this.form.querySelector('label[for="securePayment"]');t&&(t.style.opacity="1",t.style.cursor="pointer")}}setupCvvMasking(){const e=this.form?.elements.cvv;e&&(this.realCvvValue="",this.cvvMaskTimeout=null,this.cvvMaskDelay=500,e.setAttribute("type","text"),e.setAttribute("inputmode","numeric"),e.setAttribute("autocomplete","off"),e.setAttribute("maxlength","3"),e.removeAttribute("data-mask"),e.value="___",e.addEventListener("focus",()=>{"___"===e.value&&(e.value="")}),e.addEventListener("keydown",e=>{this.handleCvvKeydown(e)}),e.addEventListener("input",()=>{this.syncCvvDisplay(e)}),e.addEventListener("blur",()=>{this.cvvMaskTimeout&&clearTimeout(this.cvvMaskTimeout),0===this.realCvvValue.length?e.value="___":this.maskAllCvv(e)}),e.addEventListener("paste",t=>{t.preventDefault();const a=t.clipboardData.getData("text").replace(/\D/g,"").slice(0,3);this.realCvvValue=a,e.value=a,this.scheduleCvvMask(e)}))}handleCvvKeydown(e){const t=e.target;if(this.cvvMaskTimeout&&clearTimeout(this.cvvMaskTimeout),/^\d$/.test(e.key)){if(e.preventDefault(),this.realCvvValue.length>=3)return;this.realCvvValue+=e.key;const a="●".repeat(this.realCvvValue.length-1);return t.value=a+e.key,void this.scheduleCvvMask(t)}return"Backspace"===e.key?(e.preventDefault(),void(this.realCvvValue.length>0&&(this.realCvvValue=this.realCvvValue.slice(0,-1),t.value="●".repeat(this.realCvvValue.length)))):"Delete"===e.key?(e.preventDefault(),this.realCvvValue="",void(t.value="")):void(["Tab","Enter","ArrowLeft","ArrowRight","Home","End"].includes(e.key)||e.preventDefault())}syncCvvDisplay(e){const t=e.value,a=this.realCvvValue.length;0===t.replace(/●/g,"").length&&t.length!==a&&(e.value="●".repeat(a))}scheduleCvvMask(e){this.cvvMaskTimeout&&clearTimeout(this.cvvMaskTimeout),this.cvvMaskTimeout=setTimeout(()=>{this.maskAllCvv(e)},this.cvvMaskDelay)}maskAllCvv(e){this.realCvvValue.length>0&&(e.value="●".repeat(this.realCvvValue.length))}getRealCvvValue(){return this.realCvvValue||""}destroy(){}}class _ extends C{constructor(){super(),this.initializeRules()}initializeRules(){this.addRule("billingAddress",e=>{if(u(e))return!1;const t=e.trim();return!(t.length<10||t.length>512)},"Lütfen geçerli bir fatura adresi giriniz (10-512 karakter arası)."),this.addRule("cityCode",e=>!u(e),"Lütfen il seçiniz."),this.addRule("districtCode",e=>!u(e),"Lütfen ilçe seçiniz."),this.addRule("preContractInfo",e=>!0===e,"Sözleşme öncesi bilgi formunu onaylamanız gerekmektedir."),this.addRule("serviceAgreement",e=>!0===e,"Hizmet sözleşmesini onaylamanız gerekmektedir.")}validate(e){const t={};let a=!0;const i=this.validateField("billingAddress",e.billingAddress);i.isValid||(t.billingAddress=i.message,a=!1);const s=this.validateField("cityCode",e.cityCode);s.isValid||(t.cityCode=s.message,a=!1);const r=this.validateField("districtCode",e.districtCode);r.isValid||(t.districtCode=r.message,a=!1);const n=this.validateField("preContractInfo",e.preContractInfo);n.isValid||(t.preContractInfo=n.message,a=!1);const o=this.validateField("serviceAgreement",e.serviceAgreement);return o.isValid||(t.serviceAgreement=o.message,a=!1),{isValid:a,errors:t}}}class D{constructor(e){this.apiClient=e,this.validator=new _,this.uiHandler=new s,this.contentModalHandler=new y(e),this.form=null,this.threeDTimeout=null,this.paymentStatusPollingInterval=null,this.init()}init(){this.form=document.getElementById("verify-form"),this.form&&(this.setupValidation(),this.setupSubmitHandler(),this.setupCityDistrictDropdowns(),this.sendAddPaymentInfoEvent())}sendAddPaymentInfoEvent(){if(this.form)try{const e=this.getFormData(),t={id:e.productId||e.packageCode,name:e.productName||e.packageName||"Ürün",price:parseFloat(e.packagePriceRaw||"0")+" TL",category:e.salesCategory||"Bireysel",category2:(e.productName||"").includes("Paket")?"Paket":"Ürün",category3:e.packageGroupName,paymentType:e.paymentType||"Kredi Kartı"};e.packageGroupName&&(t.name=e.packageGroupName,t.category4=e.packageName||"Paket "+t.id),f.pu
1shPaymentEvent("add_payment_info",t)}catch(e){}}getFormData(){const e=document.getElementById("product-id")?.value,t=document.getElementById("product-name")?.value,a=document.getElementById("package-code")?.value,i=document.getElementById("package-name")?.value,s=document.getElementById("package-price")?.value,r=document.getElementById("sales-category")?.value,n=document.getElementById("package-group-name")?.value,o=document.getElementById("payment-method-description")?.value;return{productId:e,productName:t,packageCode:a,packageName:i,packagePriceRaw:s,salesCategory:r,packageGroupName:n,paymentType:o}}setupCityDistrictDropdowns(){const e=document.querySelector('[data-address-type="city"]'),t=document.querySelector('[data-address-type="district"]');if(!e||!t)return;const a=e.querySelector(".custom-select-btn"),i=e.querySelector(".custom-select-dropdown"),s=e.querySelector('input[type="hidden"]'),r=t.querySelector(".custom-select-btn"),n=t.querySelector(".custom-select-dropdown"),o=t.querySelector('input[type="hidden"]');if(!(a&&i&&r&&n))return;const l=document.getElementById("all-districts-data");let d=[];if(l)try{d=JSON.parse(l.textContent||"[]")}catch(h){}const c=s.value,u=o.value;c?(r.removeAttribute("disabled"),r.classList.remove("opacity-50","cursor-not-allowed"),this.filterDistricts(c,d,n,r,o,u),u?this.enableBillingAddress():this.disableBillingAddress()):this.disableBillingAddress(),e.addEventListener("click",t=>{if(t.target.closest(".custom-select-btn"))return t.preventDefault(),t.stopPropagation(),i.classList.contains("hidden"),i.classList.toggle("hidden"),void n.classList.add("hidden");const l=t.target.closest(".custom-select-option");if(l){t.stopPropagation();const c=l.getAttribute("data-value"),u=l.textContent.trim();s.value=c;const h=a.querySelector(".custom-select-text"),m=a.querySelector(".custom-select-label");h.textContent=u,m.classList.remove("hidden"),i.classList.add("hidden"),this.uiHandler.clearDropdownError(e),this.clearBillingAddress(),this.disableBillingAddress(),this.uncheckContractCheckboxes(),r.removeAttribute("disabled"),r.classList.remove("opacity-50","cursor-not-allowed"),this.filterDistricts(c,d,n,r,o)}}),t.addEventListener("click",e=>{const t=e.target.closest(".custom-select-btn");if(t&&!t.hasAttribute("disabled"))return e.preventDefault(),e.stopPropagation(),n.classList.toggle("hidden"),void i.classList.add("hidden")}),document.addEventListener("click",a=>{e.contains(a.target)||t.contains(a.target)||(i.classList.add("hidden"),n.classList.add("hidden"))})}filterDistricts(e,t,a,i,s,r=null){a.innerHTML="";const n=t.filter(t=>String(t.cityCode||t.citycode||"").trim()===String(e||"").trim());if(0!==n.length)if(n.forEach(e=>{const t=document.createElement("li");t.className="custom-select-option px-4 py-2 hover:bg-gray-100 cursor-pointer";const r=e.districtCode||e.districtcode,n=e.districtName||e.districtname;t.setAttribute("data-value",r),t.textContent=n,t.addEventListener("click",()=>{s.value=r;const e=i.querySelector(".custom-select-text"),t=i.querySelector(".custom-select-label");e.textContent=n,t.classList.remove("hidden"),a.classList.add("hidden");const o=document.querySelector('[data-address-type="district"]');this.uiHandler.clearDropdownError(o),this.clearBillingAddress(),this.uncheckContractCheckboxes(),this.enableBillingAddress()}),a.appendChild(t)}),r){const e=n.find(e=>(e.districtCode||e.districtcode)===r);if(e){const t=i.querySelector(".custom-select-text"),a=i.querySelector(".custom-select-label");t.textContent=e.districtName||e.districtname,a.classList.remove("hidden")}}else{s.value="";const e=i.querySelector(".custom-select-text"),t=i.querySelector(".custom-select-label");e.textContent="İlçe seçiniz",t.classList.add("hidden")}else a.innerHTML='<li class="px-4 py-2 text-gray-400">İlçe bulunamadı</li>'}clearBillingAddress(){const e=document.getElementById("billingAddress");e&&(e.value="",this.addressDetailChanged=!1,this.uiHandler.clearFieldError(e))}disableBillingAddress(){const e=document.getElementById("billingAddress");e&&(e.disabled=!0,e.classList.add("opacity-50","cursor-not-allowed","bg-gray-100"))}enableBillingAddress(){const e=document.getElementById("billingAddress");e&&(e.disabled=!1,e.classList.remove("opacity-50","cursor-not-allowed","bg-gray-100"))}uncheckContractCheckboxes(){const e=document.getElementById("preContractInfo"),t=document.getElementById("serviceAgreement");e&&e.checked&&(e.checked=!1),t&&t.checked&&(t.checked=!1)}setupValidation(){const e=this.form.elements.billingAddress;e&&(e.addEventListener("input",()=>{this.uiHandler.clearFieldError(e),this.uncheckContractCheckboxes()}),e.addEventListener("blur",()=>{this.validateField("billingAddress",e)}
1)),["preContractInfo","serviceAgreement"].forEach(e=>{const t=this.form.elements[e];t&&t.addEventListener("change",()=>{this.validateField(e,t)})})}validateField(e,t){const a="checkbox"===t.type?t.checked:t.value,i=this.validator.validateField(e,a,t);return i.isValid?(this.uiHandler.clearFieldError(t),!0):(this.uiHandler.showFieldError(t,i.message),!1)}setupSubmitHandler(){this.form.addEventListener("submit",async e=>{e.preventDefault(),e.stopPropagation(),this.validateForm()&&await this.submitForm()})}extractFormData(){const e=this.form.elements.billingAddress,t=document.getElementById("cityCode"),a=document.getElementById("districtCode"),i=this.form.elements.preContractInfo,s=this.form.elements.serviceAgreement;return{billingAddress:e?e.value.trim():"",cityCode:t?t.value:"",districtCode:a?a.value:"",preContractInfo:!!i&&i.checked,serviceAgreement:!!s&&s.checked}}validateForm(){const e=this.extractFormData(),t=this.validator.validateAll(e);return this.uiHandler.applyValidationResults(this.form,t.fieldResults),t.isValid}async submitForm(){this.form.querySelector('button[type="submit"]');try{const t=this.extractFormData(),a=await this.apiClient.post("/satis/onay",t);if(a.success&&a.data){if(a.data.requiresThreeD&&a.data.formContent)return void this.show3DSecureModal(a.data.formContent,a.data.transactionId);if(!a.data.canProceedToNextStep)throw new Error(a.message||"Onay işlemi tamamlanamadı.");{const e=await this.apiClient.post("/satis/talep-olustur",{},{showErrorModal:!0});e&&e.success&&(window.location.href=e.data?.redirectUrl||"/satis/sonuc"),this.sendPurchaseEvent(a.data.transactionId||"unknown_transaction_id")}}else{const t=a.message||"Onay işlemi sırasında bir hata oluştu.";void 0!==e&&"function"==typeof e.showError&&e.showError(t)}}catch(t){void 0!==e&&"function"==typeof e.showError&&e.showError("İşlem sırasında beklenmeyen bir hata oluştu. Lütfen tekrar deneyin.")}}show3DSecureModal(t,a){const i=document.createElement("div");i.innerHTML='\n            <div class="modal fixed inset-0 z-[9999] flex items-center justify-center bg-black/50 opacity-0 invisible transition-all duration-300" id="threeds-payment-modal">\n                <div class="modal-content bg-white rounded-lg w-full max-w-5xl mx-6 relative transform scale-95 transition-transform duration-300 max-h-[90vh] flex flex-col">\n                    <div class="flex items-center justify-between p-6 border-b">\n                        <div>\n                            <h3 class="text-2xl font-medium text-bluePrimary">Güvenli Ödeme</h3>\n                            <p class="text-sm text-gray-500 mt-1">3D Secure Doğrulama</p>\n                        </div>\n                        <button class="modal-close w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-100 transition-colors" type="button">\n                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">\n                                <path d="M18 6L6 18M6 6L18 18" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>\n                            </svg>\n                        </button>\n                    </div>\n                    <div class="flex-1 overflow-hidden p-6">\n                        <div class="text-center mb-4">\n                            <div class="inline-flex items-center gap-2 px-4 py-2 bg-blue-50 rounded-lg">\n                                <svg class="w-5 h-5 text-bluePrimary" fill="none" stroke="currentColor" viewBox="0 0 24 24">\n                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path>\n                                </svg>\n                                <span class="text-sm text-bluePrimary font-medium">Güvenli bağlantı üzerinden işlem yapıyorsunuz</span>\n                            </div>\n                            <p class="text-sm text-gray-500 mt-2">Lütfen banka sayfasında doğrulama işlemini tamamlayın</p>\n                        </div>\n                        <iframe id="threeds-iframe" \n                                name="threeds-iframe" \n                                class="w-full border rounded-lg shadow-sm"\n                                style="min-height: 500px; height: 60vh;"\n                                frameborder="0"\n                                sandbox="allow-forms allow-scripts allow-same-origin allow-top-navigation">\n                        </iframe>\n                        <div id="threeds-form-container" style="display: none;"></div>\n                    </div>\n                </div>\n            </div>\n        ';const s=i.firstElementChild;document.body.appendChild(s),s.querySelector(".modal-close").addEventListener("click",()=>{confirm("Ödeme işlemini iptal etmek istediğinizden emin misiniz?")&&this.close3DSecureModal()}),setTimeout(()=>{s.classList.remove("invisible","opacity-0"),s.querySelector(".modal-content").classList.remove("scale-95"),s.querySelector(".modal-content").classList.add("scale-100")},10),this.submitBankFormToIframe(t,s),this.startPaymentStatusPolling(a),this.threeDTimeout=setTimeout(()=>{this.close3DSecureModal(),void 0!==e&&"function"==typeof e.showError&&e.showError("Ödeme işlemi zaman aşımına uğradı. Lütfen tekrar deneyin.")},9e5)}async startPaymentStatusPolling(e){let t=0;setTimeout(async()=>{await this.checkPaymentStatus(e)},2e3),this.paymentStatusPollingInterval=setInterval(async()=>
1{if(t++,t>600)return clearInterval(this.paymentStatusPollingInterval),void(this.paymentStatusPollingInterval=null);await this.checkPaymentStatus(e)},1500)}async checkPaymentStatus(t){try{const i=await this.apiClient.get("/satis/odeme-durumu-kontrol",{showLoading:!1});if(!i||!i.data)return;switch(i.data.status){case"success":this.close3DSecureModal(),window.appService&&"function"==typeof window.appService.showSuccess&&window.appService.showSuccess(i.message||"Ödeme başarıyla tamamlandı!");try{const e=await this.apiClient.post("/satis/talep-olustur",{},{showErrorModal:!0});e&&e.success&&(window.location.href=e.data?.redirectUrl||"/satis/sonuc")}catch(a){void 0!==e&&"function"==typeof e.showError&&e.showError("Talep oluşturulurken bir hata oluştu. Lütfen destek ekibi ile iletişime geçiniz.")}this.sendPurchaseEvent(i.data.transactionId||t);break;case"failed":this.close3DSecureModal();const s=i.data.errorMessage||i.message||"Ödeme işlemi başarısız oldu.";void 0!==e&&"function"==typeof e.showError&&e.showError(s);break;case"timeout":this.close3DSecureModal(),void 0!==e&&"function"==typeof e.showError&&e.showError("Ödeme işlemi zaman aşımına uğradı.")}}catch(i){}}submitBankFormToIframe(e,t){const a=t.querySelector("#threeds-form-container");let i=e;if(i.includes("\\u"))try{i=JSON.parse('"'+i.replace(/"/g,'\\"')+'"')}catch(r){}a.innerHTML=i;const s=a.querySelector("form");s?(s.target="threeds-iframe",a.querySelectorAll("script").forEach(e=>e.remove()),setTimeout(()=>{s.submit()},500)):this.close3DSecureModal()}close3DSecureModal(){const e=document.getElementById("threeds-payment-modal");e&&(e.classList.add("invisible","opacity-0"),e.querySelector(".modal-content")?.classList.remove("scale-100"),e.querySelector(".modal-content")?.classList.add("scale-95"),setTimeout(()=>{e.remove()},300)),this.threeDTimeout&&(clearTimeout(this.threeDTimeout),this.threeDTimeout=null),this.paymentStatusPollingInterval&&(clearInterval(this.paymentStatusPollingInterval),this.paymentStatusPollingInterval=null)}destroy(){this.form&&this.form.removeEventListener("submit",this.submitForm),this.threeDTimeout&&(clearTimeout(this.threeDTimeout),this.threeDTimeout=null),this.paymentStatusPollingInterval&&(clearInterval(this.paymentStatusPollingInterval),this.paymentStatusPollingInterval=null),this.contentModalHandler&&this.contentModalHandler.destroy(),this.close3DSecureModal()}}class R{constructor(e){window.__successStepInitialized||(window.__successStepInitialized=!0,this.apiClient=e,this.viewReportBtn=null,this.init())}init(){this.setupViewReportButton(),this.setupSecurityFeatures(),this.attachButtonEvent(),this.sendPurchaseEvent()}sendPurchaseEvent(){try{const e=document.getElementById("product-id")?.value,t=document.getElementById("product-name")?.value,a=document.getElementById("product-price")?.value,i=document.getElementById("product-category")?.value,s=document.getElementById("payment-type")?.value,r={id:e||"unknown_product",name:t||"Ürün",price:parseFloat(a||"0")+" TL",category:i||"Bireysel",category2:(t||"").includes("Paket")?"Paket":"Ürün",paymentType:s||"Kredi Kartı"};f.pushPaymentEvent("purchase",r)}catch(e){}}setupViewReportButton(){this.viewReportBtn=document.getElementById("view-report-btn")}attachButtonEvent(){this.viewReportBtn&&this.viewReportBtn.addEventListener("click",e=>{e.preventDefault(),this.downloadReport()})}setupSecurityFeatures(){"function"==typeof history.pushState&&(history.pushState(null,null,location.href),window.addEventListener("popstate",()=>{history.pushState(null,null,location.href),this.showBackButtonWarning()})),document.addEventListener("visibilitychange",()=>{}),window.addEventListener("pageshow",e=>{(e.persisted||window.performance&&2===window.performance.navigation.type)&&(window.location.href="/")})}showBackButtonWarning(){window.appService&&"function"==typeof window.appService.showError&&window.appService.showError("İşleminiz başarıyla tamamlanmıştır. Bu sayfadan geri dönemezsiniz.")}downloadReport(){this.viewReportBtn?.querySelector("span");try{this.viewReportBtn&&(this.viewReportBtn.disabled=!0,this.viewReportBtn.classList.add("opacity-50","cursor-not-allowed")),this.apiClient.post("/satis/rapor-pdf-getir",{}).then(e=>{if(e.success&&e.data){const t=e.data.PdfContent||e.data.pdfContent,a=e.data.FileName||e.data.fileName||"Findeks_Rapor.pdf";if(!t)throw new Error("PDF içeriği bulunamadı");this.downloadPdfFromBase64(t,a)}else window.appService&&"function"==typeof window.appService.showError&&window.appService.showError(e.message||e.error||"Rapor görüntülenirken bir hata oluştu.")}).catch(e=>{window.appService&&"function"==typeof window.appService.showError&&window.appService.showError("Rapor görüntülenirken bir hata oluştu. Lütfen tekrar deneyiniz.")})}catch(e){window.appService&&"function"==typeof window.appService.showError&&window.appService.showError("Rapor görüntülenirken bir hata oluştu. Lütfen tekrar deneyiniz.")}finally{this.viewReportBtn&&(this.viewReportBtn.disabled=!1,this.viewReportBtn.classList.remove("opacity-50","cursor-not-allowed"))}}downloadPdfFromBase64(e,t){try{if(!e||"string"!=typeof e)throw new Error("Geçersiz PDF içeriği: Base64 string bulunamadı");const t=e.replace(/\s/g,"").replace(/\n/g,"").replace(/\r/g,"").replace(/\t/g,"").trim();if(!t||0===t.length)throw new Error("Base64 string boş veya geçersiz");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new Error("Base64 string geçersiz karakterler içeriyor");const a=window.atob(t),i=new Uint8Array(a.length);for(let e=0;e<a.length;
1e++)i[e]=a.charCodeAt(e);const s=new Blob([i],{type:"application/pdf"}),r=window.URL.createObjectURL(s);if(!window.open(r,"_blank")){const e=document.createElement("a");e.href=r,e.target="_blank",e.rel="noopener noreferrer",document.body.appendChild(e),e.click(),document.body.removeChild(e)}setTimeout(()=>{window.URL.revokeObjectURL(r)},6e4)}catch(a){throw a}}destroy(){this.viewReportBtn&&(this.viewReportBtn.removeEventListener("click",this.downloadReport),this.viewReportBtn=null),window.__successStepInitialized=!1}}class M{constructor(){this.masks=new Map,this.maskConfigs={phone:{mask:"0000 000 00 00",lazy:!1},tc:{mask:"00000000000",lazy:!1},date:{mask:"00/00/0000",lazy:!1},"card-8":{mask:"0000 0000",lazy:!1},"card-4":{mask:"0000",lazy:!1},"card-full":{mask:"0000 0000 0000 0000",lazy:!1},expiry:{mask:"00/00",lazy:!1},cvv:{mask:"000",lazy:!1},otp:{mask:"000000",lazy:!1}}}initializeAll(e=document){e.querySelectorAll("[data-mask]").forEach(e=>{this.applyMask(e)})}applyMask(e){const t=e.getAttribute("data-mask"),i=e.getAttribute("data-mask-pattern");let s;s=i?{mask:i,lazy:!1}:this.maskConfigs[t]?this.maskConfigs[t]:{mask:t,lazy:!1};try{const t=a(e,s);this.masks.set(e,t)}catch(r){}}removeMask(e){const t=this.masks.get(e);t&&(t.destroy(),this.masks.delete(e))}destroyAll(){this.masks.forEach((e,t)=>{e.destroy()}),this.masks.clear()}getUnmaskedValue(e){const t=this.masks.get(e);return t?t.unmaskedValue:e.value}getMaskedValue(e){const t=this.masks.get(e);return t?t.value:e.value}}class P{constructor(){this.apiClient=null,this.flowManager=null,this.currentStepHandler=null,this.stepHandlers={},this.maskHandler=null,this.contentModalHandler=null}init(){this.apiClient=new t({baseURL:"",timeout:3e4,unexpectedErrorMessage:"Beklenmedik bir hata oluştu. Lütfen tekrar deneyiniz."}),this.maskHandler=new M,this.maskHandler.initializeAll(),this.contentModalHandler=new y(this.apiClient),this.flowManager=new i(this.apiClient),this.initializeCurrentStep()}initializeCurrentStep(){const e=this.flowManager.getCurrentStep();switch(e){case"Information":this.currentStepHandler=new S(this.apiClient);break;case"CardVerification":this.currentStepHandler=new w(this.apiClient);break;case"PhoneVerification":this.currentStepHandler=new A(this.apiClient);break;case"PackageSelection":this.currentStepHandler=new I(this.apiClient);break;case"Payment":this.currentStepHandler=new b(this.apiClient,this.maskHandler);break;case"Confirmation":this.currentStepHandler=new D(this.apiClient);break;case"Success":this.currentStepHandler=new R(this.apiClient)}this.currentStepHandler&&(this.stepHandlers[e]=this.currentStepHandler)}destroy(){this.contentModalHandler&&"function"==typeof this.contentModalHandler.destroy&&(this.contentModalHandler.destroy(),this.contentModalHandler=null),this.maskHandler&&(this.maskHandler.destroyAll(),this.maskHandler=null),this.currentStepHandler&&"function"==typeof this.currentStepHandler.destroy&&this.currentStepHandler.destroy(),Object.values(this.stepHandlers).forEach(e=>{e&&"function"==typeof e.destroy&&e.destroy()}),this.stepHandlers={},this.currentStepHandler=null,this.flowManager=null,this.apiClient=null}}export{f as D,P as S,S as a,v as i};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.