(function ($) {
  "use strict";
	/*-------------------------------------
		Animation on scroll: Number rotator
	-------------------------------------*/
	$("[data-appear-animation]").each(function() {
		var self      = $(this);
		var animation = self.data("appear-animation");
		var delay     = (self.data("appear-animation-delay") ? self.data("appear-animation-delay") : 0);{ 
			self.html('0');
			self.waypoint(function(direction) {
				if( !self.hasClass('completed') ){
					var from     = self.data('from');
					var to       = self.data('to');
					var interval = self.data('interval');
					self.numinate({
						format: '%counter%',
						from: from,
						to: to,
						runningInterval: 2000,
						stepUnit: interval,
						onComplete: function(elem) {
							self.addClass('completed');
						}
					});
				}
			}, { offset:'85%' });
		}
	});

	/*-------------------------------------
    	Swiper Slider
    -------------------------------------*/
    var swiperslider = $(".swiper-slider");
	var x = 1;
	swiperslider.each(function () {  
				var carouselElement	= $(this);
				var columns = $(this).data('columns');
				var loop = $(this).data('loop');
				var autoplay2 = $(this).data('autoplay');
				var autoplayspeed1 = $(this).data('autoplayspeed');
				var val_nav = $(this).data('arrows');
				var nav_arrow = $(this).data('arrows-class');                
				var val_dots = $(this).data('dots');
				var val_center = $(this).data('center');
				var style = $(this).data('effect');
				var loopSlide = null;
				var sl_speed = 2500; 

				carouselElement.addClass( 'pbmit-element-viewtype-carousel-' + x );


				if( columns === 1 ){ 
					var responsive_items = [ /* 1199 : */ columns, /* 991 : */ '1', /* 767 : */ '1', /* 575 : */ '1', /* 0 : */ '1' ];
				} 
				else if( columns == 1.5 ){ 
					var responsive_items = [ /* 1199 : */ columns, /* 991 : */ '1', /* 767 : */ '1', /* 575 : */ '1', /* 0 : */ '1' ];
				} 
				else if( columns === 2 ){ 
					var responsive_items = [ /* 1199 : */ columns, /* 991 : */ '2', /* 767 : */ '2', /* 575 : */ '2', /* 0 : */ '1' ];
				}
				else if( columns === 2.6 ){ 
					var responsive_items = [ /* 1199 : */ columns, /* 991 : */ '2', /* 767 : */ '2', /* 575 : */ '2', /* 0 : */ '1' ];
				}
				else if( columns === 3 ){
					var responsive_items = [ /* 1199 : */ columns, /* 991 : */ '2', /* 767 : */ '2', /* 575 : */ '1', /* 0 : */ '1' ];
				}
				else if( columns === 4 ){
					var responsive_items = [ /* 1199 : */ columns, /* 991 : */ '3', /* 767 : */ '3', /* 575 : */ '2', /* 0 : */ '1' ];
				} 
				else if( columns === 5 ){
					var responsive_items = [ /* 1199 : */ '5', /* 991 : */ '4', /* 767 : */ '3', /* 575 : */ '2', /* 0 : */ '1' ];
				} 
				else if( columns === 6 ){
					var responsive_items = [ /* 1199 : */ '6', /* 991 : */ '4', /* 767 : */ '3', /* 575 : */ '2', /* 0 : */ '1' ];
				} 
				else {
					var responsive_items = [ /* 1199 : */ '3', /* 991 : */ '3', /* 767 : */ '2', /* 575 : */ '2', /* 0 : */ '1' ];
				}

				if (val_dots === true) {
					carouselElement.append('<div class="swiper-pagination swiper-pagination"></div>');
				}

				if(val_nav === true){
					
					if(!nav_arrow){
					carouselElement.append( '<div class="swiper-buttons"></div>' );
					carouselElement.find('.swiper-buttons').append( '<div class="swiper-button-next swiper-button-next-' + x + '"></div>' );
					carouselElement.find('.swiper-buttons').append( '<div class="swiper-button-prev swiper-button-prev-' + x + '"></div>' );
					} else{             
					$('.' + nav_arrow).append( '<div class="swiper-buttons"></div>' );
					$('.' + nav_arrow).append( '<div class="swiper-button-next swiper-button-next-' + x + '"></div>' );
					$('.' + nav_arrow).append( '<div class="swiper-button-prev swiper-button-prev-' + x + '"></div>' );
					}
				}

				var pagination_val = false;
				if (val_dots === true) {

					if(carouselElement.hasClass('pbmit-sep-number')){ 
						pagination_val = {
							el: '.swiper-pagination',
							type :'fraction',
						};
					} else{
						pagination_val = {
						el: '.swiper-pagination',
						clickable: true,
					};
						}
					}
				var navigation_val = false;
				if(val_nav === true){
					navigation_val =  {
					nextEl: '.swiper-button-next-' + x,
					prevEl: '.swiper-button-prev-' + x,
					};
				}

				if(!style){
					style = "slide";
				}    
				
				var margin_val = 30;
				if( $(carouselElement).data('margin') !== '' || $(carouselElement).data('margin') === '0'){
					margin_val = $(carouselElement).data('margin');  
				} 
				
				if(carouselElement.hasClass('marquee')){ 
					var reverse_direction = $(this).data('reverse');
					if (!reverse_direction) reverse_direction = false;
					var swiper2 = new Swiper( '.pbmit-element-viewtype-carousel-' + x, { 
						spaceBetween: 0,
						centeredSlides: true,
						speed: 10000,
						autoplay: {
							delay: 1,
							disableOnInteraction: true,
							reverseDirection: reverse_direction,
						},
						loop: true,
						slidesPerView: 'auto',
						allowTouchMove: false,
						disableOnInteraction: true
					});
				} else{     
					if(autoplay2){
						autoplay2 = { delay: 6000 };
					}               
				var swiper = new Swiper( '.pbmit-element-viewtype-carousel-' + x, { 
					loop: loop, 
					navigation: navigation_val,
					pagination: pagination_val,
					slidesPerView: columns,
					spaceBetween: margin_val,
					loopedSlides: loopSlide, 
					autoplay : autoplay2,
					effect: style,
					speed: sl_speed, 
					grabCursor: false,
					centeredSlides: val_center,
					breakpoints		  : {
					1199 : {
						slidesPerView	: responsive_items[0],
					},
					991	 : {					
						slidesPerView	: responsive_items[1],
					},
					767	 : {
						slidesPerView	: responsive_items[2],
					},
					575	 : {
						slidesPerView	: responsive_items[3],
					},
					0	 : {
						slidesPerView	: responsive_items[4],
					}
					}
				});
			}
		x = x + 1;             
	});   
	
	/*-------------------------------------
		ProgressBar
	-------------------------------------*/
	AOS.init({
		once: true,
	});

	/*-------------------------------------
		Scroll To Top
	-------------------------------------*/
	var pbmit_back_to_top = function() {
		if( jQuery('.pbmit-progress-wrap path').length > 0 ){
			var progressPath = document.querySelector('.pbmit-progress-wrap path');
			var pathLength = progressPath.getTotalLength();
			progressPath.style.transition = progressPath.style.WebkitTransition = 'none';
			progressPath.style.strokeDasharray = pathLength + ' ' + pathLength;
			progressPath.style.strokeDashoffset = pathLength;
			progressPath.getBoundingClientRect();
			progressPath.style.transition = progressPath.style.WebkitTransition = 'stroke-dashoffset 10ms linear';
			var updateProgress = function() {
				var scroll = jQuery(window).scrollTop();
				var height = jQuery(document).height() - jQuery(window).height();
				var progress = pathLength - (scroll * pathLength / height);
				progressPath.style.strokeDashoffset = progress;
			}
			updateProgress();
			jQuery(window).scroll(updateProgress);
			var offset = 50;
			var duration = 550;
			jQuery(window).on('scroll', function() {
				if (jQuery(this).scrollTop() > offset) {
					jQuery('.pbmit-progress-wrap').addClass('active-progress');
				} else {
					jQuery('.pbmit-progress-wrap').removeClass('active-progress');
				}
			});
			jQuery('.pbmit-progress-wrap').on('click', function(event) {
				event.preventDefault();
				jQuery('html, body').animate({ scrollTop: 0 }, duration);
				return false;
			})
		}
		jQuery('.pbmit-scroll-section').on('click', function(event) {
			var target = jQuery(this.hash);
			target = target.length ? target : jQuery('[name=' + this.hash.substr(1) +']');
			jQuery('html, body').animate({
				scrollTop: target.offset().top
			}, 500);
			return false;
		});
	}
	pbmit_back_to_top();

	/*-------------------------------------
		tooltip
	-------------------------------------*/
	var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
	var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
	return new bootstrap.Tooltip(tooltipTriggerEl)
	})
    
	/*-------------------------------------
		Mobile Menu
	-------------------------------------*/     
	$('.navbar-toggler,.closepanel').on('click', function () { 
		jQuery("header").toggleClass("active");
	}); 

	/*-------------------------------------
		Sticky header wrapper
	-------------------------------------*/
		if( jQuery('.site-header-menu-wrapper').length == 0 ){
			jQuery('.site-header-menu').wrap('<div class="site-header-menu-wrapper"></div>');
			}
			jQuery('.site-header-menu-wrapper').height( jQuery('.site-header-menu-wrapper').height() ).css('margin-bottom', jQuery('.site-header-menu').css('margin-bottom') );

			jQuery(window).resize(function(){
			if( jQuery(window).width() < 1200 ){
				jQuery('.site-header-menu-wrapper').css('height', '');
				jQuery('.site-header-menu-wrapper').css('margin-bottom', '');
			} else {
				jQuery('.site-header-menu-wrapper').height( jQuery('.site-header-menu-wrapper').height() ).css('margin-bottom', jQuery('.site-header-menu').css('margin-bottom') );
			}
			
		});

	/*-------------------------------------
		Magnific Popup
	-------------------------------------*/
		var i_type = 'image';
		$('.pbmin-lightbox-video, .pbmin-lightbox-video a, a.pbmit-lightbox').each(function(){
			if( $(this).hasClass('pbmin-lightbox-video')){ 
				i_type = 'iframe';
			} else {
				i_type = 'image';
			}  
			$(this).magnificPopup({type:i_type});
		});   

	/*-------------------------------------
		Magnific Popup
	-------------------------------------*/
	$('.pbmit-nav-menu-toggle').on('click', function() {
		$(".floting-bar-wrap").toggleClass("active");
	})
	$('.floting-bar-wrap .closepanel').on('click', function() {
		$(".floting-bar-wrap").toggleClass("active");
	});
	/*-------------------------------------
		Accordion
	-------------------------------------*/

	$('.accordion .accordion-item').on('click', function () { 
		var e = $(this);  
		$(this).parent().find('.accordion-item').removeClass('active');        
		if(!$(this).find('.accordion-button').hasClass('collapsed')){
		$(this).addClass('active');
		}  
	}); 

	/*-------------------------------------
		Add plus icon in menu
	-------------------------------------*/
  	$( ".main-menu ul.navigation li.dropdown").append( "<span class='righticon'><i class='pbmit-base-icon-angle-right'></i></span>" );
  
	/*-------------------------------------
		Responsive Menu
	-------------------------------------*/ 
	$('.main-menu ul.navigation li.dropdown .righticon').on('click', function() {
			$(this).siblings().toggleClass('open');
			$(this).find('i').toggleClass('pbmit-base-icon-angle-right pbmit-base-icon-up-open-big');
			return false;
	});  

	/*-------------------------------------
   		Sticky Header
    -------------------------------------*/ 
    jQuery(window).on('scroll', function() {
        var sticky = $('.site-header-menu'),
        scroll = $(window).scrollTop();
        if (scroll >= 90) sticky.addClass('sticky-header');
        else sticky.removeClass('sticky-header');
    });

	/*-------------------------------------
    	Stretched Div
    -------------------------------------*/ 	
	var document_width = $(document).width();
	function pbmit_col_stretched(){
		$('.pbmit-col-stretched-yes').each(function() {
			var this_ele = $(this);
			var window_width = jQuery(window).width();
			var main_width = $('.container').width();
			var extra_width = ((window_width - main_width) / 2);  
			if (window_width < 1200){
				extra_width = 0;
			}
			if (this_ele.hasClass('pbmit-col-right')) { 
				$('.pbmit-col-stretched-right', this_ele).css('margin-right', '-' + extra_width + 'px'); 
			} else { 
				$('.pbmit-col-stretched-left', this_ele).css('margin-left', '-' + extra_width + 'px'); 
			}
		});
	} 
	jQuery(window).on('resize', function() {
		pbmit_col_stretched();
	});
	pbmit_col_stretched();

	/*-------------------------------------
		Circle Progressbar
	-------------------------------------*/
	$('.pbmit-circle-outer').each(function() {
		var this_circle = $(this);

		// Circle settings
		var emptyFill_val = "rgba(0, 0, 0, 0)";
		var thickness_val = 10;
		var fill_val = this_circle.data('fill');
		var size_val = 115;

		if (typeof this_circle.data('emptyfill') !== 'undefined' && this_circle.data('emptyfill') !== '') {
			emptyFill_val = this_circle.data('emptyfill');
		}
		if (typeof this_circle.data('thickness') !== 'undefined' && this_circle.data('thickness') !== '') {
			thickness_val = this_circle.data('thickness');
		}
		if (typeof this_circle.data('size') !== 'undefined' && this_circle.data('size') !== '') {
			size_val = this_circle.data('size');
		}
		if (typeof this_circle.data('filltype') !== 'undefined' && this_circle.data('filltype') === 'gradient') {
			fill_val = { gradient: [this_circle.data('gradient1'), this_circle.data('gradient2')], gradientAngle: Math.PI / 4 };
		}

		if (typeof $.fn.circleProgress === "function") {
			var digit = this_circle.data('digit');
			var before = this_circle.data('before');
			var after = this_circle.data('after');
			var digit = Number(digit);
			var short_digit = (digit / 100);

			$('.pbmit-circle', this_circle).circleProgress({
				value: 0,
				size: size_val,
				startAngle: -Math.PI / 4 * 2,
				thickness: thickness_val,
				emptyFill: emptyFill_val,
				fill: fill_val
			}).on('circle-animation-progress', function(event, progress, stepValue) { // Rotate number when animating
				this_circle.find('.pbmit-circle-number').html(before + Math.round(stepValue * 100) + after);
			});
		}
		
		this_circle.waypoint(function(direction) {
			if (!this_circle.hasClass('completed')) {
				// Redraw when view
				if (typeof $.fn.circleProgress === "function") {
					$('.pbmit-circle', this_circle).circleProgress({ value: short_digit });
				};
				this_circle.addClass('completed');
			}
		}, { offset: '115%' });

	});
	
	/*-------------------------------------
   		Contact form validator
    -------------------------------------*/
    if ( $.isFunction($.fn.validate) ) {
		$("#contact-form").validate(); 
	} 
  
	/*-------------------------------------
		Send email via Ajax
		Make sure you configure send.php file 
	-------------------------------------*/
	$("#contact-form").submit(function(){

		if( $("#contact-form .doing-via-ajax").length == 0 ){
			$("#contact-form").prepend('<input class="doing-via-ajax" type="hidden" name="doing-via-ajax" value="yes" />');;
		}
	
		if( $("#contact-form").valid() ){  // check if form is valid
	
			$(".contact-form .message-status").html('');
			$('.form-btn-loader').removeClass('d-none');
			$('.contact-form button.pbmit-btn span:not(.form-btn-loader)').hide();
			$('.contact-form button.pbmit-btn').attr("disabled", "disabled");	
			$.ajax( {
			type: "POST",
			url: "send-dummy.php",
			data:$('#contact-form').serialize(),
			success: function(cevap) {					
				$('.form-btn-loader').addClass('d-none');
				$('.contact-form button.pbmit-btn span').show();
				$(".contact-form button.pbmit-btn").removeAttr("disabled");
				$(".contact-form .message-status").html(cevap);
			}
			});			
		}	
		return false;
	
	});
  
	/*-------------------------------------
		Masonry
	-------------------------------------*/
	  if (jQuery('.pbmit-element-viewtype-masonry').length > 0) {
		  jQuery('.pbmit-element-viewtype-masonry').each(function() {  
			  var main_ele = jQuery(this); 			
			  // init Masonry
			  let $grid = jQuery('.pbmit-element-posts-wrapper', main_ele).masonry({				  
				  itemSelector: '.pbmit-blog-style-1,.pbmit-portfolio-style-1',
				  columnWidth: '.pbmit-blog-style-1,.pbmit-portfolio-style-1',
				  gutter: 0,
				  percentPosition: true,
				  stagger: 30,
				  // nicer reveal transition
				  visibleStyle: { transform: 'translateY(0)', opacity: 1 },
				  hiddenStyle: { transform: 'translateY(100px)', opacity: 0 },
				  horizontalOrder: true
			  });
			  
		  }
	  )};  
})($);

   







document.addEventListener("DOMContentLoaded", () => {

    const gstPercentage = 18;

    const rows = document.querySelectorAll(".package-table tbody tr");

    const subtotalEl = document.getElementById("subtotal");
    const gstEl = document.getElementById("gst");
    const totalEl = document.getElementById("grandTotal");
    const summary = document.getElementById("selectedServices");
    const quoteBtn = document.getElementById("quoteBtn");

    /*=====================================
        Quantity Buttons
    =====================================*/
		
    document.querySelectorAll(".qty-plus").forEach(btn => {

        btn.addEventListener("click", function () {

            const input = this.parentElement.querySelector(".qty-input");

            input.value = parseInt(input.value) + 1;

            calculate();

        });

    });

    document.querySelectorAll(".qty-minus").forEach(btn => {

        btn.addEventListener("click", function () {

            const input = this.parentElement.querySelector(".qty-input");

            if (parseInt(input.value) > 1) {

                input.value = parseInt(input.value) - 1;

            }

            calculate();

        });

    });

    document.querySelectorAll(".qty-input").forEach(input => {

        input.addEventListener("input", function () {

            if (this.value == "" || this.value <= 0) {

                this.value = 1;

            }

            calculate();

        });

    });

    /*=====================================
        Checkbox Change
    =====================================*/

    document.querySelectorAll(".service-check").forEach(check => {

        check.addEventListener("change", calculate);

    });

    /*=====================================
        Drug Panel Dropdown
    =====================================*/

    document.querySelectorAll(".drug-select").forEach(select => {

        select.addEventListener("change", function () {

            const row = this.closest("tr");

            const priceCell = row.querySelector(".drug-price");

            if (this.value) {

                priceCell.innerHTML = "₹" + parseFloat(this.value).toFixed(2);

            } else {

                priceCell.innerHTML = "--";

            }

            calculate();

        });

    });

    /*=====================================
        Main Calculation
    =====================================*/

    function calculate() {

        let subtotal = 0;

        let html = "";

        rows.forEach(row => {

            const check = row.querySelector(".service-check");

            if (!check || !check.checked) return;

            const qty = parseInt(row.querySelector(".qty-input").value);

            let service = "";
            let price = 0;

            if (row.querySelector(".drug-select")) {

                const select = row.querySelector(".drug-select");

                if (!select.value) return;

                const option = select.selectedOptions[0];

                service = "Drug Test - " + option.text.split("-")[0].trim();

                price = parseFloat(option.value);

            }
            else {

                service = check.dataset.name;

                price = parseFloat(check.dataset.price);

            }

            const total = qty * price;

            subtotal += total;

            html += `
                <div class="service-row d-flex justify-content-between mb-2">
                    <div>
                        <strong>${service}</strong><br>
                        <small>${qty} × ₹${price.toFixed(2)}</small>
                    </div>
                    <div>
                        ₹${total.toFixed(2)}
                    </div>
                </div>
            `;

        });

        if (html === "") {

            html = `<p class="text-muted mb-0">No services selected.</p>`;

        }

        summary.innerHTML = html;

        const gst = subtotal * gstPercentage / 100;

        const grand = subtotal + gst;

        subtotalEl.innerHTML = "₹" + subtotal.toFixed(2);

        gstEl.innerHTML = "₹" + gst.toFixed(2);

        totalEl.innerHTML = "₹" + grand.toFixed(2);

    }

    calculate();

    /*=====================================
        Checkout Button
    =====================================*/

    quoteBtn.addEventListener("click", function (e) {

        e.preventDefault();

        let subtotal = parseFloat(subtotalEl.innerText.replace("₹", "")) || 0;

        let gst = parseFloat(gstEl.innerText.replace("₹", "")) || 0;

        let grand = parseFloat(totalEl.innerText.replace("₹", "")) || 0;

        if (subtotal <= 0) {

            alert("Please select at least one verification service.");

            return;

        }

        const packageData = {

            subtotal: subtotal,
            gst: gst,
            grandTotal: grand,
            services: []

        };

        rows.forEach(row => {

            const check = row.querySelector(".service-check");

            if (!check || !check.checked) return;

            const qty = parseInt(row.querySelector(".qty-input").value);

            let service = "";
            let price = 0;

            if (row.querySelector(".drug-select")) {

                const select = row.querySelector(".drug-select");

                if (!select.value) return;

                const option = select.selectedOptions[0];

                service = "Drug Test - " + option.text;

                price = parseFloat(option.value);

            }
            else {

                service = check.dataset.name;

                price = parseFloat(check.dataset.price);

            }

            packageData.services.push({

                service: service,
                qty: qty,
                price: price,
                total: qty * price

            });

        });

        localStorage.setItem(
            "verificationPackage",
            JSON.stringify(packageData)
        );

        window.location.href = "/custom_package_checkout";

    });

});





document.addEventListener("DOMContentLoaded", function () {

    const checkoutBtn = document.getElementById("checkoutBtn");

    if (!checkoutBtn) return;


    checkoutBtn.addEventListener("click", async function (e) {

        e.preventDefault();


        // --------------------------------
        // Get selected services
        // --------------------------------

        const selectedServices = [];

        document.querySelectorAll(".service-check:checked").forEach(function (checkbox) {

            const row = checkbox.closest("tr");

            const name = checkbox.dataset.name;
            const price = parseFloat(checkbox.dataset.price || 0);

            const quantityInput = row.querySelector(".qty-input");

            const quantity = quantityInput
                ? parseInt(quantityInput.value) || 1
                : 1;


            // Drug Test
            if (checkbox.classList.contains("drug-check")) {

                const drugSelect = row.querySelector(".drug-select");

                const drugPrice = parseFloat(drugSelect.value);

                const drugName =
                    "Drug Test - " +
                    drugSelect.options[drugSelect.selectedIndex].text;


                selectedServices.push({

                    name: drugName,
                    price: drugPrice,
                    quantity: quantity

                });

            } else {

                selectedServices.push({

                    name: name,
                    price: price,
                    quantity: quantity

                });

            }

        });


        // --------------------------------
        // No service selected
        // --------------------------------

        if (selectedServices.length === 0) {

            Swal.fire({

                icon: "warning",
                title: "No Service Selected",
                text: "Please select at least one verification service."

            });

            return;

        }


        // --------------------------------
        // Login Check + Prepare Checkout
        // --------------------------------

        try {

            const response = await fetch(
                "/prepare-checkout",
                {

                    method: "POST",

                    headers: {
                        "Content-Type": "application/json"
                    },

                    body: JSON.stringify({

                        services: selectedServices

                    })

                }
            );


            const data = await response.json();


            // --------------------------------
            // Not Logged In
            // --------------------------------

            if (response.status === 401) {

                Swal.fire({

                    icon: "warning",
                    title: "Login Required",
                    text: "Please login to continue with your verification package.",
                    confirmButtonText: "Login"

                }).then(() => {

                    window.location.href =
                        "/login?redirect=/makeown-package";

                });

                return;

            }


            // --------------------------------
            // Error
            // --------------------------------

            if (!data.status) {

                Swal.fire({

                    icon: "error",
                    title: "Unable to Continue",
                    text: data.message || "Something went wrong."

                });

                return;

            }


            // --------------------------------
            // Go Checkout
            // --------------------------------

            window.location.href =
                "/checkout";


        } catch (error) {

            console.error("Checkout Error:", error);

            Swal.fire({

                icon: "error",
                title: "Something went wrong",
                text: "Unable to proceed to checkout."

            });

        }

    });

});

