<?php $this->load->view('includes/head') ?>
<?php $this->load->view('includes/topbar') ?>
<?php $this->load->view('includes/header') ?>
<!-- light box -->
<link href="<?= base_url('assets/css/lightbox.min.css'); ?>" rel="stylesheet" />
<script src="<?= base_url('assets/js/lightbox-plus-jquery.min.js'); ?>"></script>
<script type="text/javascript" src="<?= base_url('admin_assets/js/sweetalert2.all.min.js') ?>"></script>
<link href="<?= base_url('admin_assets/css/sweetalert2.min.css') ?>" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="<?= base_url('assets/css/services-cart.css') ?>">
<link rel="stylesheet" type="text/css" href="<?= base_url('assets/css/deities.css'); ?>">
<style>
	.search-container {
		position: relative;
		display: flex;
		align-items: center;
		margin-top: 1rem !important;
		/* margin-top: 4rem !important; */
	}

	.search-icon {
		cursor: pointer;
		font-size: 24px;
		padding: 10px;
	}

	.search-input {
		width: 0;
		padding: 0;
		/*opacity: 0;*/
		transition: all 0.3s ease;
		border: 1px solid #ccc;
	}

	.search-input.open {
		/* width: 200px; */
		padding: 5px 5px 5px 39px;
		opacity: 1;
	}

	#search_col {
		display: flex;
		align-items: center;
		justify-content: end;
	}

	@media only screen and (min-width: 992px) {
		.services-thumb {
			height: 120px !important;
			/* height: 90px !important; */
		}
	}

	.dropdown-container {
		position: relative;
		/* Positioning context for the dropdown */
		display: inline-block;
	}

	.dropdown-button {
		padding: 10px 20px;
		cursor: pointer;
		border: 1px solid #ccc;
	}

	.scrollable-dropdown {
		position: absolute;
		top: 100%;
		/* Opens below the button */
		left: 0;
		max-height: 200px;
		/* Adjust the height as needed */
		overflow-y: scroll;
		list-style-type: none;
		padding: 0;
		margin: 0;
		background-color: #fff;
		border: 1px solid #ccc;
		z-index: 1000;
		/* width: 100%; */
		width: fit-content;
		z-index: 9;
		background-color: #100837 !important;
	}

	/* Optional: Style scrollbar for WebKit browsers */
	.scrollable-dropdown::-webkit-scrollbar {
		width: 8px;
	}

	.scrollable-dropdown::-webkit-scrollbar-thumb {
		background-color: #888;
		border-radius: 4px;
	}

	.scrollable-dropdown::-webkit-scrollbar-thumb:hover {
		background-color: #555;
	}

	@media (max-width: 768px) {
		#ServicesByServiceEventTypeList {
			transform: translate3d(1px, 25px, 0px);
			overflow: scroll;
			max-width: 80vw;
		}

		#ServicesByServiceEventTypeList a {
			min-width: max-content !important;
			width: 102vw;
		}
	}

	@media (max-width: 1400px) and (min-width: 1200px) {
		.res-amount {
			margin-left: -40px !important;
		}
	}

	.datepicker-services::placeholder,
	.timepicker-services::placeholder {
		/* color: var(--main-color-new-theme) !important; */
		color: #000000 !important;
	}

	@media only screen and (max-width: 768px) {
		.col-md-12 i {
			display: block;
			text-align: center;
			margin-top: 5px !important;
			font-size: 1.5em;
		}
	}



	@media (max-width: 768px) {
		.mobile-sticky-cart-wrapper {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			z-index: 1040;
			background: white;
			padding: 10px 15px;
			box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
			border-top: 1px solid #ccc;
		}

		.mobile-sticky-cart-wrapper .paymentBtn {
			width: 100%;
			margin-top: 8px;
		}

		.mobile-sticky-cart-wrapper .price-span {
			font-size: 16px;
			margin-left: auto;
			font-weight: bold;
		}

		.mobile-sticky-cart-wrapper a i.fa-shopping-cart {
			font-size: 24px;
		}

		.mobile-sticky-cart-wrapper .cart-count {
			position: relative;
			top: -10px;
			left: -10px;
		}

		#gt_float_wrapper {
			display: none !important;
		}

		.mobileHide {
			display: none !important;
		}
	}

	#footer {
		display: none !important;
	}
	.modal {
    z-index: 1100 !important;
  }

  .modal-backdrop {
    z-index: 1090 !important;
  }

  #footer {
    display: none !important;
  }

  .back-to-top {
    display: none !important;
  }

  .iti--container {
    z-index: 9999 !important;
  }
  .anyamt::placeholder{
	color: #fff!important;
  }

  .row{
	margin-left: 0px!important;
	margin-right: 0px!important;
  }
@media (min-width: 1200px) {
	.anyamt {
		width: 80%!important;
	}
}
</style>
<main id="main">
	<!-- ======= Coming Soon ======= -->

	<section class="temple-services" style="background-image: url(<?= base_url('assets/img/bg-main-page.jpg') ?>);">

		<!-- ======================= -->

		<div class="row mb-0 pb-0" style="padding: 0px 50px;">

			<center class="mb-1">
				<h2 class="text-center mb-0" style="font-weight:bold!important;font-size: 30px!important;text-shadow: 1px 1px 5px #FA9D1E;">Sponsor Now</h2>
				<img src="<?= base_url('assets/img/border.png') ?>" width="30%" alt="Sponsor Now" style="height:auto!important;">

				<h3><?php
					$dietyTypes = '';
					$eventTypes = '';
					if (isset($_GET['e']) && !empty($_GET['e'])) {
						$eventTypes = urldecode($_GET['e']);
					}
					if (isset($_GET['d']) && !empty($_GET['d'])) {
						$dietyTypes = urldecode($_GET['d']);
					}
					echo !empty($dietyTypes) ? $dietyTypes : $eventTypes;
					?></h3>
			</center>

		</div>

		<!-- ======================= -->


		<?php
		$cartList = $this->session->userdata('sponsorship_cart');
		// echo '<pre>'; print_r($cartList);

		$cart_count = isset($cartList['ids']) && $cartList['ids'] ? count($cartList['ids']) : 0;
		$cart_count = $cart_count != '' ? $cart_count : 0;
		if (empty($cartList['ids'])) {
			$cartList = array('totalPrice' => 0.00, 'ids' => array());
		} else {
			if ($cartList['is_date_required'] == 'YES') {
				// code...
				$cartDetelists = array();
				$cartDetelistsCount = 0;

				foreach ($cartList['startDate'] as $key => $value) {
					$cartDetelistsCount = $cartDetelistsCount + (count(explode(',', $value)) * $cartList['qty'][$key]);
				}
				$cart_count = $cartDetelistsCount;
			} else {
				$cart_count = $cart_count != '' ? $cart_count : 0;
			}
		}

		$currencySymbol = getCurrencySymbol();
		$GeneralSettings = GeneralSettings();

		?>

		<div class="bg-image shadow-1-strong">
			<div class="row">
				<div class="col-md-12 mx-auto">
					<div class="row m-0 p-0">
						<div class="col-md-12" id="search_col">

							<!-- <div class="search-container">
								<span class="search-icon" id="searchIcon"><i class="fa fa-search" aria-hidden="true"></i></span>
								<input type="search" name="q" id="search" class="search-input search-text searchKey d-none" placeholder="Search..." autocomplete="off">
								<button class="search-btn" id="search-btn"><i class="fa fa-search" aria-hidden="true"></i></button>
							</div> -->


							<div class="d-flex justify-content-end align-items-end" style="border-bottom: 20px;">
								<div class="row px-0 mx-0">


									<div class="col-md-12">
										<div class="d-flex justify-content-end align-items-end" style="border-bottom: 20px;" id="RightField">
											<div class="text-white px-4">
												<div class="row mobileHide">
													<div class="col-md-9 text-start text-dark">
														<span class="fw-bold" style="padding-left: 34px;">Total Amount</span>
													</div>
												</div>

												<div style="display: flex;align-items: flex-end;" class="mobileHide">
													<span style="padding-right:6px!important">
														<a href="javascript:void(0)" onclick="ViewCart()"> <i class="fa fa-shopping-cart fa-2x" style="color:#000030;"></i>
															<span class="cart-count text-dark" style="font-size: 14px!important;"><?= $cart_count ?></span></a>
													</span>
													<label class="label label-primary price-span"><?= $currencySymbol != '' ? $currencySymbol : '$ '; ?> <span class="allPrice"><?= sprintf("%.2f", $cartList['totalPrice']); ?></span></label>



													<?php if ((isset($GeneralSettings['isMultipleSelect']) && $GeneralSettings['isMultipleSelect'] == 'YES')) { ?>

														<a href="javascript:void(0)" class="btn btn-success paymentBtn" onclick="CartCheckLogin('sponsorships')">

															<?php if ((isset($GeneralSettings['payNowText']) && $GeneralSettings['payNowText'] != '' && $GeneralSettings['payNowText'] != 'null')) {
																echo $GeneralSettings['payNowText'];
															} else {
																echo 'Proceed to Checkout';
															} ?>
														</a>
													<?php } else if (isset($GeneralSettings['isMultipleSelect']) && $GeneralSettings['isMultipleSelect'] == 'NO') { ?>

														<a href="javascript:void(0)" class="btn btn-success paymentBtn" onclick="CartCheckLogin('sponsorships')">

															<?php if ((isset($GeneralSettings['payLetterText']) && $GeneralSettings['payLetterText'] != '' && $GeneralSettings['payLetterText'] != 'null')) {
																echo $GeneralSettings['payLetterText'];
															} else {
																echo 'BOOK NOW';
															} ?>
														</a>

													<?php } else { ?>
														<a href="javascript:void(0)" class="btn btn-success paymentBtn" onclick="CartCheckLogin('sponsorships')">
															<?php if ((isset($GeneralSettings['payNowText']) && $GeneralSettings['payNowText'] != '' && $GeneralSettings['payNowText'] != 'null')) {
																echo $GeneralSettings['payNowText'];
															} else {
																echo 'Proceed To Checkout';
															} ?>
														</a>
													<?php } ?>

												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>




						<div class="justify-content-center align-items-center filter-tab px-2 mt-3" style="overflow:hidden">

							<!-- <div style="padding: 0px 50px;" id="Abc"> -->
							<div style="padding: 0px 10px;" id="Abc">
								<div class="responsive-container">
									<div class="tab-content  table-responsive mb-5" id="myTabContent">
										<?php

										echo getSponsorTypesServicesByServiceQR($cartList);

										?>
										<div id="emptyServices" style="padding: 4px 66px; font-size: 21px; font-weight: 700;">

										</div>
									</div>
								</div>
								<div class="mobile-sticky-cart-wrapper d-md-none">
									<div style="display: flex;align-items: flex-end; justify-content: space-between;width: 82%;">

										<span style="padding-right:6px!important;display:none;">
											<a href="javascript:void(0)" onclick="ViewCart()"> <i class="fa fa-shopping-cart fa-2x" style="color:#000030;"></i>
												<span class="cart-count text-dark" style="font-size: 14px!important;"><?= $cart_count ?></span></a>
										</span>
										<label class="label label-primary price-span"><?= $currencySymbol != '' ? $currencySymbol : '$ '; ?> <span class="allPrice"><?= sprintf("%.2f", $cartList['totalPrice']); ?></span></label>



										<?php if ((isset($GeneralSettings['isMultipleSelect']) && $GeneralSettings['isMultipleSelect'] == 'YES')) { ?>

											<a href="javascript:void(0)" class="btn btn-success paymentBtn" onclick="CartCheckLogin('sponsorships')">

												<?php if ((isset($GeneralSettings['payNowText']) && $GeneralSettings['payNowText'] != '' && $GeneralSettings['payNowText'] != 'null')) {
													echo $GeneralSettings['payNowText'];
												} else {
													echo 'Proceed to Checkout';
												} ?>
											</a>
										<?php } else if (isset($GeneralSettings['isMultipleSelect']) && $GeneralSettings['isMultipleSelect'] == 'NO') { ?>

											<a href="javascript:void(0)" class="btn btn-success paymentBtn" onclick="CartCheckLogin('sponsorships')">

												<?php if ((isset($GeneralSettings['payLetterText']) && $GeneralSettings['payLetterText'] != '' && $GeneralSettings['payLetterText'] != 'null')) {
													echo $GeneralSettings['payLetterText'];
												} else {
													echo 'BOOK NOW';
												} ?>
											</a>

										<?php } else { ?>
											<a href="javascript:void(0)" class="btn btn-success paymentBtn" onclick="CartCheckLogin('sponsorships')">
												<?php if ((isset($GeneralSettings['payNowText']) && $GeneralSettings['payNowText'] != '' && $GeneralSettings['payNowText'] != 'null')) {
													echo $GeneralSettings['payNowText'];
												} else {
													echo 'Proceed To Checkout';
												} ?>
											</a>
										<?php } ?>

									</div>
								</div>

							</div>


						</div>



					</div>
				</div>
			</div>
		</div>

	</section>



</main>

<input type="hidden" id="datesArray" value="">


<?php $this->load->view('includes/footer') ?>

<script type="text/javascript" src="<?= base_url('assets/js/paging.js'); ?>"></script>

<script src="https://cdn.jsdelivr.net/gh/dubrox/Multiple-Dates-Picker-for-jQuery-UI@master/jquery-ui.multidatespicker.js"></script>
<?php
$booking = getBookingTimes(); // ['startTime' => '09:00 AM', 'endTime' => '09:00 PM']
?>

<script type="text/javascript">
	$(document).ready(function() {

		var Page_limit = $("#pageLength").val();
		if (Page_limit > 20) {
			$('.servicesDataTable').paging({
				limit: Page_limit
			});
		}

		$("[data-page='0']").click();

		// TimePicker
		// $('.timepicker-services').mdtimepicker();
		// $('.timepicker-services').on('timechanged', function() {
		// 	// console.log("okkkkkk555454");
		// 	addTocart();
		// });

		function convertTo24Hour(timeStr) {
			const [time, meridian] = timeStr.split(" ");
			let [hours, minutes] = time.split(":").map(Number);
			if (meridian.toLowerCase() === 'pm' && hours !== 12) hours += 12;
			if (meridian.toLowerCase() === 'am' && hours === 12) hours = 0;
			return hours * 60 + minutes;
		}

		const bookingStartTime = "<?php echo $booking['startTime']; ?>"; // 09:00 AM
		const bookingEndTime = "<?php echo $booking['endTime']; ?>"; // 09:00 PM


		$('.timepicker-services').on('focus', function(e) {
			const id = $(this).attr('_id');
			// alert(id);
			const dateSelected = $('#datepicker_' + id).val();
			const isDTVisible = $(this).data('dt-visible');

			if (isDTVisible === 'YES' && (!dateSelected || dateSelected.trim() === '')) {
				$("#datepicker_" + id).notify("Please select a date first.", {
					position: "bottom",
					className: "error",
				});
				$(this).blur();
			} else {
				// Format selected date and today's date to compare
				const selectedDate = new Date(dateSelected);
				const today = new Date();

				const formatDate = (d) =>
					d.getFullYear() + '-' +
					String(d.getMonth() + 1).padStart(2, '0') + '-' +
					String(d.getDate()).padStart(2, '0');

				let timepickerOptions = {
					timeFormat: 'hh:mm tt',
					theme: 'blue',
					readOnly: true
				};

				const isToday = formatDate(selectedDate) === formatDate(today);

				if (isToday) {
					const now = new Date();
					const currentHour = now.getHours();
					const currentMinute = now.getMinutes();

					// Set min and max time for today
					timepickerOptions.minTime = `${String(currentHour).padStart(2, '0')}:${String(currentMinute).padStart(2, '0')}`;
					timepickerOptions.maxTime = `21:00`;
				} else {
					// For future date, only maxTime
					timepickerOptions.maxTime = `21:00`;
				}

				// Destroy any previous instance
				$('#timepicker_' + id).mdtimepicker('destroy');

				// Initialize again with new min/max
				$('#timepicker_' + id).mdtimepicker(timepickerOptions);

				// Bind timechanged
				$('#timepicker_' + id).off('timechanged').on('timechanged', function(e) {
					const selectedTime = e.time; // example: "02:30 PM" or maybe just "14:30"
					if (!selectedTime) return;

					let selectedHour = 0;
					let selectedMinute = 0;

					if (selectedTime.includes(" ")) {
						// 12-hour format with AM/PM
						let [time, meridian] = selectedTime.split(" ");
						let [hh, mm] = time.split(":");

						selectedHour = parseInt(hh);
						if (meridian.toLowerCase() === 'pm' && selectedHour !== 12) selectedHour += 12;
						if (meridian.toLowerCase() === 'am' && selectedHour === 12) selectedHour = 0;
						selectedMinute = parseInt(mm);
					} else {
						// 24-hour format fallback
						let [hh, mm] = selectedTime.split(":");
						selectedHour = parseInt(hh);
						selectedMinute = parseInt(mm);
					}

					const selectedTotalMinutes = selectedHour * 60 + selectedMinute;





					const minAllowedMinutes = convertTo24Hour(bookingStartTime); // e.g. "09:00 AM" => 540
					const maxAllowedMinutes = convertTo24Hour(bookingEndTime); // e.g. "09:00 PM" => 1260

					if (isToday) {
						const now = new Date();
						const currentMinutes = now.getHours() * 60 + now.getMinutes();

						// Must be after current time AND within allowed range
						if (
							selectedTotalMinutes <= currentMinutes ||
							selectedTotalMinutes < minAllowedMinutes ||
							selectedTotalMinutes > maxAllowedMinutes
						) {
							$("#timepicker_" + id).notify(`Please select a time between ${bookingStartTime} and ${bookingEndTime} that is after the current time.`, {
								position: "bottom",
								className: "error",
							});
							$('#timepicker_' + id).val('');
							return;
						}
					} else {
						// For future date: only check range
						console.log("bookingStartTime :" + maxAllowedMinutes);
						console.log("minAllowedMinutes :" + minAllowedMinutes);
						console.log("selectedTotalMinutes :" + selectedTotalMinutes);
						if (selectedTotalMinutes < minAllowedMinutes || selectedTotalMinutes > maxAllowedMinutes) {
							$("#timepicker_" + id).notify(`Please select a time between ${bookingStartTime} and ${bookingEndTime}.`, {
								position: "bottom",
								className: "error",
							});
							$('#timepicker_' + id).val('');
							return;
						}
					}


					// All good
					addTocart();
				});

			}


		});




		$("input[id^='datepicker_']").on('change', function() {
			const id = $(this).attr('id').split('_')[1];
			$('#timepicker_' + id).val('');
		});
	});

	$(document).ready(function() {
		/*$("#search").on("keyup", function() {
			var value = $(this).val().toLowerCase();
			var $tableRows = $(".serviceSearch");
			var noResults = true;

			$tableRows.filter(function() {
				var rowText = $(this).text().toLowerCase();
				var isMatch = rowText.indexOf(value) > -1;
				$(this).toggle(isMatch);
				if (isMatch) {
					noResults = false;
				}
			});

			if (noResults && value !== "") {
				$("#emptyServices").text("Sponsorship not found!").show();
			} else {
				$("#emptyServices").hide();
			}
		}).on("search", function() {
			if ($(this).val() === "") {
				$("#table tr").show();
				$("#emptyServices").hide();
			}
		});*/
		$(".search-btn").on("click", function() {
			// alert("okk");

			var value = $("#search").val().toLowerCase(); // Getting value from #search input
			var $tableRows = $(".serviceSearch");
			var noResults = true;

			$tableRows.filter(function() {
				var rowText = $(this).text().toLowerCase();
				var isMatch = rowText.indexOf(value) > -1;
				$(this).toggle(isMatch);
				if (isMatch) {
					noResults = false;
				}
			});

			if (noResults && value !== "") {
				$("#emptyServices").text("Service not found!").show();
			} else {
				$("#emptyServices").hide();
			}
		});

		$("#search").on("input", function() {
			if ($(this).val() === "") {
				$(".serviceSearch").show();
				$("#emptyServices").hide();
			}
		});
	});





	var tithiDates = [];

	function getDatesOfTithi(tithiVal) {
		$.ajax({
			type: "POST",
			url: "<?= base_url('SponsorNow/getThithiNext90Days'); ?>",
			data: {
				tithi: tithiVal
			},
			dataType: 'json',
			success: function(result) {
				tithiDates = result;

				$("#datesArray").val(tithiDates);
			}
		});
	}


	function getWeekdayOccurrence(date) {
		// Convert the date string to a Date object
		const dateObj = new Date(date);

		// Get the weekday (0 = Sunday, 1 = Monday, ..., 6 = Saturday)
		const weekday = dateObj.getDay();

		// Get the day of the month
		const dayOfMonth = dateObj.getDate();

		// Calculate the occurrence of the weekday in the month
		const occurrence = Math.ceil(dayOfMonth / 7);

		const weekdayNames = ['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY'];
		const occurrences = ['', 'FIRST', 'SECOND', 'THIRD', 'FOURTH', 'FIFTH', 'SIXTH'];

		return `${occurrences[occurrence]} ${weekdayNames[weekday]}`;
	}


	function getWeekday(date) {
		// Convert the date string to a Date object
		const dateObj = new Date(date);

		// Get the weekday (0 = Sunday, 1 = Monday, ..., 6 = Saturday)
		const weekday = dateObj.getDay();

		const weekdayNames = ['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY'];

		return weekdayNames[weekday];
	}



	$(document).on('click', '.datepicker-services', function() {
		var dayVal = $(this).attr('daytype');
		var nclickF = $(this);
		var startDate = nclickF.attr('start_date');
		var endDate = nclickF.attr('end_date');
		var _id = nclickF.attr('_id');
		var isDietySelected = nclickF.attr('data-isDietySelected');
		var dietyDayType = $("#dietyName_" + _id + " option:selected").data("daytype");
		var dietySelectedLength = $("#dietyName_" + _id + " option:selected").length;
		var dietyName = $("#dietyName_" + _id).val();
		console.log("dietyName: " + dietyName);
		console.log("dietyDayType: " + dietyDayType);
		console.log("dietySelectedLength: " + dietySelectedLength);
		console.log("isDietySelecteds: " + _id);
		if (isDietySelected == 'YES' && dayVal == '') {
			console.log("dietyDayType:fkghkf");
			console.log(dietyDayType != undefined && dietyDayType != null && dietySelectedLength);
			if (dietyDayType != undefined && dietyDayType != null && dietySelectedLength > 0) {
				dayVal = dietyDayType;
			} else {
				$("#dietyName_" + _id).notify(
					"Please select deity!", {
						position: "bottom",
						className: "error",
					}
				);
				return;
			}
		} else {
			if (isDietySelected == 'YES') {
				if (dietyDayType != undefined && dietyDayType != null && dietySelectedLength > 0) {

				} else {
					$("#dietyName_" + _id).notify(
						"Please select deity!", {
							position: "bottom",
							className: "error",
						}
					);
					return;
				}
			}
		}
		if (dayVal !== '' && dayVal != 'EVERY DAY' && dayVal != 'ALL DAY') {

			$.ajax({
				type: "POST",
				url: "<?= base_url('SponsorNow/getThithiNext90Days'); ?>",
				data: {
					tithi: dayVal
				},
				dataType: 'json',
				success: function(result) {
					$("#datesArray").val(result);



					if (dayVal !== '') {
						nclickF.notify(
							"You can select only " + dayVal + " dates!", {
								position: "top",
								className: "success",
							}
						);
					} else {
						nclickF.notify(
							"You can select any date!", {
								position: "top",
								className: "success",
							}
						);
					}


					if (!$(nclickF).hasClass('hasDatepicker')) {
						if (dayVal == '') {
							$(nclickF).multiDatesPicker({
								dateFormat: "mm/dd/yy",
								minDate: 0,
								changeMonth: true,
								changeYear: false,
								onSelect: function(dateText, inst) {
									$(this).multiDatesPicker('resetDates'); // Purana date hata dega
									$(this).multiDatesPicker('addDates', dateText);
									$(this).datepicker('show');
									addTocart();
								}
							});
						} else {

							$(nclickF).multiDatesPicker({
								dateFormat: "mm/dd/yy",
								minDate: 0,
								changeMonth: true,
								changeYear: false,
								onSelect: function(dateText, inst) {
									$(this).multiDatesPicker('resetDates'); // Purana date hata dega
									$(this).multiDatesPicker('addDates', dateText);
									$(this).datepicker('show');
									addTocart();
								},


								beforeShowDay: function(date) {
									var dayOfWeek = $.datepicker.formatDate('DD', date);
									var dateInMMDDYYFormat = $.datepicker.formatDate('yy-mm-dd', date);

									var tithis = ["PRATIPADA", "DWITIYA", "TRITIYA", "CHATURTHI", "PANCHAMI", "SHASHDI", "SAPTAMI", "ASHTAMI", "NAVAMI", "DASHAMI", "EKADASHI", "DWADASHI", "TRAYODASHI", "CHATURDASHI", "PURNIMA", "AMAVASYA"];
									var today = new Date();


									if (!dayVal || dayVal === '') {
										return [date >= today]; // Enable only dates from today onward
									} else if (dayOfWeek.toUpperCase() === dayVal.toUpperCase()) {
										// return [true];
										return [date >= today];
									} else if (tithis.includes(dayVal.toUpperCase())) {

										var tithiDates = $("#datesArray").val();




										var startDatearray = tithiDates.split(" ").pop().split(",");
										// return [startDatearray.includes(dateInMMDDYYFormat)];
										return [startDatearray.includes(dateInMMDDYYFormat) && date >= today];



									} else if (getWeekdayOccurrence(date) === dayVal.toUpperCase()) {
										// return [true];
										return [date >= today];
									} else {
										return [false];
									}
								}
							});
						}
					}

					$(nclickF).datepicker('show');

				}
			});
		} else {
			nclickF.notify(
				"You can select any date!", {
					position: "bottom",
					className: "success",
				}
			);
			if (!$(nclickF).hasClass('hasDatepicker')) {

				console.log("okkkkk567687");
				$(nclickF).multiDatesPicker({
					dateFormat: "mm/dd/yy",
					minDate: 0,
					changeMonth: true,
					changeYear: false,
					onSelect: function(dateText, inst) {
						$(this).multiDatesPicker('resetDates'); // Purana date hata dega
						$(this).multiDatesPicker('addDates', dateText);
						$(this).datepicker('show');
						addTocart();
					}
				});

			}



			$(nclickF).datepicker('show');
		}

	});



	$(document).on('click', '.datepicker-services1', function() {
		var dayVal = $(this).attr('daytype'); // Day type (e.g., "Tuesday")
		var nclickF = $(this);
		var startDate = nclickF.attr('start_date');
		var endDate = nclickF.attr('end_date');
		var _id = nclickF.attr('_id');
		var serviceOccurrencesNo = parseInt(nclickF.attr('serviceoccurrencesno'), 10); // Number of occurrences (e.g., 6)

		// Clear previously selected dates when opening the datepicker
		var selectedDates = []; // To store the selected dates
		var isDietySelected = nclickF.attr('data-isDietySelected');
		var dietyDayType = $("#dietyName_" + _id + " option:selected").data("daytype");
		var dietySelectedLength = $("#dietyName_" + _id + " option:selected").length;
		var dietyName = $("#dietyName_" + _id).val();
		console.log("dietyName: " + dietyName);
		console.log("dietyDayType: " + dietyDayType);
		console.log("dietySelectedLength: " + dietySelectedLength);
		console.log("isDietySelecteds: " + _id);
		if (isDietySelected == 'YES' && dayVal == '') {
			console.log("dietyDayType:fkghkf");
			console.log(dietyDayType != undefined && dietyDayType != null && dietySelectedLength);
			if (dietyDayType != undefined && dietyDayType != null && dietySelectedLength > 0) {
				dayVal = dietyDayType;
			} else {
				$("#dietyName_" + _id).notify(
					"Please select deity!", {
						position: "bottom",
						className: "error",
					}
				);
				return;
			}
		} else {
			if (isDietySelected == 'YES') {
				if (dietyDayType != undefined && dietyDayType != null && dietySelectedLength > 0) {

				} else {
					$("#dietyName_" + _id).notify(
						"Please select deity!", {
							position: "bottom",
							className: "error",
						}
					);
					return;
				}
			}
		}
		if (dayVal !== '' && dayVal != 'EVERY DAY' && dayVal != 'ALL DAY') {

			$.ajax({
				type: "POST",
				url: "<?= base_url('SponsorNow/getThithiNext90Days'); ?>",
				data: {
					tithi: dayVal,
					// startDate: startDate,
					// endDate: endDate
				},
				dataType: 'json',
				success: function(result) {
					$("#datesArray").val(result);
					console.log(dayVal);
					if (dayVal !== '') {
						nclickF.notify(
							"You can select only " + dayVal + " dates!", {
								position: "right",
								className: "success",
							}
						);
					} else {
						nclickF.notify(
							"You can select any date!", {
								position: "right",
								className: "success",
							}
						);
					}

					if (!$(nclickF).hasClass('hasDatepicker')) {
						if (dayVal == '') {
							$(nclickF).multiDatesPicker({
								dateFormat: "mm/dd/yy",
								minDate: 0,
								changeMonth: true,
								changeYear: false,
								onSelect: function(dateText, inst) {
									// Clear previously selected dates
									selectedDates = []; // Reset selected dates

									// Store the newly selected date
									selectedDates.push(dateText); // Add the selected date

									// Automatically select the next occurrences (e.g., Tuesdays)
									var firstDate = $(nclickF).datepicker('getDate'); // Get the selected date
									var tithis = ["PRATIPADA", "DWITIYA", "TRITIYA", "CHATURTHI", "PANCHAMI", "SHASHDI", "SAPTAMI", "ASHTAMI", "NAVAMI", "DASHAMI", "EKADASHI", "DWADASHI", "TRAYODASHI", "CHATURDASHI", "PURNIMA", "AMAVASYA"];
									var tithiDates = $("#datesArray").val();
									// Function to calculate next occurrences based on the dayType
									function getNextOccurrences(date, dayType, occurrences) {
										console.log(dayType);
										var nextDates = [];
										var count = 0; // To count valid occurrences

										var endLimitDate = new Date(date);
										endLimitDate.setFullYear(endLimitDate.getFullYear() + 2);
										console.log("endLimitDate: " + endLimitDate);
										console.log("date: " + date);
										while (count < occurrences && date <= endLimitDate) {
											// alert(dayType);
											date.setDate(date.getDate() + 1); // Move to the next day
											// alert($.datepicker.formatDate('DD', date).toUpperCase() === dayType.toUpperCase());
											if (dayType.length > 0) {
												if ($.datepicker.formatDate('DD', date).toUpperCase() === dayType.toUpperCase()) {
													nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
													count++; // Increment valid occurrence count
												} else if (tithis.includes(dayType.toUpperCase())) {
													var dateInMMDDYYFormat = $.datepicker.formatDate('yy-mm-dd', date);
													var startDateArray = tithiDates.split(" ").pop().split(",");
													if (startDateArray.includes(dateInMMDDYYFormat)) {
														console.log("djsghkjd" + startDateArray.includes(dateInMMDDYYFormat));
														nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
														count++;
													}

												} else if (getWeekdayOccurrence(date) === dayVal.toUpperCase()) {
													nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
													count++;
												}
											} else {
												nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
												count++;
											}


										}
										return nextDates;
									}

									// Get next occurrences based on the day type
									var nextDates = getNextOccurrences(new Date(firstDate), dayVal, serviceOccurrencesNo - 1);

									// Combine selected date with next occurrences
									selectedDates = [dateText].concat(nextDates); // Resetting to only the new selection and its occurrences
									var formattedDates = selectedDates.join(", ");
									// Clear the datepicker and add the new dates
									$(nclickF).datepicker('setDate', selectedDates[0]); // Set the datepicker to the newly selected date
									$(nclickF).multiDatesPicker('resetDates'); // Clear all previous selections
									$(nclickF).multiDatesPicker('addDates', formattedDates.split(", ")); // Add the new dates for multiDatesPicker compatibility

									// $(nclickF).val(formattedDates); // Update the input field with formatted dates
									var showDate = selectedDates[0] + ' - ' + selectedDates.at(-1);
									// $(nclickF).val(formattedDates); // Update the input field with formatted dates
									$(nclickF).val(showDate); // Update the input field with formatted dates
									$("#datepicker_" + _id).val(formattedDates); // Update the input field with formatted dates
									$("#datepickerCount_" + _id).html("( " + selectedDates.length + " Bookings )"); // Update the input field with formatted dates


									// Notify the user about the selected dates
									// nclickF.notify(
									// 	"Selected dates: " + formattedDates, {
									// 		position: "right",
									// 		className: "success",
									// 	}
									// );
									$("#datesArray").val(formattedDates);
									// Add all selected dates to the cart
									addTocart();

									// Disable further selections if the limit is reached
									if (selectedDates.length > serviceOccurrencesNo) {
										nclickF.notify(
											"You have reached the maximum number of selections! You can still change your selection.", {
												position: "bottom",
												className: "error",
											}
										);
									}
								}
							});
						} else {
							$(nclickF).datepicker({
								dateFormat: "mm/dd/yy",
								// minDate: parseDate(startDate),
								// maxDate: parseDate(endDate),
								minDate: 0,
								changeMonth: true,
								changeYear: false,
								onSelect: function(dateText, inst) {
									// Clear previously selected dates
									selectedDates = []; // Reset selected dates

									// Store the newly selected date
									selectedDates.push(dateText); // Add the selected date

									// Automatically select the next occurrences (e.g., Tuesdays)
									var firstDate = $(nclickF).datepicker('getDate'); // Get the selected date
									var tithis = ["PRATIPADA", "DWITIYA", "TRITIYA", "CHATURTHI", "PANCHAMI", "SHASHDI", "SAPTAMI", "ASHTAMI", "NAVAMI", "DASHAMI", "EKADASHI", "DWADASHI", "TRAYODASHI", "CHATURDASHI", "PURNIMA", "AMAVASYA"];
									var tithiDates = $("#datesArray").val();
									// Function to calculate next occurrences based on the dayType
									function getNextOccurrences(date, dayType, occurrences) {
										console.log(dayType);
										var nextDates = [];
										var count = 0; // To count valid occurrences
										var endLimitDate = new Date(date);
										endLimitDate.setFullYear(endLimitDate.getFullYear() + 2);
										console.log("endLimitDate: " + endLimitDate);
										console.log("date: " + date);
										while (count < occurrences && date <= endLimitDate) {
											// alert(dayType);
											console.log(count + ' - ' + dayType);
											date.setDate(date.getDate() + 1); // Move to the next day
											// alert($.datepicker.formatDate('DD', date).toUpperCase() === dayType.toUpperCase());
											if (dayType.length > 0) {
												if ($.datepicker.formatDate('DD', date).toUpperCase() === dayType.toUpperCase()) {
													nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
													count++; // Increment valid occurrence count
												} else if (tithis.includes(dayType.toUpperCase())) {
													console.log(tithis.includes(dayType.toUpperCase()));
													var dateInMMDDYYFormat = $.datepicker.formatDate('yy-mm-dd', date);
													console.log(dateInMMDDYYFormat);

													console.log(startDateArray);
													var startDateArray = tithiDates.split(" ").pop().split(",");
													console.log("djsghkjd" + startDateArray.includes(dateInMMDDYYFormat));
													if (startDateArray.includes(dateInMMDDYYFormat)) {
														console.log("djsghkjd" + startDateArray.includes(dateInMMDDYYFormat));
														nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
														count++;
													}

												} else if (getWeekdayOccurrence(date) === dayVal.toUpperCase()) {
													nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
													count++;
												}
											} else {
												nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
												count++;
											}


										}
										return nextDates;
									}

									// Get next occurrences based on the day type
									var nextDates = getNextOccurrences(new Date(firstDate), dayVal, serviceOccurrencesNo - 1);
									console.log(nextDates);
									// Combine selected date with next occurrences
									selectedDates = [dateText].concat(nextDates); // Resetting to only the new selection and its occurrences
									var formattedDates = selectedDates.join(", ");
									// Clear the datepicker and add the new dates
									$(nclickF).datepicker('setDate', selectedDates[0]); // Set the datepicker to the newly selected date
									$(nclickF).multiDatesPicker('resetDates'); // Clear all previous selections
									$(nclickF).multiDatesPicker('addDates', formattedDates.split(", ")); // Add the new dates for multiDatesPicker compatibility

									// $(nclickF).val(formattedDates); // Update the input field with formatted dates
									var showDate = selectedDates[0] + ' - ' + selectedDates.at(-1);
									// $(nclickF).val(formattedDates); // Update the input field with formatted dates
									$(nclickF).val(showDate); // Update the input field with formatted dates
									$("#datepicker_" + _id).val(formattedDates); // Update the input field with formatted dates
									$("#datepickerCount_" + _id).html("( " + selectedDates.length + " Bookings )"); // Update the input field with formatted dates


									// Notify the user about the selected dates
									// nclickF.notify(
									// 	"Selected dates: " + formattedDates, {
									// 		position: "right",
									// 		className: "success",
									// 	}
									// );
									$("#datesArray").val(formattedDates);
									// Add all selected dates to the cart
									addTocart();

									// Disable further selections if the limit is reached
									if (selectedDates.length > serviceOccurrencesNo) {
										nclickF.notify(
											"You have reached the maximum number of selections! You can still change your selection.", {
												position: "bottom",
												className: "error",
											}
										);
									}
								},
								beforeShowDay: function(date) {

									var dayOfWeek = $.datepicker.formatDate('DD', date);
									var dateInMMDDYYFormat = $.datepicker.formatDate('yy-mm-dd', date);
									var tithis = ["PRATIPADA", "DWITIYA", "TRITIYA", "CHATURTHI", "PANCHAMI", "SHASHDI", "SAPTAMI", "ASHTAMI", "NAVAMI", "DASHAMI", "EKADASHI", "DWADASHI", "TRAYODASHI", "CHATURDASHI", "PURNIMA", "AMAVASYA"];
									var today = new Date();
									if (!dayVal || dayVal === '') {
										return [date >= today]; // Enable only dates from today onward
									} else if (dayOfWeek.toUpperCase() === dayVal.toUpperCase()) {
										// return [true];
										return [date >= today];
									} else if (tithis.includes(dayVal.toUpperCase())) {
										var tithiDates = $("#datesArray").val();
										// console.log(tithiDates);
										var startDateArray = tithiDates.split(" ").pop().split(",");
										// console.log(startDateArray);
										// return [startDateArray.includes(dateInMMDDYYFormat)];
										return [startDateArray.includes(dateInMMDDYYFormat) && date >= today];
									} else if (getWeekdayOccurrence(date) === dayVal.toUpperCase()) {
										// return [true];
										return [date >= today];
									} else {
										return [false];
									}
								}
							});
						}
					}

					// Show the datepicker
					$(nclickF).datepicker('show');
				}
			});
		} else {
			nclickF.notify(
				"You can select any date!", {
					position: "bottom",
					className: "success",
				}
			);
			if (!$(nclickF).hasClass('hasDatepicker')) {
				$(nclickF).multiDatesPicker({
					dateFormat: "mm/dd/yy",
					minDate: 0,
					changeMonth: true,
					changeYear: false,
					onSelect: function(dateText, inst) {
						// Clear previously selected dates
						selectedDates = []; // Reset selected dates

						// Store the newly selected date
						selectedDates.push(dateText); // Add the selected date

						// Automatically select the next occurrences (e.g., Tuesdays)
						var firstDate = $(nclickF).datepicker('getDate'); // Get the selected date
						var tithis = ["PRATIPADA", "DWITIYA", "TRITIYA", "CHATURTHI", "PANCHAMI", "SHASHDI", "SAPTAMI", "ASHTAMI", "NAVAMI", "DASHAMI", "EKADASHI", "DWADASHI", "TRAYODASHI", "CHATURDASHI", "PURNIMA", "AMAVASYA"];
						var tithiDates = $("#datesArray").val();
						// Function to calculate next occurrences based on the dayType
						function getNextOccurrences(date, dayType, occurrences) {
							console.log(dayType);
							var nextDates = [];
							var count = 0; // To count valid occurrences
							while (count < occurrences) {
								// alert(dayType);
								date.setDate(date.getDate() + 1); // Move to the next day
								// alert($.datepicker.formatDate('DD', date).toUpperCase() === dayType.toUpperCase());
								if (dayType.length > 0) {
									if ($.datepicker.formatDate('DD', date).toUpperCase() === dayType.toUpperCase()) {
										nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
										count++; // Increment valid occurrence count
									} else if (tithis.includes(dayType.toUpperCase())) {
										var dateInMMDDYYFormat = $.datepicker.formatDate('yy-mm-dd', date);
										var startDateArray = tithiDates.split(" ").pop().split(",");
										if (startDateArray.includes(dateInMMDDYYFormat)) {
											nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
											count++;
										}

									} else if (getWeekdayOccurrence(date) === dayVal.toUpperCase()) {
										nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
										count++;
									}
								} else {
									nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
									count++;
								}


							}
							return nextDates;
						}

						// Get next occurrences based on the day type
						var nextDates = getNextOccurrences(new Date(firstDate), dayVal, serviceOccurrencesNo - 1);

						// Combine selected date with next occurrences
						selectedDates = [dateText].concat(nextDates); // Resetting to only the new selection and its occurrences
						var formattedDates = selectedDates.join(", ");
						// Clear the datepicker and add the new dates
						$(nclickF).datepicker('setDate', selectedDates[0]); // Set the datepicker to the newly selected date
						$(nclickF).multiDatesPicker('resetDates'); // Clear all previous selections
						$(nclickF).multiDatesPicker('addDates', formattedDates.split(", ")); // Add the new dates for multiDatesPicker compatibility

						// $(nclickF).val(formattedDates); // Update the input field with formatted dates
						var showDate = selectedDates[0] + ' - ' + selectedDates.at(-1);
						// $(nclickF).val(formattedDates); // Update the input field with formatted dates
						$(nclickF).val(showDate); // Update the input field with formatted dates
						$("#datepicker_" + _id).val(formattedDates); // Update the input field with formatted dates
						$("#datepickerCount_" + _id).html("( " + selectedDates.length + " Bookings )"); // Update the input field with formatted dates


						// Notify the user about the selected dates
						// nclickF.notify(
						// 	"Selected dates: " + formattedDates, {
						// 		position: "right",
						// 		className: "success",
						// 	}
						// );
						$("#datesArray").val(formattedDates);
						// Add all selected dates to the cart
						addTocart();

						// Disable further selections if the limit is reached
						if (selectedDates.length > serviceOccurrencesNo) {
							nclickF.notify(
								"You have reached the maximum number of selections! You can still change your selection.", {
									position: "bottom",
									className: "error",
								}
							);
						}
					}
				});

			}



			$(nclickF).datepicker('show');
		}
	});

	$(document).on('change', '[id^=dietyName_]', function() {
		var id = $(this).attr('id').split('_')[1]; // Get service ID
		var dayVal = $("#dietyName_" + id + " option:selected").data("daytype");

		// Reset datepicker field
		$('#datepicker_' + id).val('');

		// Uncheck the checkbox (remove from cart)
		$('input[data-id="' + id + '"]').prop('checked', false);




		var nclickF = $('#datepicker1_' + id);
		if (nclickF.length > 0) {

			var startDate = nclickF.attr('start_date');
			var endDate = nclickF.attr('end_date');
			var _id = nclickF.attr('_id');
			var serviceOccurrencesNo = parseInt(nclickF.attr('serviceoccurrencesno'), 10); // Number of occurrences (e.g., 6)



			$('#datepicker1_' + id).val('');
			$('#datepickerCount_' + id).html('');
			$('#datepicker1_' + id).multiDatesPicker('destroy');
			if (dayVal !== '' && dayVal != 'EVERY DAY' && dayVal != 'ALL DAY') {

				$.ajax({
					type: "POST",
					url: "<?= base_url('Services/getThithiNext90Days'); ?>",
					data: {
						tithi: dayVal,
						startDate: startDate,
						endDate: endDate
					},
					dataType: 'json',
					success: function(result) {
						$("#datesArray").val(result);
						console.log(dayVal);
						if (dayVal !== '') {
							nclickF.notify(
								"You can select only " + dayVal + " dates!", {
									position: "bottom",
									className: "success",
								}
							);
						} else {
							nclickF.notify(
								"You can select any date!", {
									position: "bottom",
									className: "success",
								}
							);
						}

						if (!$(nclickF).hasClass('hasDatepicker')) {
							if (dayVal == '') {
								console.log("okkkkk");
								$(nclickF).multiDatesPicker({
									dateFormat: "mm/dd/yy",
									minDate: 0,
									changeMonth: true,
									changeYear: false,
									onSelect: function(dateText, inst) {
										// Clear previously selected dates
										selectedDates = []; // Reset selected dates

										// Store the newly selected date
										selectedDates.push(dateText); // Add the selected date

										// Automatically select the next occurrences (e.g., Tuesdays)
										var firstDate = $(nclickF).datepicker('getDate'); // Get the selected date
										var tithis = ["PRATIPADA", "DWITIYA", "TRITIYA", "CHATURTHI", "PANCHAMI", "SHASHDI", "SAPTAMI", "ASHTAMI", "NAVAMI", "DASHAMI", "EKADASHI", "DWADASHI", "TRAYODASHI", "CHATURDASHI", "PURNIMA", "AMAVASYA"];
										var tithiDates = $("#datesArray").val();
										// Function to calculate next occurrences based on the dayType
										function getNextOccurrences(date, dayType, occurrences) {
											console.log(dayType);
											var nextDates = [];
											var count = 0; // To count valid occurrences
											// while (count < occurrences) {
											var endLimitDate = new Date(date);
											endLimitDate.setFullYear(endLimitDate.getFullYear() + 2);
											console.log("endLimitDate: " + endLimitDate);
											console.log("date: " + date);
											while (count < occurrences && date <= endLimitDate) {
												// alert(dayType);
												date.setDate(date.getDate() + 1); // Move to the next day
												// alert($.datepicker.formatDate('DD', date).toUpperCase() === dayType.toUpperCase());
												if (dayType.length > 0) {
													if ($.datepicker.formatDate('DD', date).toUpperCase() === dayType.toUpperCase()) {
														nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
														count++; // Increment valid occurrence count
													} else if (tithis.includes(dayType.toUpperCase())) {
														var dateInMMDDYYFormat = $.datepicker.formatDate('yy-mm-dd', date);
														var startDateArray = tithiDates.split(" ").pop().split(",");
														if (startDateArray.includes(dateInMMDDYYFormat)) {
															nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
															count++;
														}

													} else if (getWeekdayOccurrence(date) === dayVal.toUpperCase()) {
														nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
														count++;
													}
												} else {
													nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
													count++;
												}


											}
											return nextDates;
										}

										// Get next occurrences based on the day type
										var nextDates = getNextOccurrences(new Date(firstDate), dayVal, serviceOccurrencesNo - 1);

										// Combine selected date with next occurrences
										selectedDates = [dateText].concat(nextDates); // Resetting to only the new selection and its occurrences
										var formattedDates = selectedDates.join(", ");
										// Clear the datepicker and add the new dates
										$(nclickF).datepicker('setDate', selectedDates[0]); // Set the datepicker to the newly selected date
										$(nclickF).multiDatesPicker('resetDates'); // Clear all previous selections
										$(nclickF).multiDatesPicker('addDates', formattedDates.split(", ")); // Add the new dates for multiDatesPicker compatibility
										var showDate = selectedDates[0] + ' - ' + selectedDates.at(-1);
										// $(nclickF).val(formattedDates); // Update the input field with formatted dates
										$(nclickF).val(showDate); // Update the input field with formatted dates
										$("#datepicker_" + _id).val(formattedDates); // Update the input field with formatted dates
										$("#datepickerCount_" + _id).html("( " + selectedDates.length + " Bookings )"); // Update the input field with formatted dates


										// Notify the user about the selected dates
										/*nclickF.notify(
											"Selected dates: " + formattedDates, {
												position: "right",
												className: "success",
											}
										);*/
										$("#datesArray").val(formattedDates);
										// Add all selected dates to the cart
										addTocart();

										// Disable further selections if the limit is reached
										if (selectedDates.length > serviceOccurrencesNo) {
											nclickF.notify(
												"You have reached the maximum number of selections! You can still change your selection.", {
													position: "bottom",
													className: "error",
												}
											);
										}
									}
								});
							} else {
								$(nclickF).datepicker({
									dateFormat: "mm/dd/yy",
									minDate: parseDate(startDate),
									maxDate: parseDate(endDate),
									changeMonth: true,
									changeYear: false,
									onSelect: function(dateText, inst) {
										// Clear previously selected dates
										selectedDates = []; // Reset selected dates

										// Store the newly selected date
										selectedDates.push(dateText); // Add the selected date

										// Automatically select the next occurrences (e.g., Tuesdays)
										var firstDate = $(nclickF).datepicker('getDate'); // Get the selected date
										var tithis = ["PRATIPADA", "DWITIYA", "TRITIYA", "CHATURTHI", "PANCHAMI", "SHASHDI", "SAPTAMI", "ASHTAMI", "NAVAMI", "DASHAMI", "EKADASHI", "DWADASHI", "TRAYODASHI", "CHATURDASHI", "PURNIMA", "AMAVASYA"];
										var tithiDates = $("#datesArray").val();
										// Function to calculate next occurrences based on the dayType
										function getNextOccurrences(date, dayType, occurrences) {
											console.log(dayType);
											var nextDates = [];
											var count = 0; // To count valid occurrences
											// while (count < occurrences) {
											var endLimitDate = new Date(date);
											endLimitDate.setFullYear(endLimitDate.getFullYear() + 2);
											console.log("endLimitDate: " + endLimitDate);
											console.log("date: " + date);
											while (count < occurrences && date <= endLimitDate) {
												// alert(dayType);
												date.setDate(date.getDate() + 1); // Move to the next day
												// alert($.datepicker.formatDate('DD', date).toUpperCase() === dayType.toUpperCase());
												if (dayType.length > 0) {
													if ($.datepicker.formatDate('DD', date).toUpperCase() === dayType.toUpperCase()) {
														nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
														count++; // Increment valid occurrence count
													} else if (tithis.includes(dayType.toUpperCase())) {
														var dateInMMDDYYFormat = $.datepicker.formatDate('yy-mm-dd', date);
														var startDateArray = tithiDates.split(" ").pop().split(",");
														if (startDateArray.includes(dateInMMDDYYFormat)) {
															nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
															count++;
														}

													} else if (getWeekdayOccurrence(date) === dayVal.toUpperCase()) {
														nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
														count++;
													}
												} else {
													nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
													count++;
												}


											}
											return nextDates;
										}

										// Get next occurrences based on the day type
										var nextDates = getNextOccurrences(new Date(firstDate), dayVal, serviceOccurrencesNo - 1);

										// Combine selected date with next occurrences
										selectedDates = [dateText].concat(nextDates); // Resetting to only the new selection and its occurrences
										var formattedDates = selectedDates.join(", ");
										// Clear the datepicker and add the new dates
										$(nclickF).datepicker('setDate', selectedDates[0]); // Set the datepicker to the newly selected date
										$(nclickF).multiDatesPicker('resetDates'); // Clear all previous selections
										$(nclickF).multiDatesPicker('addDates', formattedDates.split(", ")); // Add the new dates for multiDatesPicker compatibility
										var showDate = selectedDates[0] + ' - ' + selectedDates.at(-1);
										// $(nclickF).val(formattedDates); // Update the input field with formatted dates
										$(nclickF).val(showDate); // Update the input field with formatted dates
										$("#datepicker_" + _id).val(formattedDates); // Update the input field with formatted dates
										$("#datepickerCount_" + _id).html("( " + selectedDates.length + " Bookings )"); // Update the input field with formatted dates


										// Notify the user about the selected dates
										/*nclickF.notify(
											"Selected dates: " + formattedDates, {
												position: "right",
												className: "success",
											}
										);*/
										$("#datesArray").val(formattedDates);
										// Add all selected dates to the cart
										addTocart();

										// Disable further selections if the limit is reached
										if (selectedDates.length > serviceOccurrencesNo) {
											nclickF.notify(
												"You have reached the maximum number of selections! You can still change your selection.", {
													position: "bottom",
													className: "error",
												}
											);
										}
									},
									beforeShowDay: function(date) {

										var dayOfWeek = $.datepicker.formatDate('DD', date);
										// console.log("dayVal: "+dayVal);
										// console.log("dayOfWeek: "+dayOfWeek);
										// 	console.log("dayOfWeek: "+ getWeekdayOccurrence(date));
										var dateInMMDDYYFormat = $.datepicker.formatDate('yy-mm-dd', date);
										var tithis = ["PRATIPADA", "DWITIYA", "TRITIYA", "CHATURTHI", "PANCHAMI", "SHASHDI", "SAPTAMI", "ASHTAMI", "NAVAMI", "DASHAMI", "EKADASHI", "DWADASHI", "TRAYODASHI", "CHATURDASHI", "PURNIMA", "AMAVASYA"];
										var today = new Date();
										// Allow selection only on the specified day or Tithi
										if (!dayVal || dayVal === '') {
											return [date >= today]; // Enable only dates from today onward
										} else if (dayOfWeek.toUpperCase() === dayVal.toUpperCase()) {
											// return [true];
											return [date >= today];
										} else if (tithis.includes(dayVal.toUpperCase())) {
											var tithiDates = $("#datesArray").val();
											var startDateArray = tithiDates.split(" ").pop().split(",");
											// return [startDateArray.includes(dateInMMDDYYFormat)];
											return [startDatearray.includes(dateInMMDDYYFormat) && date >= today];
										} else if (getWeekdayOccurrence(date) == dayVal.toUpperCase()) {


											return [date >= today];
										} else {
											return [false];
										}
									}
								});
							}
						}

						// Show the datepicker
						$(nclickF).datepicker('show');
					}
				});
			} else {
				nclickF.notify(
					"You can select any date!", {
						position: "bottom",
						className: "success",
					}
				);
				if (!$(nclickF).hasClass('hasDatepicker')) {

					console.log("okkkkk567687");
					$(nclickF).multiDatesPicker({
						dateFormat: "mm/dd/yy",
						minDate: 0,
						changeMonth: true,
						changeYear: false,
						onSelect: function(dateText, inst) {
							// Clear previously selected dates
							selectedDates = []; // Reset selected dates

							// Store the newly selected date
							selectedDates.push(dateText); // Add the selected date

							// Automatically select the next occurrences (e.g., Tuesdays)
							var firstDate = $(nclickF).datepicker('getDate'); // Get the selected date
							var tithis = ["PRATIPADA", "DWITIYA", "TRITIYA", "CHATURTHI", "PANCHAMI", "SHASHDI", "SAPTAMI", "ASHTAMI", "NAVAMI", "DASHAMI", "EKADASHI", "DWADASHI", "TRAYODASHI", "CHATURDASHI", "PURNIMA", "AMAVASYA"];
							var tithiDates = $("#datesArray").val();
							// Function to calculate next occurrences based on the dayType
							function getNextOccurrences(date, dayType, occurrences) {
								console.log(dayType);
								var nextDates = [];
								var count = 0; // To count valid occurrences
								while (count < occurrences) {
									// alert(dayType);
									date.setDate(date.getDate() + 1); // Move to the next day
									// alert($.datepicker.formatDate('DD', date).toUpperCase() === dayType.toUpperCase());
									if (dayType.length > 0) {
										if ($.datepicker.formatDate('DD', date).toUpperCase() === dayType.toUpperCase()) {
											nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
											count++; // Increment valid occurrence count
										} else if (tithis.includes(dayType.toUpperCase())) {
											var dateInMMDDYYFormat = $.datepicker.formatDate('yy-mm-dd', date);
											var startDateArray = tithiDates.split(" ").pop().split(",");
											if (startDateArray.includes(dateInMMDDYYFormat)) {
												nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
												count++;
											}

										} else if (getWeekdayOccurrence(date) === dayVal.toUpperCase()) {
											nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
											count++;
										}
									} else {
										nextDates.push($.datepicker.formatDate('mm/dd/yy', date)); // Format to mm/dd/yy
										count++;
									}


								}
								return nextDates;
							}

							// Get next occurrences based on the day type
							var nextDates = getNextOccurrences(new Date(firstDate), dayVal, serviceOccurrencesNo - 1);

							// Combine selected date with next occurrences
							selectedDates = [dateText].concat(nextDates); // Resetting to only the new selection and its occurrences
							var formattedDates = selectedDates.join(", ");
							// Clear the datepicker and add the new dates
							$(nclickF).datepicker('setDate', selectedDates[0]); // Set the datepicker to the newly selected date
							$(nclickF).multiDatesPicker('resetDates'); // Clear all previous selections
							$(nclickF).multiDatesPicker('addDates', formattedDates.split(", ")); // Add the new dates for multiDatesPicker compatibility
							var showDate = selectedDates[0] + ' - ' + selectedDates.at(-1);
							// $(nclickF).val(formattedDates); // Update the input field with formatted dates
							$(nclickF).val(showDate); // Update the input field with formatted dates
							$("#datepicker_" + _id).val(formattedDates); // Update the input field with formatted dates
							$("#datepickerCount_" + _id).html("( " + selectedDates.length + " Bookings )"); // Update the input field with formatted dates


							// Notify the user about the selected dates
							/*nclickF.notify(
								"Selected dates: " + formattedDates, {
									position: "right",
									className: "success",
								}
							);*/
							$("#datesArray").val(formattedDates);
							// Add all selected dates to the cart
							addTocart();

							// Disable further selections if the limit is reached
							if (selectedDates.length > serviceOccurrencesNo) {
								nclickF.notify(
									"You have reached the maximum number of selections! You can still change your selection.", {
										position: "bottom",
										className: "error",
									}
								);
							}
						}
					});

				}

			}
		} else {
			// Clear old datepicker instance if any
			$('#datepicker_' + id).multiDatesPicker('destroy');

			// Call calendar setup again with new dayVal (dayType)
			if (dayVal !== '' && dayVal !== 'EVERY DAY' && dayVal !== 'ALL DAY') {
				var startDate = $('#datepicker_' + id).attr('start_date');
				var endDate = $('#datepicker_' + id).attr('end_date');

				$.ajax({
					type: "POST",
					url: "<?= base_url('Services/getThithiNext90Days'); ?>",
					data: {
						tithi: dayVal,
						startDate: startDate,
						endDate: endDate
					},
					dataType: 'json',
					success: function(result) {
						$("#datesArray").val(result);

						$('#datepicker_' + id).multiDatesPicker({
							dateFormat: "mm/dd/yy",
							minDate: parseDate(startDate),
							maxDate: parseDate(endDate),
							changeMonth: true,
							changeYear: false,
							onSelect: function(dateText, inst) {
								$(this).multiDatesPicker('resetDates');
								$(this).multiDatesPicker('addDates', dateText);
								// $(this).datepicker('show');
								addTocart();
							},
							beforeShowDay: function(date) {
								var dayOfWeek = $.datepicker.formatDate('DD', date);
								var dateInMMDDYYFormat = $.datepicker.formatDate('yy-mm-dd', date);
								var today = new Date();
								var tithis = ["PRATIPADA", "DWITIYA", "TRITIYA", "CHATURTHI", "PANCHAMI", "SHASHDI", "SAPTAMI", "ASHTAMI", "NAVAMI", "DASHAMI", "EKADASHI", "DWADASHI", "TRAYODASHI", "CHATURDASHI", "PURNIMA", "AMAVASYA"];

								if (!dayVal || dayVal === '') {
									return [date >= today];
								} else if (dayOfWeek.toUpperCase() === dayVal.toUpperCase()) {
									return [date >= today];
								} else if (tithis.includes(dayVal.toUpperCase())) {
									var tithiDates = $("#datesArray").val();
									var startDatearray = tithiDates.split(" ").pop().split(",");
									return [startDatearray.includes(dateInMMDDYYFormat) && date >= today];
								} else if (getWeekdayOccurrence(date) == dayVal.toUpperCase()) {
									return [date >= today];
								} else {
									return [false];
								}
							}
						});

						// $('#datepicker_' + id).notify("Calendar updated as per deity", {
						//     position: "bottom",
						//     className: "info"
						// });
					}
				});
			} else {
				// If dayVal is empty or EVERY DAY, enable all future dates
				$('#datepicker_' + id).multiDatesPicker({
					dateFormat: "mm/dd/yy",
					minDate: 0,
					changeMonth: true,
					changeYear: false,
					onSelect: function(dateText, inst) {
						$(this).multiDatesPicker('resetDates');
						$(this).multiDatesPicker('addDates', dateText);
						// $(this).datepicker('show');
						addTocart();
					}
				});
			}
		}


	});

	function parseDate(dateString) {
		console.log(dateString);
		if (!dateString || typeof dateString !== 'string') {
			console.error('Invalid date string:', dateString);
			return null; // Or handle it as per your requirement
		}
		var parts = dateString.split('/');
		return new Date(parts[2], parts[0] - 1, parts[1]);
	}

	function clearCart() {

		$('input[name="sponsorships_id[]"]:checked').each(function() {
			$("input[name='sponsorships_id[]']").prop('checked', false);
		});

		if ($("input[name='allCheck']").is(":checked")) {
			$("input[name='allCheck']").prop('checked', false);
		}
		addTocart();

	}

	function addTocart() {

		var totalPrice = 0;
		var cart_type = 'SPONSORSHIP';
		var ids = [];
		var qty = [];
		var ctg = [];
		var serviceTypes = [];
		var serviceName = [];
		var startDate = [];
		var startTime = [];
		var serviceAmount = [];
		var description = [];
		var image = [];
		var cart_ctg = [];
		var is_date_required = [];

		var is_membership_discount = [];
		var membership_discount_amt = [];
		var noDateSelected = 0;
		var addtoCartStatus = true;
		var service_desc = [];
		var serviceOccurrencesNo = [];
		var fullPackage = [];
		var isDietySelected = [];
		var dietyName = [];
		var disclaimerText = [];


		$('input[name="sponsorships_id[]"]:checked').each(function() {
			id = $(this).attr('data-id');

			loader.on();


			var anyAmountCheck = parseFloat($("#anyAmtEvent" + id).val());
			var serviceoccurrencesno = parseFloat($(this).attr('data-serviceoccurrencesno'));

			if (anyAmountCheck < 0 || anyAmountCheck == 0) {
				$(this).attr('data-price', 0.00);
				$(this).prop('checked', false);
				$("#anyAmtEvent" + id).focus();
				$("#anyAmtEvent" + id).notify(
					"Entered Amount Must Be Greater Than 0!", {
						position: "top"
					}
				);
				addtoCartStatus = false;
				// return false;
			}


			if ($("#anyAmtEvent" + id).val() == '') {
				$(this).attr('data-price', 0.00);
				$(this).prop('checked', false);
				$("#anyAmtEvent" + id).focus();
				$("#anyAmtEvent" + id).notify(
					"Please Enter Any Amount!", {
						position: "top"
					}
				);

				addtoCartStatus = false;
				// return false;
			}



			// else if($("#timepicker_"+id).val().length == 0)
			// {
			// 	$("#timepicker_"+id).focus();
			// 	$(this).prop('checked', false);

			// 	$("#timepicker_"+id).notify(
			// 		"Please select time!",
			// 		{
			// 			position: "top"
			// 		}
			// 		);


			// 	addtoCartStatus = false;
			// 	return false;
			// }

			var init_qty = parseInt($("#quantity-input" + id).val());

			var isdietyselectedVal = $(this).attr('isdietyselected');
			if (isdietyselectedVal != 'YES') {
				isdietyselectedVal = 'NO';
			}
			console.log("isdietyselectedVal: " + isdietyselectedVal);
			isDietySelected.push(isdietyselectedVal);
			if (isdietyselectedVal == 'YES') {

				var selectedValue = $("#dietyName_" + id).val();
				console.log("selectedValue: " + selectedValue);
				console.log(selectedValue == "");
				if (selectedValue == "" || selectedValue == null || selectedValue == undefined) {
					$("#dietyName_" + id).focus();
					$(this).prop('checked', false);

					$("#dietyName_" + id).notify(
						"Please select diety!", {
							position: "top"
						}
					);


					addtoCartStatus = false;
					return false;
				} else {
					dietyName.push(selectedValue);
				}
			} else {
				dietyName.push('');
			}


			if ($(this).attr('is_date_required') == 'YES') {

				if ($("#datepicker_" + id).val().length == 0) {
					$(this).prop('checked', false);
					$("#datepicker_" + id).focus();
					$("#datepicker_" + id).notify(
						"Please select date!", {
							position: "top"
						}
					);

					var dayVal = $("#datepicker_" + id).attr('daytype');
					var nclickF = $("#datepicker_" + id);

					$.ajax({
						type: "POST",
						url: "<?= base_url('SponsorNow/getThithiNext90Days'); ?>",
						data: {
							tithi: dayVal
						},
						dataType: 'json',
						success: function(result) {
							$("#datesArray").val(result);



							if (dayVal !== '') {
								nclickF.notify(
									"You can select only " + dayVal + " dates!", {
										position: "top",
										className: "success",
									}
								);
							} else {
								nclickF.notify(
									"You can select any date!", {
										position: "top",
										className: "success",
									}
								);
							}


							if (!$(nclickF).hasClass('hasDatepicker')) {
								if (dayVal == '') {
									$(nclickF).multiDatesPicker({
										dateFormat: "mm/dd/yy",
										minDate: 0,
										changeMonth: true,
										changeYear: false,
										onSelect: function(dateText, inst) {
											$(this).datepicker('show');
											addTocart();
										}
									});
								} else {

									$(nclickF).multiDatesPicker({
										dateFormat: "mm/dd/yy",
										minDate: 0,
										changeMonth: true,
										changeYear: false,
										onSelect: function(dateText, inst) {
											$(this).datepicker('show');
											addTocart();
										},


										beforeShowDay: function(date) {
											var dayOfWeek = $.datepicker.formatDate('DD', date);
											var dateInMMDDYYFormat = $.datepicker.formatDate('yy-mm-dd', date);

											var tithis = ["PRATIPADA", "DWITIYA", "TRITIYA", "CHATURTHI", "PANCHAMI", "SHASHDI", "SAPTAMI", "ASHTAMI", "NAVAMI", "DASHAMI", "EKADASHI", "DWADASHI", "TRAYODASHI", "CHATURDASHI", "PURNIMA", "AMAVASYA"];
											var today = new Date();


											if (!dayVal || dayVal === '') {
												return [date >= today]; // Enable only dates from today onward
											} else if (dayOfWeek.toUpperCase() === dayVal.toUpperCase()) {
												// return [true];
												return [date >= today];
											} else if (tithis.includes(dayVal.toUpperCase())) {

												var tithiDates = $("#datesArray").val();




												var startDatearray = tithiDates.split(" ").pop().split(",");
												// return [startDatearray.includes(dateInMMDDYYFormat)];
												return [startDatearray.includes(dateInMMDDYYFormat) && date >= today];



											} else if (getWeekdayOccurrence(date) === dayVal.toUpperCase()) {
												// return [true];
												return [date >= today];
											} else {
												return [false];
											}
										}
									});
								}
							}

							$(nclickF).datepicker('show');

						}
					});

					addtoCartStatus = false;
					return false;
				}

				startDate.push($("#datepicker_" + id).val());
				console.log($("#datepicker_" + id).val());
				var dateArray = startDate[0].split(', ');
				var count = dateArray.length;
				var nDateSelectCount = ($("#datepicker_" + id).val()).split(', ');
				nDateSelectCount = nDateSelectCount.length;

				init_qty = (init_qty ? parseInt(init_qty) : 1);
				noDateSelected = noDateSelected + (nDateSelectCount * init_qty);

				if (serviceoccurrencesno) {
					serviceoccurrencesno = nDateSelectCount;
					totalPrice = (parseFloat(totalPrice) + ((parseFloat($(this).attr('data-price')) * init_qty)));
					$("#Totalprice_" + $(this).attr('data-id')).html("<?= $currencySymbol; ?>&nbsp;" + (parseFloat($(this).attr('data-price')) * init_qty).toFixed(2));

				} else {
					totalPrice = (parseFloat(totalPrice) + ((parseFloat($(this).attr('data-price')) * init_qty) * nDateSelectCount));
					$("#Totalprice_" + $(this).attr('data-id')).html("<?= $currencySymbol; ?>&nbsp;" + (parseFloat($(this).attr('data-price')) * init_qty * nDateSelectCount).toFixed(2));

				}


				// $("#Totalprice_" + $(this).attr('data-id')).html("<?= $currencySymbol; ?>&nbsp;" + ((parseFloat($(this).attr('data-price')) * init_qty) * nDateSelectCount) + ".00");
			} else {

				init_qty = (init_qty ? parseInt(init_qty) : 1);
				totalPrice = (parseFloat(totalPrice) + (parseFloat($(this).attr('data-price')) * init_qty));

				$("#Totalprice_" + $(this).attr('data-id')).html("<?= $currencySymbol; ?>&nbsp;" + (parseFloat($(this).attr('data-price')) * init_qty) + ".00");
				startDate.push('');

			}




			let time = $("#timepicker_" + id).val();
			let formattedTime = $("#timepicker_" + id).val();
			if (time) {
				let newTimeArr = time.split(':');
				if (newTimeArr) {
					formattedTime = formatTime(newTimeArr[0], newTimeArr[1]);
				}
			}

			function formatTime(hour, minute) {
				// Convert hour to two digits
				const formattedHour = String(hour).padStart(2, '0');
				// Convert minute to two digits
				const formattedMinute = String(minute).padStart(2, '0');

				return `${formattedHour}:${formattedMinute}`;
			}

			if (time) {
				startTime.push(formattedTime);
			} else {
				startTime.push("");
			}



			ctg.push($(this).attr('data-category'));
			serviceTypes.push($(this).attr('data-service-type'));
			serviceName.push($(this).attr('data-service-name'));
			image.push($(this).attr('data-image'));
			is_membership_discount.push($(this).attr('is_membership_discount'));
			membership_discount_amt.push($(this).attr('membership_discount_amt'));
			disclaimerText.push($(this).attr('disclaimerText'));

			description.push($(this).attr('data-description').replace(/['"`]/g, ''));
			cart_ctg.push($(this).attr('cart_category'));
			// serviceAmount.push($(this).attr('data-price'));
			if (serviceoccurrencesno) {
				// serviceAmount.push(parseFloat(parseFloat($(this).attr('data-price'))/serviceoccurrencesno).toFixed(2));
				fullPackage.push('true');
				serviceAmount.push(parseFloat(parseFloat($(this).attr('data-price')) / serviceoccurrencesno));
				// console.log($(this).attr('data-service-name'));
				// console.log(parseFloat($(this).attr('data-price')) / serviceoccurrencesno);
			} else {
				fullPackage.push('false');
				serviceAmount.push($(this).attr('data-price'));
			}
			// console.log(serviceoccurrencesno);
			ids.push($(this).attr('data-id'));
			qty.push(init_qty);
			service_desc.push($(this).attr('data-servicedesc'));
			is_date_required.push($(this).attr('is_date_required'));
			// serviceOccurrencesNo.push($(this).attr('data-serviceOccurrencesNo'));
			serviceOccurrencesNo.push(isNaN(serviceoccurrencesno) ? '' : serviceoccurrencesno);



		});


		if (addtoCartStatus == false) {
			loader.off();
			return false;
		} else {
			if ($(this).attr('is_date_required') == 'YES') {

				$(".cart-count").text(noDateSelected);
			} else {
				// $(".cart-count").text(ids.length);
			}
			// $(".allPrice").text((totalPrice / 1).toFixed(2));
		}

		$.ajax({
			type: "POST",
			url: "<?= base_url('SponsorNow/addCart'); ?>",
			data: {
				ids: ids,
				totalPrice: totalPrice,
				qty: qty,
				ctg: ctg,
				serviceTypes: serviceTypes,
				serviceName: serviceName,
				startDate: startDate,
				startTime: startTime,
				serviceAmount: serviceAmount,
				cart_type: cart_type,
				image: image,
				description: description,
				cart_ctg: cart_ctg,
				is_date_required: is_date_required,
				service_desc: service_desc,
				serviceOccurrencesNo: serviceOccurrencesNo,
				is_membership_discount: is_membership_discount,
				membership_discount_amt: membership_discount_amt,
				fullPackage: fullPackage,
				dietyName: dietyName,
				isDietySelected: isDietySelected,
				disclaimerText: disclaimerText,
				defaultServiceTypes: "<?= $this->uri->segment('2') ?>"
			},
			success: function(result) {

				console.log(result);
				var parsedResult = JSON.parse(result);
				console.log("result.totalPrice");
				console.log(parsedResult.totalPrice);
				if (parsedResult.status == "1") {
					var totalPrice1 = parsedResult.totalPrice;
					console.log("Total Price:", totalPrice1); // Print to console
					$(".allPrice").text((totalPrice1 / 1).toFixed(2));
				} else {
					$(".allPrice").text((totalPrice / 1).toFixed(2));
				}

				loader.off();
				updateCartCount();
			}
		});


	}


	function quantityMinusFunction(id) {

		var totalPrice = 0;
		var init_qty = parseInt($('#quantity-input' + id).val());
		if (init_qty > 1) {
			init_qty = init_qty ? parseInt(init_qty) - 1 : 0;

			$('#quantity-input' + id).val(init_qty);
		}

		addTocart();
	}

	function quantityPlusFunction(id) {
		var totalPrice = 0;
		var init_qty = parseInt($('#quantity-input' + id).val());


		init_qty = init_qty ? parseInt(init_qty) + 1 : 0;
		$('#quantity-input' + id).val(init_qty);
		addTocart();

	}


	function ViewCart() {
		// if ($(".cart-count").text() > 0) {
		// 	window.location.href = "<?= base_url('SponsorNow/ViewCart') ?>";

		// } else {
		// 	swal({
		// 		title: "Your cart is empty!",
		// 		text: "Please add some items to your cart.",
		// 		icon: "warning",
		// 		confirmButtonText: 'OK',
		// 		confirmButtonColor: 'var(--main-color-new-theme)',
		// 	});


		// }

	}

	function CartCheckLogin(page) {

		if ($(".cart-count").text() > 0) {
			loader.on();

			var page_name = page;
			event.preventDefault();
			$.ajax({
				url: "<?= base_url('check-login-status') ?>",
				type: "POST",
				dataType: "json",
				success: function(data) {
					loader.off();

					if (data == 0) {
						openLoginModal(page_name);
					} else {

						window.location.href = "<?= base_url('checkout/sponsorship') ?>";

					}

				}
			});

		} else {
			swal({
				title: "Your cart is empty!",
				text: "Please add some items to your cart.",
				icon: "warning",
				confirmButtonText: 'OK',
				confirmButtonColor: 'var(--main-color-new-theme)',
			});


		}
	}



	$(document).ready(function() {
		$('.price_types').change(function() {
			var selectedValue = parseFloat($(this).val()).toFixed(2);

			var id = $(this).attr('id');

			var selectedOption = $(this).find('option:selected');

			var key = selectedOption.attr('key');

			var spanId = "Totalprice_" + id;

			var checkboxId = "checkbox_" + id;

			$("#" + spanId).text('$ ' + selectedValue);
			$("#" + checkboxId).attr('data-price', selectedValue);
			$("#" + checkboxId).attr('data-servicedesc', key);


			addTocart();
		});
	});
</script>
<script type="text/javascript">
	// Get all Accordion and Panel

	$(function() {
		let accHeading = document.querySelectorAll(".accordion");
		let accPanel = document.querySelectorAll(".accordion-panel");

		// alert('dd');
		for (let i = 0; i < accHeading.length; i++) {
			// Execute whenever an accordion is clicked
			accHeading[i].onclick = function() {
				if (this.nextElementSibling.style.maxHeight) {
					hidePanels(); // Hide All open Panels
				} else {
					showPanel(this); // Show the panel
				}
			};
		}



		// Function to Show a Panel
		function showPanel(elem) {
			hidePanels();
			elem.classList.add("active");
			elem.classList.add("minus-sign");
			elem.nextElementSibling.style.maxHeight = elem.nextElementSibling.scrollHeight + "px";
		}

		// Function to Hide all shown Panels
		function hidePanels() {
			for (let i = 0; i < accPanel.length; i++) {
				accPanel[i].style.maxHeight = null;
				accHeading[i].classList.remove("active");
				accHeading[i].classList.remove("minus-sign");
			}
		}
	});


	$(document).ready(function() {
		$(".accordionFirst").click();

		window.scrollTo({
			top: 225,
			behavior: 'smooth'
		});

	});

	$(document).ready(function() {
		$("#searchIcon").click(function() {
			$("#search").toggleClass("d-none");

			if ($("#search").hasClass("d-none")) {
				$("#searchIcon").html("<i class='fa fa-search' aria-hidden='true'></i>");
				$(".search-btn").css("background", "var(--main-color-new-theme)");
				$(".search-btn").css("display", "none");
				$(".search-btn").css("position", "relative");
				$(".search-btn").css("left", "-40px");
				$(".search-btn").css("z-index", "9");
				$(".search-btn").css("border-radius", "0px 30px 30px 0px");
				$(".search-btn").css("height", "40px");
				$("#search").val('');
				$(".serviceSearch").show();
				if ($(window).width() < 768) {
					$(".search-container").css("order", "1"); // Moves first div to second position
					$(".d-flex.justify-content-end").css("order", "2");
					$("#search_col").css("display", "flex");
				}
			} else {
				$("#searchIcon").html("<i class='fa fa-times' aria-hidden='true'></i>");
				$(".search-btn").css("background", "var(--main-color-new-theme)");
				$(".search-btn").css("display", "block");
				$(".search-btn").css("position", "relative");
				$(".search-btn").css("left", "-40px");
				$(".search-btn").css("z-index", "9");
				$(".search-btn").css("border-radius", "0px 30px 30px 0px");
				$(".search-btn").css("height", "40px");
				if ($(window).width() < 768) {
					$(".search-container").css("order", "2"); // Moves first div to second position
					$(".d-flex.justify-content-end").css("order", "1");
					$("#search_col").css("display", "flow");
				}
			}
		});
	});
</script>

<?php $this->load->view('includes/script') ?>