<?php $this->load->view('includes/head') ?>
<?php $this->load->view('includes/topbar') ?>
<?php $this->load->view('includes/header') ?>
<link rel="stylesheet" type="text/css" href="<?= base_url('assets/css/services-cart.css') ?>">
<?php
$cartList = $this->session->userdata('events_cart');
if (isset($cartList['includeSankalpam'])) {
	$includeSankalpam = checkForYesValue($cartList['includeSankalpam']);
} else {

	$includeSankalpam = 'NO';
}
$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());
}
$currencySymbol = getCurrencySymbol();
$GeneralSettings = GeneralSettings();
?>
<style type="text/css">
	:root {
		--main-color-new-theme: #76020f;
	}

	input::placeholder {
		color: var(--main-color-new-theme) !important;
		font-size: 13px !important;
	}

	.anyamt {
		color: white !important;
		font-size: 13px !important;
	}

	p,
	span {
		font-size: 16px !important;
	}

	h6 {
		font-size: 18px !important;
	}

	label {
		font-size: 23px !important;
	}

	pre {
		font-size: 16px !important;
	}

	input.search-text {
		color: #222;
		position: relative;
		z-index: 5;
		transition: z-index 0.8s, width 0.5s, background 0.3s ease, border 0.3s;
		height: 39px;
		width: 0;
		margin: 0;
		padding: 5px 0 5px 38px;
		box-sizing: border-box;
		font-size: 16px;
		font-size: 1rem;
		cursor: pointer;
		border-radius: 30px;
		border: 1px solid transparent;
		/*background: url(search.png) no-repeat left 9px center transparent;*/
		background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDUxMiA1MTIiIGhlaWdodD0iNTEycHgiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCA1MTIgNTEyIiB3aWR0aD0iNTEycHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGQ9Ik01MDMuODY2LDQ3Ny45NzRMMzYwLjk1OCwzMzUuMDUyYzI4LjcyNS0zNC41NDQsNDYuMDE3LTc4LjkxMiw0Ni4wMTctMTI3LjMzNiAgYzAtMTEwLjA4NC04OS4yMjctMTk5LjMxMi0xOTkuMzEyLTE5OS4zMTJDOTcuNTk5LDguNDAzLDguMzUxLDk3LjYzMSw4LjM1MSwyMDcuNzE1YzAsMTEwLjA2NCw4OS4yNDgsMTk5LjMxMiwxOTkuMzEyLDE5OS4zMTIgIGM0OC40MzUsMCw5Mi43OTItMTcuMjkyLDEyNy4zMzYtNDYuMDE3bDE0Mi45MDgsMTQyLjkyMkw1MDMuODY2LDQ3Ny45NzR6IE0yOS4zMzEsMjA3LjcxNWMwLTk4LjMzNCw3OS45ODctMTc4LjMzMiwxNzguMzMyLTE3OC4zMzIgIGM5OC4zMjUsMCwxNzguMzMyLDc5Ljk5OCwxNzguMzMyLDE3OC4zMzJzLTgwLjAwNywxNzguMzMyLTE3OC4zMzIsMTc4LjMzMkMxMDkuMzE4LDM4Ni4wNDcsMjkuMzMxLDMwNi4wNSwyOS4zMzEsMjA3LjcxNXoiIGZpbGw9IiMzNzQwNEQiLz48L3N2Zz4=) no-repeat left 9px center transparent;
		background-size: 24px;
	}

	input.search-text:focus {
		z-index: 3;
		width: 270px;
		border: 2px solid var(--main-color-new-theme);
		background-color: white;
		outline: none;
		cursor: auto;
		padding-right: 10px;
	}

	input.search-submit {
		position: relative;
		z-index: 4;
		top: 17px;
		left: 49px;
		width: 45px;
		height: 45px;
		margin: 0;
		padding: 0;
		border: 0;
		outline: 0;
		border-radius: 30px;
		cursor: pointer;
		background: none;
	}

	input.search-text::-webkit-search-cancel-button {
		cursor: pointer;
	}

	.paymentBtn {
		background-color: #ffc107;
		padding: 5px 14px;
		color: #15102e;
		border-radius: 6px !important;
		font-size: 14px;
		font-weight: 1000;
		border: 0px !important;
		margin: 0px 8px;
	}

	@media (max-width: 768px){
		.event-img{
			min-height: 160px !important;
		}
	}

	.event-desc{
		padding-right: 8px !important;
	}
</style>
<main id="main" style="background-size: auto;">
	<?php

	if (isset($serviceDetails['bookingType']) && CheckEmptyNullVar($serviceDetails['bookingType']) != '') {

		if ($serviceDetails['bookingType'] == 'PAY NOW'  &&  $serviceDetails['serviceAmount'] > 0) {

			$payment_btn_check = 'PAY NOW';
		} else if ($serviceDetails['bookingType'] == 'PAY LATER'  &&  $serviceDetails['serviceAmount'] > 0) {
			$payment_btn_check = 'PAY LATER';
		} else {
			$payment_btn_check = 'SERVICE REQUEST';
		}
	} else {

		if ($serviceDetails['serviceAmount'] > 0) {
			$payment_btn_check = 'PAY NOW';
		} else {
			$payment_btn_check = 'SERVICE REQUEST';
		}
	}
	?>

	<!-- ======= Temple Services Section ======= -->
	<section id="temple-services" class="temple-services" style="background-size: auto;">
		<div class="cartUpdateMsg"></div>
		<div class="container-fluid">
			<?php $ServicePrice = str_replace("$", "", $serviceDetails['serviceAmount']); ?>
			<div class="container-fluid">

				<div class="row mb-0 pb-0 px-3">
					<?php if ($serviceDetails['Image'] != "") { ?>
						<div class="col-md-6 mb-0 pb-0" data-aos="fade-right">
							<center>

								<h2 class="text-center mb-0" style="font-weight:bold!important;font-size: 2em!important;text-shadow: 1px 1px 5px #FA9D1E;"><?= $serviceDetails['refDataName']; ?></h2>
								<img src="<?= base_url('assets/img/border.png'); ?>" width="40%">
							</center>
							<div class="event-img" style="min-height: 350px; max-height: 422px; width: 100%; display: flex; justify-content: center; align-items: center; background-image: url('<?= ApiBaseUrl()['url'] . $serviceDetails['Image']; ?>'); background-size: contain; background-position: center; background-repeat: no-repeat;"></div>

						</div>
					<?php } ?>
					<div class="text-center mb-0 pb-0 <?= $serviceDetails['Image'] ? 'col-md-6' : 'col-md-12'; ?>" data-aos="fade-left">
						<!-- <h5 class="title2  mb-4"><u>EVENT DETAILS</u></h5> -->


						<!-- Date Start -->
						<h4 class="mb-0 pb-0 fw-bold">
							<?php

							// print_r($serviceDetails);

							if (isset($serviceDetails['startDate']) && !empty(CheckEmptyNullVar($serviceDetails['startDate'])) && isset($serviceDetails['endDate']) && !empty(CheckEmptyNullVar($serviceDetails['endDate']))) {
								$startYear = date('Y', strtotime($serviceDetails['startDate']));
								$endYear = date('Y', strtotime($serviceDetails['endDate']));


								if ($serviceDetails['startDate'] == $serviceDetails['endDate']) {
									if ($startYear == $endYear) {
										echo  date('M d', strtotime($serviceDetails['startDate'])) . ', ' . $startYear;
									} else {
										echo date('M d', strtotime($serviceDetails['startDate'])) . ', ' . $endYear;
									}
								} else {

									if ($startYear == $endYear) {
										echo  date('M d', strtotime($serviceDetails['startDate'])) . ' - ' . date('M d', strtotime($serviceDetails['endDate'])) . ', ' . $startYear;
									} else {
										echo date('M d', strtotime($serviceDetails['startDate'])) . ', ' . $startYear . ' - ' . date('M d', strtotime($serviceDetails['endDate'])) . ', ' . $endYear;
									}
								}
							} else if (isset($serviceDetails['startDate']) && !empty(CheckEmptyNullVar($serviceDetails['startDate'])) && isset($serviceDetails['endDate']) && empty(CheckEmptyNullVar($serviceDetails['endDate']))) {


								echo date('M d', strtotime($serviceDetails['startDate'])) . ', ' . date('Y', strtotime($serviceDetails['startDate']));
							} else if (isset($serviceDetails['startDate']) && empty(CheckEmptyNullVar($serviceDetails['startDate'])) && isset($serviceDetails['endDate']) && !empty(CheckEmptyNullVar($serviceDetails['endDate']))) {


								echo  date('M d', strtotime($serviceDetails['endDate'])) . ', ' . date('Y', strtotime($serviceDetails['endDate']));
							}
							?>

							<!-- Flyer Link 1 -->
							<?php if (isset($serviceDetails['flyerLink']) && $serviceDetails['flyerLink'] != '') { ?>
								<p style="font-weight:bold;font-size: 14px!important;margin-bottom:0!important">Flyer Links 👇</p> <a href="<?= ApiBaseUrl()['url'] . @$serviceDetails['flyerLink']; ?>" target="_blank" style="text-decoration: underline;color: blue;font-size: 14px!important;font-weight: bold!important;" download><?= @$serviceDetails['flyerName'] ? $serviceDetails['flyerName'] : 'Link 1'; ?></a>
							<?php } ?>
							<!-- Flyer Link 2 -->

							<?php if (isset($serviceDetails['eventSponsorshipLink2']) && $serviceDetails['eventSponsorshipLink2'] != '') { ?>
								<a href="<?= @$serviceDetails['eventSponsorshipLink2']; ?>" target="_blank" style="text-decoration: underline;color: blue;font-size: 14px!important;font-weight: bold!important;" download><?= @$serviceDetails['flyerName2'] ? ' | ' . $serviceDetails['flyerName2'] : ' | Link 2'; ?></a>
							<?php } else if ((isset($serviceDetails['flyerLink2']) && $serviceDetails['flyerLink2'] != '')) { ?>

								<a href="<?= ApiBaseUrl()['url'] . @$serviceDetails['flyerLink2']; ?>" target="_blank" style="text-decoration: underline;color: blue;font-size: 14px!important;font-weight: bold!important;" download><?= @$serviceDetails['flyerName2'] ? ' | ' . $serviceDetails['flyerName2'] : ' | Link 2'; ?></a>
							<?php } ?>

							<!-- Flyer Link 3 -->

							<?php if (isset($serviceDetails['flyerLink3']) && $serviceDetails['flyerLink3'] != '') { ?>
								<a href="<?= ApiBaseUrl()['url'] . @$serviceDetails['flyerLink3']; ?>" target="_blank" style="text-decoration: underline;color: blue;font-size: 14px!important;font-weight: bold!important;" download><?= @$serviceDetails['flyerName3'] ? ' | ' . $serviceDetails['flyerName3'] : 'Link 3'; ?></a>
							<?php } ?>

						</h4>
						<img src="<?= base_url('assets/img/border.png'); ?>" width="40%">
						<?= isset($serviceDetails['description']) ? ($serviceDetails['description'] && $serviceDetails['description'] != 'null' ?  '<p class="text-center pt-4">' . $serviceDetails['description'] . '</p>' : '') : ''; ?>



						<?php if (isset($serviceDetails['venue']) && $serviceDetails['venue'] && $serviceDetails['venue'] != 'null') { ?>

							<span style="display: flex;   justify-content: space-between; width: 176px; flex-wrap: wrap; flex-direction: row;">
								<h4 class="pb-0 mb-0 text-center fw-bold">Venue:</h4>
								<p><?= camelCase($serviceDetails['venue']) ?></p>
							</span>

						<?php } ?>

						<?php if (isset($ServicePrice) && ($ServicePrice != 0.00  && $ServicePrice != 'null')) { ?>

							<h4 class="pb-0 mb-0"><?= camelCase($serviceDetails['refDataName']); ?> Sponsorship Amount:<br><img src="<?= base_url('assets/img/border.png') ?>" style="width: 40%;"></h4>
							<p style="text-align: center !important;">$ <?= ($ServicePrice != 0.00  && $ServicePrice != 'null') ?  sprintf("%.2f", $ServicePrice) : ''; ?></p>
						<?php } ?>
						<?php $child_Events = GetChildEventByParentEvent($serviceDetails['refDataName'], $serviceDetails['serviceTypes'], $serviceDetails['serviceCategoryTypes'], $cartList);
						?>

						<?php if ($child_Events == '' && ($serviceDetails['serviceAmount'] != 0 || $serviceDetails['serviceAmount'] != '' || $serviceDetails['serviceAmount'] != 0.00)) {   ?>


							<?php if ($serviceDetails['status'] == 'ACTIVE') { ?>

								<a href="javaScript:void(0)" class="btn btn-primary bookeventbtn btn-sm" style="background-color: #ffc107;padding: 5px 14px;color: #15102e;border-radius: 6px!important;font-size: 17px;font-weight: 1000;border: 0px!important;margin: 0px 8px;" onclick="addSingleCart('<?= $ServicePrice ?>', '<?= str_replace("'", "`", $serviceDetails['refDataName']) ?>', '<?= $serviceDetails['_id'] ?>', '<?= $serviceDetails['serviceCategoryTypes'] ?>','<?= $serviceDetails['serviceTypes'] ?>','<?= $serviceDetails['dayTypes'] ?>', '<?= $serviceDetails['startDate'] ?>','<?= $serviceDetails['startTime'] ?>','<?= @$serviceDetails['membershipDiscount'] ?>')">Add to Cart</a>

							<?php } else { ?>

								<a href="javaScript:void(0)" class="btn btn-primary bookeventbtn btn-sm" style="background-color: #B02135;padding: 5px 14px;color: #fff;border-radius: 6px!important;font-size: 17px;font-weight: 1000;border: 0px!important;margin: 0px 8px;"><i class="fa fa-warning"></i> This puja service is sold out!</a>

							<?php } ?>


						<?php } ?>

					</div>



					<?php


					if ($child_Events != '') {
						echo '<div class="row mt-0 pt-0" id="service-data">';


						echo  '
						<div class="col-md-4" style="display: flex; flex-direction: row; align-items: flex-end;">
						<div class="row m-0 p-0" id="searchField">
						<div class="col-md-12 m-0 p-0">
						<div class="px-2">
						<input type="search" name="q" id="search" class="search-text searchKey" placeholder="Search..." autocomplete="off" style="margin-left: 10px;width: 401px;height: 56px;">
						</div>
						</div>
						</div>
						</div>
						<div class="col-md-8">
						<div class="d-flex justify-content-end align-items-end" style="border-bottom: 20px;">
						<div class="text-white px-2">
						<div class="row px-0 mx-0">
						<div class="col-md-9 text-start text-dark">
						<span style="padding-left: 55px;">Total Amount</span>
						</div>
						</div>
						<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: 20px!important;">' . $cart_count . '</span></a>
						</span>
						<label class="label label-primary" style="background: #000030;padding: 5px 14px;color: white;margin: 0px 8px;border-radius: 6px;font-size: 16px!important;font-weight: 1000;">' . ($currencySymbol != '' ? $currencySymbol . ' ' : '$ ') . '<span class="allPrice">' . sprintf("%.2f", $cartList['totalPrice']) . '</span></label>
						<a href="javaScript:void(0)" class="btn btn-success paymentBtn"  onclick="CartCheckLogin(' . "'" . 'events' . "'" . ')">
						PROCEED TO CHECKOUT
						</a>
						</div>
						</div>
						' . (($ServicePrice != 0.00) ? '<!--<a href="javaScript:void(0)" class="btn btn-primary bookeventbtn btn-sm" style="background-color: green;padding: 5px 14px;color: #fff;border-radius: 6px!important;font-size: 17px;font-weight: 1000;border: 0px!important;margin: 0px 8px;" onclick="checkLoginStatus(' . "'" . $ServicePrice . "'" . ', ' . "'" . str_replace("'", "`", $serviceDetails['refDataName']) . "'" . ', ' . "'" . $serviceDetails['_id'] . "'" . ', ' . "'" . $serviceDetails['serviceCategoryTypes'] . "'" . ',' . "'" . $serviceDetails['serviceTypes'] . "'" . ',' . "'" . $serviceDetails['dayTypes'] . "'" . ', ' . "'" . $serviceDetails['startDate'] . "'" . ',' . "'" . $serviceDetails['startTime'] . "'" . ')">Book Full Package ( $ ' . price_format($ServicePrice, 2) . ')</a>-->' : '') . '</div></div>';

						echo $child_Events;
						echo '</div>';
					}

					?>

				</div>

			</div>

			<input type="hidden" id="includeSankalpamModal" value="<?= @$includeSankalpam ?>">
		</div>
	</section><!-- End Temple Services Section -->


</main><!-- End #main -->


<script type="text/javascript" src="<?= base_url('admin_assets/js/sweetalert2.all.min.js') ?>"></script>
<?php
$booking = getBookingTimes(); // ['startTime' => '09:00 AM', 'endTime' => '09:00 PM']
?>
<script type="text/javascript">
	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;

				/*if (isToday) {
					const now = new Date();
					const currentTotalMinutes = now.getHours() * 60 + now.getMinutes();
					console.log("now");
					console.log(now);
					console.log("currentTotalMinutes");
					console.log(currentTotalMinutes);
					console.log(selectedTotalMinutes);

					if (selectedTotalMinutes <= currentTotalMinutes) {
						$("#timepicker_" + id).notify("Please select a time after the current time.", {
							position: "bottom",
							className: "error",
						});
						$('#timepicker_' + id).val(''); // Clear invalid time
						return;
					}
				}
				// Handle non-today (future) dates
				const maxAllowedMinutes = 21 * 60; // 9:00 PM => 21 * 60 = 1260
				if (selectedTotalMinutes > maxAllowedMinutes) {
					$("#timepicker_" + id).notify("Please select a time before 9:00 PM.", {
						position: "bottom",
						className: "error",
					});
					$('#timepicker_' + id).val('');
					return;
				}
				*/



				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",
						// });
						Swal.fire(`Please select a time between ${bookingStartTime} and ${bookingEndTime} that is after the current time.`, '', 'warning');
						$('#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",
						// });
						Swal.fire(`Please select a time between ${bookingStartTime} and ${bookingEndTime}.`, '', 'warning');
						$('#timepicker_' + id).val('');
						return;
					}
				}


				// All good
				addTocart();
			});

		}


	});




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

	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;
	}
	$(document).on('click', '.datepicker-events', function() {
		var startDate = $(this).attr('data-start-date');

		// alert(startDate);
		var endDate = $(this).attr('data-end-date');

		var dayVal = $(this).attr('daytype');
		// var dayVal = 'MONDAY';
		if (startDate !== '' && endDate !== '') {
			var nclickF = $(this);

			if (startDate !== '' && endDate) {
				nclickF.notify(
					"You can select a date between " + startDate + " and " + endDate, {
						position: "right",
						className: "success",
					}
				);
			}

			if (!nclickF.hasClass('hasDatepicker')) {

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


					beforeShowDay: function(date) {

						var startTime = new Date(nclickF.attr('data-start-date')).getTime();
						var endTime = new Date(nclickF.attr('data-end-date')).getTime();
						var currentDate = date.getTime();

						var dayOfWeek = $.datepicker.formatDate('DD', date);

						console.log(dayOfWeek);
						console.log(dayVal);

						if (currentDate >= startTime && currentDate <= endTime) {


							if (dayVal != '') {

								if (dayOfWeek.toUpperCase() === dayVal.toUpperCase()) {

									return [true, 'enabled-date', 'This date is enabled'];
								} else {

									return [false, '', 'This date is disabled'];
								}
							} else {
								return [true, 'enabled-date', 'This date is enabled'];

							}
						}
						return [false, '', 'This date is disabled'];
					}
				});

				nclickF.datepicker('show');
			}
		} else if (startDate != '') {
			var nclickF = $(this);

			if (startDate !== '' && endDate) {
				nclickF.notify(
					"You can select a date from " + startDate, {
						position: "right",
						className: "success",
					}
				);
			}

			if (!nclickF.hasClass('hasDatepicker')) {

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


					beforeShowDay: function(date) {

						var startTime = new Date(nclickF.attr('data-start-date')).getTime();
						var endTime = new Date(nclickF.attr('data-end-date')).getTime();
						var currentDate = date.getTime();

						var dayOfWeek = $.datepicker.formatDate('DD', date);

						console.log(dayOfWeek);
						console.log(dayVal);

						if (currentDate >= startTime) {


							if (dayVal != '') {

								if (dayOfWeek.toUpperCase() === dayVal.toUpperCase()) {

									return [true, 'enabled-date', 'This date is enabled'];
								} else {

									return [false, '', 'This date is disabled'];
								}
							} else {
								return [true, 'enabled-date', 'This date is enabled'];

							}
						}
						return [false, '', 'This date is disabled'];
					}
				});

				nclickF.datepicker('show');
			}
		} else {
			var nclickF = $(this);

			if (startDate !== '' && endDate) {
				nclickF.notify(
					"You can select any date", {
						position: "right",
						className: "success",
					}
				);
			}

			if (!nclickF.hasClass('hasDatepicker')) {

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


					beforeShowDay: function(date) {

						var startTime = new Date(nclickF.attr('data-start-date')).getTime();
						var endTime = new Date(nclickF.attr('data-end-date')).getTime();
						var currentDate = date.getTime();

						var dayOfWeek = $.datepicker.formatDate('DD', date);

						console.log(dayOfWeek);
						console.log(dayVal);

						// if (currentDate >= startTime) {


						if (dayVal != '') {

							if (dayOfWeek.toUpperCase() === dayVal.toUpperCase()) {

								return [true, 'enabled-date', 'This date is enabled'];
							} else {

								return [false, '', 'This date is disabled'];
							}
						} else {
							return [true, 'enabled-date', 'This date is enabled'];

						}
						// }
						return [false, '', 'This date is disabled'];
					}
				});

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

	$(document).ready(function() {

		// Custom Search Bar Start
		$("#search").on("keyup", function() {
			var value = $(this).val().toLowerCase();
			$(".serviceSearch").filter(function() {
				$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
			});
		}).on("search", function() {
			if ($(this).val() === "") {
				$(".serviceSearch").show();
			}
		});
	});

	function BookNow(serviceAmt, serviceId, serviceName, serviceCategory, serviceTypes, startDate, startTime, payment_btn_check, logged_in) {


		var serviceAmt = serviceAmt;
		var serviceId = serviceId;
		var serviceName = serviceName;
		var serviceCategory = serviceCategory;
		var serviceTypes = serviceTypes;
		var startDate = startDate;
		var startTime = startTime;
		var payment_btn_check = payment_btn_check;

		if (logged_in == 0) {
			alert('Please Log-in first!');
		} else {

			loader.on();
			swal({
					title: "Confirmation?",
					text: "Are you want to Request this Service!",
					type: "warning",
					showCancelButton: true,
					confirmButtonColor: "var(--main-color-new-theme)",
					confirmButtonText: "Yes",
					closeOnConfirm: false
				},
				function(isConfirmed) {
					if (isConfirmed) {
						// Disable the button
						$('.confirm').prop('disabled', true);

						loader.on();
						$.ajax({
							url: "<?= base_url('Services/AddServiceRequest') ?>",
							type: "POST",
							dataType: "json",
							data: {
								serviceAmt: serviceAmt,
								serviceId: serviceId,
								serviceName: serviceName,
								serviceCategory: serviceCategory,
								serviceTypes: serviceTypes,
								startDate: startDate,
								startTime: startTime,
								payment_btn_check: payment_btn_check
							},
							success: function(response) {
								loader.off();
								if (response.statusCode == 1) {
									swal({
											html: true,
											title: "Service Requested Successful!",
											type: "success",
											confirmButtonText: 'OK',
											confirmButtonColor: 'var(--main-color-new-theme)',
										},
										function() {
											window.location.reload();
										});

								} else {
									swal({
											html: true,
											title: "Failed!",
											text: "<span>Transaction Failed!<span>",
											type: "error",
											confirmButtonText: 'OK',
											confirmButtonColor: 'var(--main-color-new-theme)',
										},
										function() {
											window.location.reload();
										});
								}

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

	}

	function addTocart() {

		var totalPrice = 0;
		var sankalpam_data = [];
		var includeSankalpam = [];
		var cart_type = 'EVENTS';
		var ids = [];
		var qty = [];
		var ctg = [];
		var startDate = [];
		var serviceTypes = [];
		var serviceName = [];
		var serviceAmount = [];
		var description = [];
		var image = [];
		var cart_ctg = [];
		var available_count = [];
		var is_date_required = [];
		var serviceDesc = [];
		var isDietySelected = [];
		var dietyName = [];

		var is_membership_discount = [];

		if ($(this).attr('includeSankalpam') == 'YES') {
			$("#includeSankalpamModal").val($(this).attr('includeSankalpam'));
		}


		sankalpam_data.push($("#includeSankalpamModal").val());


		var noDateSelected = 0;
		var addtoCartStatus = true;

		$('input[name="services_id[]"]:checked').each(function() {



			id = $(this).attr('data-id');
			loader.on();
			console.log(id);
			// alert("ok2");
			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);
			console.log('i am here1');
			if (isdietyselectedVal == 'YES') {
				console.log('i am here');
				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: "left"
						}
					);



					addtoCartStatus = false;
					return false;
				}




				startDate.push($("#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);


				totalPrice = (parseFloat(totalPrice) + ((parseFloat($(this).attr('data-price')) * init_qty) * nDateSelectCount));

				// $("#Totalprice_" + $(this).attr('data-id')).html(((parseFloat($(this).attr('data-price')) * init_qty) * nDateSelectCount) + ".00");
				let Price = ((parseFloat($(this).attr('data-price')) * init_qty) * nDateSelectCount);
				let formatted = Price.toLocaleString('en-US', {
					minimumFractionDigits: 2,
					maximumFractionDigits: 2
				});
				$("#Totalprice_" + $(this).attr('data-id')).text(formatted);
			} 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((parseFloat($(this).attr('data-price')) * init_qty) + ".00");
				let Price = (parseFloat($(this).attr('data-price')) * init_qty);
				let formatted = Price.toLocaleString('en-US', {
					minimumFractionDigits: 2,
					maximumFractionDigits: 2
				});
				$("#Totalprice_" + $(this).attr('data-id')).text(formatted);

				// startDate.push('');
			}






			var anyAmountCheck = parseFloat($("#anyAmtEvent" + id).val());
			if (anyAmountCheck < 0 || anyAmountCheck == 0) {
				$(this).prop('checked', false);
				$("#anyAmtEvent" + id).focus();
				$("#anyAmtEvent" + id).notify(
					"Entered Amount Must Be Greater Than 0!", {
						position: "right"
					}
				);
				addtoCartStatus = false;
				return false;
			}


			if ($("#anyAmtEvent" + id).val() == '') {
				$(this).prop('checked', false);
				$("#anyAmtEvent" + id).focus();
				$("#anyAmtEvent" + id).notify(
					"Please Enter Any Amount!", {
						position: "left"
					}
				);
				addtoCartStatus = false;
				return false;
			}

			// var serviceDescCheck = $("#serviceDesc" + id).val();
			// if (serviceDescCheck.length == 0) {
			// 	$(this).prop('checked', false);
			// 	$("#serviceDesc" + id).focus();
			// 	$("#serviceDesc" + id).notify(
			// 		"Entered Service Name!", {
			// 			position: "right"
			// 		}
			// 	);
			// 	addtoCartStatus = false;
			// 	return false;
			// }

			if ($(this).attr('data-price') != 0) {


				startDate.push($("#datepicker_" + id).val());
				ctg.push($(this).attr('data-category'));
				available_count.push($(this).attr('available_count'));
				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'));
				description.push($(this).attr('data-description').replace(/['"`]/g, ''));
				serviceDesc.push($(this).attr('data-serviceDesc'));
				cart_ctg.push($(this).attr('cart_category'));
				serviceAmount.push($(this).attr('data-price'));
				ids.push($(this).attr('data-id'));
				includeSankalpam.push($(this).attr('includeSankalpam'));
				qty.push(init_qty);
			}
		});

		if (addtoCartStatus == false) {
			loader.off();
			return false;
		} else {
			$(".cart-count").text(ids.length);
			$(".allPrice").text((totalPrice / 1).toFixed(2));
		}



		$.ajax({
			type: "POST",
			url: "<?= base_url('Events/addCart'); ?>",
			data: {
				ids: ids,
				totalPrice: totalPrice,
				qty: qty,
				ctg: ctg,
				startDate: startDate,
				serviceTypes: serviceTypes,
				serviceName: serviceName,
				serviceAmount: serviceAmount,
				cart_type: cart_type,
				image: image,
				description: description,
				cart_ctg: cart_ctg,
				is_membership_discount: is_membership_discount,
				includeSankalpam: includeSankalpam,
				available_count: available_count,
				serviceDesc: serviceDesc,
				isDietySelected: isDietySelected,
				dietyName: dietyName,
			},
			success: function(result) {

				var responseObject = JSON.parse(result);
				var totalPrice = responseObject.totalPrice;

				console.log(totalPrice);
				$("#includeSankalpamModal").val(result.includeSankalpam);
				// 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);
		}
		var initialPrice = $("#price_" + id).text();
		var initialResultAmt = initialPrice.replace(/\$/g, "");
		var substractiveAmt = init_qty * initialResultAmt;
		$("#Totalprice_" + id).text(substractiveAmt.toFixed(2));
		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);
		var initialPrice = $("#price_" + id).text();
		var initialResultAmt = initialPrice.replace(/\$/g, "");
		var substractiveAmt = init_qty * initialResultAmt;
		$("#Totalprice_" + id).text(substractiveAmt.toFixed(2));
		addTocart();
	}

	function ViewCart() {
		// if ($(".cart-count").text() > 0) {
		// 	window.location.href = "<?= base_url('Events/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 (parseInt($(".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 {
						if (page_name == 'events') {
							window.location.href = "<?= base_url('events/checkout') ?>";
						}
					}
				}
			});
		} 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 changebtnStyles(id) {
		$(".styles").removeClass('active-services');
		$(".styles").addClass('services');
		$("#" + id).addClass('active-services');
		$("#" + id).removeClass('services');
	}



	function addSingleCart(service_price, service_name, service_id, service_category, service_type, day_type, start_date, start_time, membership_discount) {

		console.log(service_price + " :: " + service_name + " :: " + service_id + " :: " + service_category + " :: " + service_type + " :: " + day_type + " :: " + start_date + " :: " + start_time);



		var totalPrice = service_price;
		var sankalpam_data = [];
		var cart_type = 'EVENTS';
		var ids = [];
		var qty = [];
		var ctg = [];
		var startTime = [];
		var startDate = [];
		var serviceTypes = [];
		var serviceName = [];
		var serviceAmount = [];
		var cart_ctg = [];


		var is_membership_discount = [];

		startTime.push(start_time);
		startDate.push(start_date);
		ctg.push(service_category);
		serviceTypes.push(service_type);
		serviceName.push(service_name);


		cart_ctg.push(cart_type);
		serviceAmount.push(service_price);
		ids.push(service_id);
		qty.push(1);

		is_membership_discount.push(membership_discount);

		$(".cart-count").text(ids.length);




		$.ajax({
			type: "POST",
			url: "<?= base_url('Events/addCart'); ?>",
			data: {
				ids: ids,
				totalPrice: totalPrice,
				qty: qty,
				ctg: ctg,
				startDate: startDate,
				serviceTypes: serviceTypes,
				serviceName: serviceName,
				serviceAmount: serviceAmount,
				cart_type: cart_type,
				cart_ctg: cart_ctg,
				is_membership_discount: is_membership_discount
			},
			success: function(result) {

				var responseObject = JSON.parse(result);

				console.log(responseObject.status);
				var totalPrice = responseObject.totalPrice;

				if (responseObject.status == 1) {
					Swal.fire({
						title: 'Added into Cart!',
						showDenyButton: false,
						showCancelButton: false,
						icon: 'success',
						confirmButtonText: 'Proceed to Checkout',
						allowOutsideClick: false,
						// denyButtonText: `Cancel`,
					}).then((result) => {

						if (result.isConfirmed) {

							CartCheckLogin('events');

						}
					});

				} else {
					Swal.fire('Something went wrong!', '', 'warning');
				}




				loader.off();
			}
		});


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