// source --> https://www.pricepropharmacy.com/wp-content/plugins/wp-pharmacywire-v5/Themes/js/common.js?ver=5.8.3 
// Description: Common JS for PharmacyWire, global App namespace
window.pwireApp = window.pwireApp || {}

pwireApp.dispatchPwireEvent = function (eventName, eventDetail) {
	// Inner function to dispatch the event
	function dispatchEvent() {
		const event = new CustomEvent(eventName, {
			detail: eventDetail,
			bubbles: true,
			cancelable: true
		})
		const target = document.querySelector('.pwire-event-manager')
		if (target) {
			target.dispatchEvent(event)
		} else {
			console.error('pwire-event-manager not found') // Error if the target isn't available in the DOM
		}
	}

	// Check if the DOM is fully loaded
	if (document.readyState === 'complete') {
		dispatchEvent()  // Dispatch immediately if the document is fully loaded
	} else {
		window.addEventListener('DOMContentLoaded', dispatchEvent)  // Wait for the DOM to be fully loaded
	}
}

// Function to add an event listener, single or space seperated event names
// similar to jQuery's .on() method
pwireApp.addListenerPwireEvent = function (eventName, callback) {
	var eventArray = eventName.split(' ')
	function readyAndListen() {
		const target = document.querySelector('.pwire-event-manager')
		if (target) {
			eventArray.forEach((eventN) => {
				target.addEventListener(eventN, callback)
			})
		} else {
			console.error('pwire-event-manager not found at the time of event attachment')
		}
	}

	if (document.readyState === 'loading') {  // If still loading
		document.addEventListener('DOMContentLoaded', readyAndListen)
	} else {  // `DOMContentLoaded` already fired
		readyAndListen()
	}
}

// Function to remove an event listener, single or space seperated event names
// similar to jQuery's .off() method
pwireApp.removeListenerPwireEvent = function (eventName, callback) {
	var eventArray = eventName.split(' ')
	function removeListener() {
		const target = document.querySelector('.pwire-event-manager')
		if (target) {
			eventArray.forEach((eventN) => {
				target.removeEventListener(eventN, callback)
			})
		} else {
			console.error('pwire-event-manager not found at the time of event removal')
		}
	}

	if (document.readyState === 'loading') {  // If still loading
		document.addEventListener('DOMContentLoaded', removeListener)
	} else {  // `DOMContentLoaded` already fired
		removeListener()
	}
}

document.addEventListener('DOMContentLoaded', function () {
	pwireApp.addListenerPwireEvent('pwire:account:userLogin', function (e) {
		document.body.classList.add('pwire-logged-in')
		document.body.classList.remove('pwire-logged-out')
		if (pw_session) {
			pw_session.logged_in = 'yes'
		}
	})

	pwireApp.addListenerPwireEvent('pwire:account:userLogout', function (e) {
		// Clear session and local storage on logout
		sessionStorage.clear()
		localStorage.clear()

		jQuery('.pw-login-block').addClass('pw-login-logged-out').removeClass('pw-login-logged-in')
		document.body.classList.add('pwire-logged-out')
		document.body.classList.remove('pwire-logged-in')
		if (pw_session) {
			pw_session.logged_in = 'no'
		}
	})
})

jQuery(($) => {
	// Check token status on ajax requests and act accordingly
	$(document).ajaxComplete((event, request) => {
		// Get the raw header string
		const headers = request.getAllResponseHeaders()

		// Convert the header string into an array
		// of individual headers
		const arr = headers.trim().split(/[\r\n]+/)

		// Create a map of header names to values
		const headerMap = {}
		arr.forEach((line) => {
			const parts = line.split(': ')
			const header = parts.shift()
			const value = parts.join(': ')
			headerMap[header] = value
		})
		const xPwireTokenStatus = request.getResponseHeader('x-pwire-token-status')
		const xPwireResetPassword = request.getResponseHeader('x-pwire-reset-password')

		if (xPwireTokenStatus === 'expired') {
			window.location.href = pw_json.logout_url
		} else if (xPwireResetPassword && (xPwireResetPassword === 'true')) {
			window.location.href = pw_json.login_url
		}
	})

	// *** TLDR; Redirect to login page if PHP session expired ***
	// Unlike the above PharmacyWire token status check, this is a PHP session check.
	//
	// If browser suggests the user is logged in (pw_session.logged_in),
	// set an interval check to confirm if still logged in (response.logged_in), 
	// if not (session expired) redirect to login page
	// eslint-disable-next-line no-unused-vars
	const checkLoginStatus = () => {
		setInterval(() => {
			// check pw_json.logged_in status to only check/redirect if user was logged in
			// it's a 'yes' or 'no' string
			if (typeof pw_session === 'undefined' || pw_session.logged_in === 'no') {
				return JSON.stringify({ status: 'success', logged_in: 0 }) // No need to check if not logged in
			}
			$.ajax({
				url: pw_json.request_url,
				data: {
					r: 'logged-in',
					'pw_nonce': pw_session.nonce,
				},
				type: 'POST',
				success: (data) => {
					try {
						const response = JSON.parse(data)
						if (response.logged_in === 0 && location.href !== pw_json.login_url && location.href !== pw_json.logout_url) {
							console.warn('Session expired, redirecting to login page...')
							window.location.replace(pw_json.logout_url)
						}
					} catch (error) {
						console.error('Error parsing login status:', error)
					}
				},
			})
		}, 180000) // every 3 minutes (milliseconds)
	}

	checkLoginStatus()

	// For tier pricing, setup proper product-id on the drug-row
	$('.pw-search-detail[data-tier-pricing="1"]').find('.drug-row.drug-package').each((index, elem) => {
		const drugPackage = $(elem)
		const selectedDrug = drugPackage.find('[name="drug-package-dropdown"] option:selected')
		drugPackage.attr('package-id', selectedDrug.attr('data-package-id'))
	})

	$('.pw-search-detail, .pw-reorder').on('click', '.add-drugpackage-to-cart', (ev) => {
		const $drugPackage = $(ev.target).closest('.drug-package')
		const $selectedTier = $drugPackage.find(':selected, :checked')
		ev.preventDefault()

		// If drug package exists and not using a custom add to cart event
		if (typeof $drugPackage !== 'undefined' && ($drugPackage.data('add-to-cart') !== 'custom-event')) {
			const packageId = $drugPackage.attr('data-package-id')
			const formId = $drugPackage.attr('data-form-id')
			const $selectedForm = $(`#frmDetail-${formId}`)
			const $objPackage = $(`#package-${formId}`)
			const $objQty = $(`#qty-${formId}`)
			$objPackage.val(packageId)

			// if tier pricing is on, and not a dropdown, make sure to setup tiered qty
			if ((parseInt($('.pw-search-detail').attr('data-tier-pricing'), 10) === 1) && !$drugPackage.hasClass('drug-dropdown')) {
				// find the related form and set the package-id and qty
				$selectedForm.find(`#package-${formId}`).val(packageId)
				$selectedForm.find(`#qty-${formId}`).val($drugPackage.data('tier-qty'))
				$selectedForm.find(`.drug-package-qty-${formId}`).val($drugPackage.data('tier-qty'))
			}

			// if there is a dropdown within the drug package for qty, use that
			// otherwise use the drug form qty for initial qty value
			const $qty = ($drugPackage.find('.drug-package-qty').length) ? $drugPackage.find('.drug-package-qty') : $selectedForm.find('.drug-package-qty')

			// original method, use value set when dropdown is switched etc.
			// originally done this way to support a separate qty dropdown and other implementations
			if ($qty && $qty.val() >= 1) {
				$objQty.val($qty.val())
				// new method, if selected input has tier qty set on it - use that
			} else if (!Number.isNaN(parseInt($selectedTier.attr('data-tier-qty'), 10))) {
				$objQty.val(parseInt($selectedTier.attr('data-tier-qty'), 10))
			} else {
				$objQty.val(1)
			}

			$selectedForm.trigger('submit')
		}
	})

	$('.pw-search-detail, .pw-reorder').on('change', '.drug-package-dropdown', (ev) => {
		try {
			if (parseInt($('.pw-search-detail').attr('data-tier-pricing') || '0', 10) === 1) {
				const $selectedTier = $(ev.target).find('option:selected')
				const $drugPackage = $(ev.target).closest('.drug-package')

				// Safely access data attributes with null checks
				const drugPackageId = $selectedTier.data('package-id')
				const formId = $selectedTier.data('form-id')

				if (!formId) {
					console.warn('Form ID not found for selected tier')
					return
				}

				$drugPackage.attr('package-id', drugPackageId || '')

				// Check if form exists before manipulating it
				const $selectedForm = $(`form#frmDetail-${formId}`)
				if ($selectedForm.length) {
					const $packageElement = $selectedForm.find(`#package-${formId}`)
					if ($packageElement.length) $packageElement.val(drugPackageId || '')

					const tierQty = $selectedTier.data('tier-qty')
					const $qtyElement = $selectedForm.find(`#qty-${formId}`)
					if ($qtyElement.length) $qtyElement.val(tierQty || 1)

					const $packageQtyElement = $selectedForm.find(`.drug-package-qty-${formId}`)
					if ($packageQtyElement.length) $packageQtyElement.val(tierQty || 1)
				}
			} else {
				const packageId = $(ev.target).val()
				$(ev.target).closest('.drug-package').attr('package-id', packageId || '')
			}
		} catch (error) {
			console.error('Error in drug package dropdown change:', error)
		}
	})

	// https://www.dropzonejs.com
	if ((typeof Dropzone !== 'undefined') && $('#prescriptionUpload').length && (typeof $('#prescriptionUpload')[0].dropzone != 'object')) {
		// eslint-disable-next-line no-unused-vars
		const prescriptionUploadDropzone = new Dropzone('#prescriptionUpload', {
			url: pw_json.upload_url,
			drop: () => {
				$('.upload-rx-response').removeClass('success error').html('')
			},
			init: function init() {
				this.on('success', (file, response) => {
					let msg = ''
					// handle pharmacywire response or dropzone response
					if (typeof response === 'object') {
						if (Object.prototype.hasOwnProperty.call(response, 'messages')) {
							msg = response.messages
						}
					} else {
						msg = response
					}
					$('.upload-rx-response').addClass('success').html(msg).fadeIn()
					pwireApp.dispatchPwireEvent('pwire:document:uploadcomplete')
					if ($('.pw-upload-document').length) {
						pwireApp.dispatchPwireEvent('pwire:document:uploadcomplete_frontend')
					}
					if ($('.checkout_form').length) {
						pwireApp.dispatchPwireEvent('pwire:document:uploadcomplete_checkout')
					}
				})
				this.on('error', (file, response) => {
					let msg = ''
					// handle pharmacywire response or dropzone response
					if (typeof response === 'object') {
						if (Object.prototype.hasOwnProperty.call(response, 'messages')) {
							msg = response.messages
						}
					} else {
						msg = response
					}
					$('.upload-rx-response').addClass('error').html(msg).fadeIn()
				})
			},
			dictDefaultMessage: '<i class="fa-solid fa-file-prescription"></i><i class="far fa-upload"></i><br />Click or drag Rx files here to upload',
			maxFilesize: 10, // MB
			acceptedFiles: 'image/*,application/pdf',
		})
	}
})

jQuery.fn.pwireSpinner = function pwireSpinner(spinOpt = {}) {
	const $this = jQuery(this)
	const topY = spinOpt.top || `${($this.outerHeight() / 2)}px`
	const leftX = spinOpt.left || `${($this.outerWidth() / 2)}px`
	const cssClass = spinOpt.classname || 'pwire-spinner'

	const opts = {
		lines: spinOpt.lines || 8, // The number of lines to draw
		length: spinOpt.length || 3, // The length of each line
		width: spinOpt.width || 8, // The line thickness
		radius: spinOpt.radius || 10, // The radius of the inner circle
		scale: spinOpt.scale || 1, // Scales overall size of the spinner
		corners: 1, // Corner roundness (0..1)
		color: spinOpt.color || '#787878', // CSS color or array of colors
		fadeColor: 'transparent', // CSS color or array of colors
		speed: 1, // Rounds per second
		rotate: 0, // The rotation offset
		animation: 'spinner-line-fade-quick', // The CSS animation name for the lines
		direction: 1, // 1: clockwise, -1: counterclockwise
		zIndex: 2e9, // The z-index (defaults to 2000000000)
		className: cssClass, // The CSS class to assign to the spinner
		top: topY, // Top position relative to parent
		left: leftX, // Left position relative to parent
		shadow: '0 0 1px transparent', // Box-shadow for the lines
		position: spinOpt.position || 'relative', // Element positioning
	}

	const response = {
		init: () => {
			if (!$this.find('.pwire-spinner').length) {
				$this.addClass(`${cssClass}-container`)
				// eslint-disable-next-line no-undef
				new Spin.Spinner(opts).spin($this.get(0))
			}
		},
		stop: () => {
			$this.find('> .pwire-spinner').remove()
			$this.removeClass(`${cssClass}-container`)
		},
	}

	response.init()

	return response
};
// source --> https://www.pricepropharmacy.com/wp-content/themes/pricepro-pharmacy/js/productimage.js?ver=41.67 
jQuery(document).ready(function() {


 

});
// source --> https://www.pricepropharmacy.com/wp-content/themes/pricepro-pharmacy/js/dynamic-content.js?ver=41.67 
(function($) {
	
	
	var dynamicContentUpdate = function() {
	
		var getData = [{ name: 'action', value: 'dynamic_content_update'}];

		var $mastHead = $('#masthead');
		var $myAccount = $mastHead.find('.my-account');
		var $login = $mastHead.find('.login');

		$.getJSON(
			'/wp-admin/admin-ajax.php',
			getData,
			function(data, textStatus, jqXHR) {
				if (data.success == 1) {
					
							  		

					$mastHead.find('.cart-count').text('(' + data.cart['item-count'] + ')');
				}
				
				
		    }
		);
	}

	
	jQuery(document).ready(function($){

		//dynamicContentUpdate();
		
		$("#pharmacy-wrap").on('pwire:cart:updateCartForm pwire:cart:removeLineItem', function () {
			dynamicContentUpdate();
		});

		$('#masthead .login[data-status=logged-in]').click(function(e) {
			e.preventDefault();		
			
			$.ajax({
				type: "POST",
				url: '/login/',
				data: { action: 'logout', logout: 'Logout' },
				success: function(data, textStatus, jqXHR) {
					window.location = '/';	
				},
				dataType: 'html'
			});
			
			
		});
		
		jQuery('.mobile-menu-only.signin').find('a').click(function(e) {
			
			var data_status = jQuery(this).attr('data-status');
			if(data_status == "logged-in") {
			e.preventDefault();		
			
			$.ajax({
				type: "POST",
				url: '/login/',
				data: { action: 'logout', logout: 'Logout' },
				success: function(data, textStatus, jqXHR) {
					window.location = '/';	
				},
				dataType: 'html'
			});
			
			}
		});
		
		var amountScrolled = 300;
	
		$(window).scroll(function() {
			if ( $(window).scrollTop() > amountScrolled ) {
				$('a.back-to-top').fadeIn('slow');
			} else {
				$('a.back-to-top').fadeOut('slow');
			}
		});
		
	});
		
})(jQuery);