<?php $this->load->view('includes/head') ?>
<?php $this->load->view('includes/topbar') ?>
<?php $this->load->view('includes/header') ?>
<link href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/css/lightbox.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/js/lightbox-plus-jquery.min.js"></script>




<link rel="stylesheet" type="text/css" href="<?= base_url('assets/css/services-cart.css') ?>">
<style>
	.form-check-input:checked[type="radio"] {
		background-color: var(--main-color-new-theme);
		border-radius: 11px;
		font-size: 18px;
		border: 2px solid #ffc107;
		background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cpath fill='none' stroke='%23ffc107' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M6 10l3 3 6-6'/%3E%3C/svg%3E");
		background-position: center;
		background-repeat: no-repeat;
		background-size: 60%;
		padding: 16px;
	}


	/* For unchecked state */
	.form-check-input[type="radio"] {
		background-color: transparent;
		border-radius: 11px;
		font-size: 18px;
		border: 2px solid #ffc107;
		padding: 16px;
	}
</style>

<main id="main">
	<?php

	$cartList = $this->session->userdata('facilities_cart');
	// var_dump(  $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());
	}

	?>

	<!-- ======= Coming Soon ======= -->
	<!-- <section class="temple-services" style="background-image: url(<?= base_url('assets/img/paisley.webp'); ?>);background-size: 162px;"> -->
	<section class="temple-services" style="">



		<style type="text/css">
			* {
				margin: 0;
				padding: 0
			}

			/* Fix Facilities Section Scroll Issue */
			.temple-services {
				overflow-x: hidden !important;
				/* Prevents horizontal scroll */
				max-width: 100%;
			}

			.temple-services .row {
				max-width: 100%;
				display: flex;
				flex-wrap: wrap;
				margin: 0;
			}

			.temple-services fieldset {
				width: 100% !important;
				overflow-x: hidden;
				padding-right: 20px;
			}

			/* Ensure Inputs & Tables Fit Within Screen */
			.table-inputs {
				max-width: 100%;
				table-layout: fixed;
				/* Ensures proper width */
				word-wrap: break-word;
			}

			.table-inputs td,
			.table-inputs th {
				white-space: normal !important;
				/* Prevents text from stretching table */
				word-break: break-word;
			}

			/* Fix Timepicker Overflows */
			.ui-timepicker-container {
				max-width: 100%;
				overflow-x: hidden;
			}

			.ui-timepicker {
				width: auto !important;
				max-width: 100%;
			}

			/* Responsive Fix */
			@media (max-width: 768px) {
				.temple-services {
					padding: 10px;
				}

				.table-inputs {
					display: block;
					overflow-x: auto;
					/* Allows horizontal scroll only if necessary */
				}

				.form-control {
					font-size: 16px !important;
					/* Adjust font size for small screens */
				}

				.nav-tabs {
					flex-wrap: wrap;
					justify-content: center;
				}
			}

			html {
				height: 100%
			}

			p {
				color: grey
			}

			#heading {
				text-transform: uppercase;
				color: var(--main-color-new-theme);
				font-weight: normal
			}

			#msform {
				text-align: center;
				position: relative;
				margin-top: 20px
			}

			#msform fieldset {
				background: white;
				border: 0 none;
				border-radius: 0.5rem;
				box-sizing: border-box;
				width: 100%;
				margin: 0;
				padding-bottom: 11px;
				position: relative;
				padding-right: 20px;
			}

			.form-card {
				text-align: left
			}

			#msform fieldset:not(:first-of-type) {
				display: none
			}



			#msform .action-button {
				width: auto;
				background: var(--main-color-new-theme);
				font-weight: bold;
				color: white;
				border: 0 none;
				border-radius: 5px;
				cursor: pointer;
				padding: 11px 32px;
				margin: 10px 0px 10px 5px;
			}

			#msform .action-button:hover,
			#msform .action-button:focus {
				background-color: var(--main-color-new-theme)
			}

			#msform .action-button-previous {
				width: auto;
				background: #616161;
				font-weight: bold;
				color: white;
				border: 0 none;
				border-radius: 5px;
				cursor: pointer;
				padding: 11px 32px;
				margin: 10px 0px 10px 5px;
			}

			#msform .action-button-previous:hover,
			#msform .action-button-previous:focus {
				background-color: #000000
			}

			.card {
				z-index: 0;
				border: none;
				position: relative
			}

			.fs-title {
				font-size: 25px;
				color: var(--main-color-new-theme);
				margin-bottom: 15px;
				font-weight: normal;
				text-align: left
			}

			.purple-text {
				color: var(--main-color-new-theme);
				font-weight: normal
			}



			.fieldlabels {
				color: gray;
				text-align: left
			}

			#progressbar {
				margin-bottom: 8px;
				overflow: hidden;
				color: lightgrey;
				padding-left: 0;
			}

			#progressbar .active {
				color: var(--main-color-new-theme)
			}

			#progressbar li {
				list-style-type: none;
				font-size: 15px;
				width: 33.33%;
				float: left;
				position: relative;
				font-weight: 400
			}


			#progressbar #account:before {
				font-family: FontAwesome;
				content: "\f14b"
			}

			#progressbar #personal:before {
				font-family: FontAwesome;
				content: "\f274"
			}

			#progressbar #payment:before {
				font-family: FontAwesome;
				content: "\f0f6"
			}

			#progressbar #confirm:before {
				font-family: FontAwesome;
				content: "\f00c"
			}

			#progressbar li:before {
				width: 50px;
				height: 50px;
				line-height: 45px;
				display: block;
				font-size: 20px;
				color: #ffffff;
				background: lightgray;
				border-radius: 50%;
				margin: 0 auto 10px auto;
				padding: 2px
			}

			#progressbar li:after {
				content: '';
				width: 100%;
				height: 2px;
				background: lightgray;
				position: absolute;
				left: 0;
				top: 25px;
				z-index: -1
			}

			#progressbar li.active:before,
			#progressbar li.active:after {
				background: var(--main-color-new-theme)
			}

			.progress {
				height: 20px
			}

			.progress-bar {
				background-color: var(--main-color-new-theme)
			}

			.fit-image {
				width: 100%;
				object-fit: cover
			}


			.fa2 {
				margin-top: 7px;

			}

			.fa {
				padding-top: 3px;
			}

			.form-control {
				font-size: 20px !important;
			}

			.form-control2 {
				border: 0 !important;
			}

			.form-control:focus {
				box-shadow: 0 0 0 0.25rem rgb(255 255 255 / 0%) !important;
			}


			.table-inputs {
				border-spacing: 0;
				border-collapse: collapse;
			}

			.table-inputs th {
				padding: 0 0.75rem;
				line-height: 1.75rem;
				font-weight: normal;
				font-size: 12px;
				border: 1px solid #d2d2d2;
			}

			.table-inputs td {
				background-color: #fff;
				border-right: 1px solid #d2d2d2;
				padding: 0;
			}

			.table-inputs input {
				border: 0;
				background-color: transparent;
			}

			.ui-timepicker-container {
				position: absolute;
				overflow: hidden;
				box-sizing: border-box
			}

			.ui-timepicker,
			.ui-timepicker-viewport {
				box-sizing: content-box;
				height: 205px;
				display: block;
				margin: 0
			}

			.ui-timepicker {
				list-style: none;
				padding: 0 1px;
				text-align: center
			}

			.ui-timepicker-viewport {
				padding: 0;
				overflow: auto;
				overflow-x: hidden
			}

			.ui-timepicker-standard {
				font-size: 12px;
				font-family: sans-serif;
				list-style: none;
				background-color: #fff;
				background-clip: padding-box;
				border-radius: 0 0 3px 3px;
				box-shadow: 0 0 0 .75px #bbb, 2px 1.5px 3px rgba(0, 0, 0, .16);
				margin: 0;
				padding: 0;
			}

			.ui-timepicker-standard a {
				display: block;
				background: transparent;
				filter: none;
				border: none;
				width: 100%;
				text-align: left;
				border-radius: 0;
				font-size: 11.5px;
				padding: 5px 10px;
				line-height: 18px;
				white-space: nowrap;
				text-decoration: none;
				color: inherit;
			}

			.ui-timepicker-standard .ui-state-hover {
				box-shadow: none;
				border: none;
				text-decoration: none;
				background-color: #555;
				color: #fff;
			}

			.ui-timepicker-standard .ui-menu-item {
				margin: 0;
				padding: 0
			}

			.ui-timepicker-hidden {
				display: none
			}

			.ui-timepicker-no-scrollbar .ui-timepicker {
				border: none
			}
		</style>


		<?php

		$currencySymbol = getCurrencySymbol();
		$GeneralSettings = GeneralSettings();
		$client_info = getclientInfoById();
		$facilities_shift = SettingsApi()['result']['data'][0]['facilitySettings']['shift'];
		// var_dump(SettingsApi()['result']['data'][0]['facilitySettings']['bookingTypes']);
		$hourlyBookingRules = SettingsApi()['result']['data'][0]['facilitySettings']['hourlyBookingRules'];
		// echo "<br><br>";
		// var_dump($hourlyBookingRules);
		?>

		<?php

		$header_data = getWebSyncsData('Header Settings', 'headerSettings', '');

		$fgh = getFullPaymentSettings();

		$dsbj = $fgh['result']['data'][0]['paymentGatewayoffon'];

		foreach ($dsbj as $key => $dd) {
			if ($dd['source'] == 'WEBSITE') {
				$paymentSeverOn = $dd['isenable'];
				$paymentSeverText = $dd['desc'];
			}
		}

		$paymentSetting = @getPaymentGatewaySettings();

		if ($this->session->userdata('logged_in') == 1) {

			$current_user = @getUserDetails()->data[0];

			// print_r($current_user);
		}

		$getclientInfoById = @getclientInfoById()['data'][0];

		$CAW_MerchantId = @$getclientInfoById['ChargeAnywhereMerchantId'];
		$CAW_TerminalId = @$getclientInfoById['ChargeAnywhereTerminalId'];
		$formAction = SettingsApi()['result']['data'][0]['facilitySettings']['bookingTypes']; //REQUEST WITH PAYMENT
		// $formAction = "REQUEST WITH PAYMENT1";//REQUEST WITH PAYMENT

		?>
		<div class="container-fluid bg-image shadow-1-strong">
			<div class="row">
				<div class="col-md-12 mx-auto" style="padding-left: unset; padding-right: unset;">
					<div class="row m-0 p-0">

						<div class="col-md-12">
							<!--  <div class="row" id="searchField">
                  <div class="col-md-12 m-0 p-0"> -->

							<!-- <div class="px-5">
                        <input type="search" name="q" id="search" class="search-text searchKey" placeholder="Search..." autocomplete="off" style="margin-left: 10px;height: 70px;">

                      </div> -->

							<!--   </div>
                  </div>  -->



							<div class="row" style="display: flex; flex-direction: row; align-content: flex-end; align-items: flex-end;">



								<div class="col-md-6 col-lg-4 col-xl-4 px-4" style="display: flex;align-items: flex-end;">
									<div class="row m-0 p-0">
										<div class="col-md-12 m-0 p-0">
										</div>
									</div>
								</div>

								<div class="col-md-6 col-lg-3 col-xl-3">
									<h2 class="bottomborder text-center pb-1 mb-2" style="font-weight:bold!important;font-size: 25px!important;">BOOK FACILITIES</h2>
								</div>

								<div class="col-md-6 col-lg-5 col-xl-5">
									<div class="d-flex justify-content-end align-items-end" style="border-bottom: 20px;">
										<div class="text-white">

											<div class="row">
												<div class="col-md-12 text-end text-dark">
													<span class="fw-bold" style="padding-left: 34px;">Total Amount</span>
												</div>

												<div class="col-md-12 text-end text-dark">
													<span style="padding-right:6px!important">
														<a href="javaScript:void(0)"> <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" style="background: #000030;padding: 5px 14px;color: white;margin: 0px 8px;border-radius: 6px;font-size: 14px;font-weight: 1000;"><?= getCurrencySymbol(); ?> <span class="allPrice"><?= sprintf("%.2f", $cartList['totalPrice']); ?></span></label>

													<!-- <a href="javaScript:void(0)" class="btn btn-success" style="background-color: #ffc107;padding: 5px 14px;color: #15102e;border-radius: 6px!important;font-size: 14px;font-weight: 1000;border: 0px!important;margin: 0px 8px;" onclick="CartCheckLogin('facilities')">SEND REQUEST</a> -->

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


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



							<div class="container-fluid" style="padding-left: unset;padding-right: unset;">
								<div class="row justify-content-center">
									<div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 text-center p-0 mb-2" style="padding-left: unset; padding-right: unset;">
										<div class="card">
											<form id="msform" method="post">
												<!-- progressbar -->
												<ul id="progressbar">
													<li class="active" id="account"><strong>Event Details</strong></li>
													<li id="personal"><strong>Choose Rental</strong></li>
													<!-- <li id="payment"><strong>Terms and Conditions</strong></li> -->
													<li id="confirm"><strong>Submit Request</strong></li>
												</ul>
												<div class="progress">
													<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
												</div>
												<fieldset class="steps">
													<div class="form-card">



														<fieldset class="border-2 bg-white">
															<legend class="legend-outer  float-none w-auto"> Event Details</legend>
															<div class="row">
																<div class="col-md-6">
																	<fieldset class="border">
																		<legend class="legend-inner float-none w-auto">Event Name<span class="mandate">*</span></legend>
																		<div class="input-group">
																			<input type="text" class="form-control form-control2" name="eventName" id="eventName" placeholder="Enter Event Name" aria-label="eventName" required>
																			<span class="mandate" id="eventNameErrMsg"></span>
																		</div>
																	</fieldset>
																</div>

																<div class="col-md-6">
																	<fieldset class="border">
																		<legend class="legend-inner float-none w-auto">Event Date<span class="mandate">*</span></legend>
																		<div class="input-group">
																			<i class="fa fa-calendar"></i>
																			<input type="text" class="form-control form-control2 event-datepicker" name="eventDate" id="eventDate" placeholder="MM/DD/YYYY" aria-label="eventDate" readonly required>
																			<span class="mandate" id="eventDateErrMsg"></span>
																		</div>
																	</fieldset>
																</div>
															</div>

															<div class="row">
																<div class="col-md-6">
																	<fieldset class="border">
																		<legend class="legend-inner float-none w-auto">Event Time<span class="mandate">*</span></legend>
																		<div class="input-group">
																			<i class="fa fa-clock-o fa2"></i>

																			<input type='text' class='form-control2 form-control' name="eventTime" id="eventTime" placeholder='00:00' required>

																		</div>

																		<!--<table class="table-inputs mb-2">
                                      <tbody>
                                        <tr>
                                          <td style="width:33.33%">
                                            <div class="input-group" style="padding: 5px;">
                                              <input name="eventTime" id="eventTime" type="text" class="hasTimepicker start" placeholder="From Time" required hidden>
                                            </div>
                                          </td>
                                          <td style="width:33.33%">
                                            <div class="input-group" style="padding: 5px;">
                                              <input name="eventEndTime" id="eventEndTime" type="text" class="hasTimepicker end" placeholder="To Time" required hidden>
                                            </div>
                                          </td>
                                        </tr>
                                      </tbody>
                                    </table>-->


																	</fieldset>
																</div>
																<div class="col-md-6">
																	<fieldset class="border">
																		<legend class="legend-inner float-none w-auto">Preferred Language</legend>
																		<div class="input-group">

																			<select name="preferredLanguage" id="preferredLanguage" style="color:black!important;" class="form-select form-control border-dark mb-1">
																				<option value=" " selected disabled>Select Preferred Language</option>
																				<?php foreach ($preferredLanguage->data as $item) { ?>
																					<option value="<?= @$item->refDataName ?>"><?= @$item->refDataName ?></option>
																				<?php } ?>
																			</select>
																		</div>
																	</fieldset>
																</div>

																<div class="col-md-6">
																	<fieldset class="border">
																		<legend class="legend-inner float-none w-auto">Estimated Number of Attendees<span class="mandate">*</span></legend>
																		<div class="input-group">
																			<input type="number" class="form-control form-control2" onkeydown="disableE(event)" name="adults" id="adults" placeholder="No of Attendees" aria-label="adults" required>
																		</div>
																	</fieldset>

																</div>
																<div class="col-md-6 d-none">
																	<fieldset class="border">
																		<legend class="legend-inner float-none w-auto">Estimated Number of Children<span class="mandate">*</span></legend>
																		<div class="input-group">
																			<input type="number" class="form-control form-control2" onkeydown="disableE(event)" name="children" id="children" value="0" placeholder="No of Children" aria-label="children" required hidden>
																		</div>
																	</fieldset>
																</div>

																<div class="col-md-6">
																	<fieldset class="border">
																		<legend class="legend-inner float-none w-auto">Street Address</legend>
																		<div class="input-group">
																			<i class="fa fa-map-marker"></i>
																			<input type="text" class="form-control form-control2 border-dark mb-1 " name="eventLocation" id="eventLocation" placeholder="Event Location" style="color:black!important;" value="<?= $client_info['data'][0]['addressLineOne']; ?>" readonly>
																		</div>
																	</fieldset>
																</div>

																<div class="col-md-6">
																	<fieldset class="border">
																		<legend class="legend-inner float-none w-auto">State</legend>
																		<div class="input-group">

																			<input type="text" class="form-control form-control2" name="state" id="stateSelect" value="<?= $client_info['data'][0]['state']; ?>" readonly>
																		</div>
																	</fieldset>
																</div>
																<div class="col-md-6">
																	<fieldset class="border">
																		<legend class="legend-inner float-none w-auto">City</legend>
																		<div class="input-group">

																			<input type="text" class="form-control form-control2" name="city" id="city" value="<?= $client_info['data'][0]['city']; ?>" readonly>

																		</div>
																	</fieldset>
																</div>
																<div class="col-md-6">
																	<fieldset class="border">
																		<legend class="legend-inner float-none w-auto">Zip Code</legend>
																		<div class="input-group">
																			<i class="fa fa-file"></i>
																			<input type="number" class="form-control form-control2" onKeyPress="if(this.value.length==6) return false;" name="zipcode" id="zipcode" onkeydown="disableE(event)" value="<?= $client_info['data'][0]['zipCode']; ?>" placeholder="Zip Code" aria-label="zipcode" aria-describedby="basic-addon1" readonly>
																		</div>
																	</fieldset>
																</div>

																<div class="col-md-12">
																	<fieldset class="border">
																		<legend class="legend-inner float-none w-auto required">Event Description</legend>
																		<div class="input-group">
																			<i class="fa fa-file"></i>
																			<textarea class="form-control form-control2" name="eventDescription" id="eventDescription" placeholder="Enter Event Description" aria-label="eventDescription" aria-describedby="eventDescription"></textarea>
																		</div>
																	</fieldset>
																</div>

																<div class="col-md-12">
																	<!-- <fieldset class="border"> -->
																	<legend class="legend-inner float-none w-auto fw-bold eyeIcon" style="font-size: 22px!important;">Would you like to add Priest Services to your Facility Booking?</legend>


																	<div class="form-check form-check-inline" style="padding-bottom: 5px;">
																		<input class="form-check-input" type="radio" id="inlineCheckbox2" name="add_service" value="YES" style="border-radius: 11px;padding: 16px;font-size: 18px;border: 2px solid #ffc107;margin-right: 5px;">
																		<label class="form-check-label m-auto pt-2" for="inlineCheckbox2">Yes</label>
																	</div>

																	<div class="form-check form-check-inline mx-5" style="padding-bottom: 5px;margin-left: unset !important;">
																		<input class="form-check-input" type="radio" id="inlineCheckbox1" name="add_service" value="NO" style="border-radius: 11px;padding: 16px;font-size: 18px;border: 2px solid #ffc107;margin-right: 5px;">
																		<label class="form-check-label m-auto pt-2" for="inlineCheckbox1">No</label>
																	</div>
																	<!-- </fieldset> -->
																</div>
																<div class="row d-none" id="serviceDiv">
																	<div class="col-md-4 m-0 p-5 d-none">
																		<fieldset class="border">
																			<legend class="legend-inner float-none w-auto required">Preferred Location<span class="mandate">*</span></legend>
																			<div class="input-group">
																				<select id="preferredLocation" name="preferredLocation" style="color:black!important;" class="form-control2 form-control rounded  form-select">
																					<option value="IN-TEMPLE" selected style="color:black!important;">IN TEMPLE</option>

																				</select>
																			</div>
																		</fieldset>
																	</div>
																	<div class="col-md-4 m-0 p-5">
																		<fieldset class="border">
																			<legend class="legend-inner float-none w-auto required">Service<span class="mandate">*</span></legend>
																			<div class="input-group">
																				<select name="serviceName" id="serviceName" style="color:black!important;" class="form-control2 form-control rounded  form-select">
																					<option value="" selected disabled>Select Service</option>
																					<?php
																					$filter['query'] = ['aspectType' => 'ServiceSetup', 'serviceCategoryTypes' => "IN-TEMPLE", 'sourceTypes' => 'SERVICE REQUEST', 'status' => 'ACTIVE'];
																					$getServiceRequestData = getServiceRequestData($filter);
																					// $preferredLocations = sortBySequenceId($preferredLocations);
																					// var_dump($getServiceRequestData);
																					foreach ($getServiceRequestData as $item) {

																					?>

																						<option value="<?= $item['refDataName'] ?>" serviceId="<?= $item['_id'] ?>" startDate="<?= $item['startDate'] ?>" startTime="<?= $item['startTime'] ?>" serviceType="<?= $item['serviceTypes'] ?>" serviceAmount="<?= $item['serviceAmount'] ?>" membershipDiscount="<?= @$item['membershipDiscount'] ?>" membershipDiscountAmt="<?= @$item['membershipAmount'] ?>"><?= $item['refDataName'] ?>(<?= getCurrencySymbol(); ?><?= $item['serviceAmount'] ?>)</option>
																					<?php
																					} ?>
																				</select>
																				<input type="hidden" id="serviceType" name="serviceType">
																				<input type="hidden" id="serviceAmount" name="serviceAmount">
																				<input type="hidden" name="serviceId" id="serviceId">
																				<input type="hidden" name="serviceMembershipDiscount" id="serviceMembershipDiscount">
																				<input type="hidden" name="serviceMembershipDiscountAmt" id="serviceMembershipDiscountAmt">
																			</div>
																		</fieldset>
																	</div>


																	<div class="col-md-4 m-0 p-5">
																		<fieldset class="border" style="background-color: #e7e6e6;">
																			<legend class="legend-inner float-none w-auto required">Service Amount<span class="mandate">*</span></legend>
																			<div class="input-group">
																				<i class="fa fa-location fa2"></i>
																				<input type="text" class="form-control2 form-control rounded" name="serviceAmountBoxNew" id="serviceAmountBoxNew" placeholder="Service Amount*" value="" readonly style="background-color: #e7e6e6;">
																			</div>
																		</fieldset>
																	</div>


																	<div class="col-md-3 m-0 p-5 d-none">
																		<fieldset class="border">
																			<legend class="legend-inner float-none w-auto required">Service Date<span class="mandate">*</span></legend>
																			<div class="input-group">
																				<i class="fa fa-calendar fa2"></i>
																				<input placeholder="MM/DD/YYYY" class="form-control2 form-control rounded " id="serviceDate" name="serviceDate" type="text" readonly>
																			</div>
																		</fieldset>
																	</div>

																	<div class="col-md-3 m-0 p-5" style="margin-top: 6px !important;">
																		<fieldset class="border">
																			<legend class="legend-inner float-none w-auto required">Service Time<span class="mandate">*</span></legend>
																			<div class="input-group">
																				<i class="fa fa-clock-o fa2"></i>

																				<input type='text' class='time_picker_start hasTimepicker start' name="serviceTime" id="serviceTime" placeholder='00:00' style="border: none;
    padding-left: 12px;
    margin-top: 10px;">


																			</div>
																		</fieldset>

																	</div>

																	<div class="col-md-5 m-0 p-5">
																		<fieldset class="border">
																			<legend class="legend-inner float-none w-auto required">Priests<span class="mandate">*</span></legend>
																			<div class="input-group">
																				<select id="priestName" name="priestName" style="color:black!important;" class="form-control2 form-control rounded  form-select">
																					<option value="" selected disabled>Select Preferred Priest</option>

																					<!-- <option value="Any Priest" email="" phone="" priestId="0">Any Priest</option> -->

																				</select>

																				<input type="hidden" name="priestPhone" id="priestPhone" value="<?= json_decode(@$userDetails->priestPhone); ?>">
																				<input type="hidden" name="priestEmail" id="priestEmail" value="<?= json_decode(@$userDetails->priestEmail); ?>">
																				<input type="hidden" name="priestId" id="priestId" value="<?= @$userDetails->requestedPriestId; ?>">
																			</div>

																		</fieldset>
																	</div>
																	<!-- <div class="col-md-6 m-0 p-5" style="display: flex; align-items: center; flex-direction: row-reverse;">
																	<div class="form-check form-check-inline mx-4">
																		<input class="form-check-input" type="checkbox" id="inlineCheckbox" name="confirmByPriest">
																		<label class="form-check-label" style="padding-top: 10px !important;  padding-left: 20px;" for="inlineCheckbox">Already Confirmed By Priest</label>
																	</div>
																</div> -->



																	<div class="col-md-3 m-0 p-5 d-none">
																		<fieldset class="border">
																			<legend class="legend-inner float-none w-auto required">Select Venue<span class="mandate">*</span></legend>
																			<div class="input-group">
																				<select name="selectVenue" id="selectVenue" style="color:black!important;" class="form-control2 form-control rounded  form-select">
																					<option value="Same as Temple Address">Same as Temple Address</option>
																				</select>

																			</div>
																		</fieldset>

																	</div>

																	<div class="col-md-12 m-0 p-5 d-none">
																		<fieldset class="border" id="serviceAddressBox">
																			<legend class="legend-inner float-none w-auto required">Full Address</legend>
																			<div class="input-group">
																				<i class="fa fa-location fa2"></i>

																				<input type="text" class="form-control2 form-control rounded " name="serviceAddress" id="serviceAddress" placeholder="Please enter your address*" value="">
																			</div>
																		</fieldset>
																	</div>

																	<div class="col-md-12 m-0 p-5 d-none">
																		<fieldset class="border">
																			<legend class="legend-inner float-none w-auto">Additional Info</legend>
																			<div class="input-group">
																				<textarea type="textarea" id="addtionalInfo" name="addtionalInfo" class="form-control2 form-control rounded form-text-area" placeholder="Please provide any additional details here."></textarea>

																				<input type="hidden" name="source" value="SERVICES-PAGE">
																			</div>
																		</fieldset>
																	</div>
																</div>

															</div>
															<div class="text-center my-3">
																<button type="submit" id="eventdetailsButtonn" class="btn btn-success d-none" style="background-color: var(--main-color-new-theme);padding: 5px 14px;color: #fff;border-radius: 6px!important;font-size: 17px;font-weight: 700;border: 0px!important;margin: 0px 8px;">SUBMIT</button>
															</div>
														</fieldset>

													</div>

													<input type="button" name="next" class="next action-button mx-3" style="float:right" value="Next" />
												</fieldset>

												<fieldset class="steps">
													<div class="mt-3">

														<!-- @@@@@@@@@@@@@@@@@@@@@@ Service Types @@@@@@@@@@@@@@@@@@@@@@@@@ -->


														<div class="tab-content" id="myTabContent">



															<div class="tab-pane table-responsive fade shadow panettttttttt show active" id="home-tab-pane" role="tabpanel" aria-labelledby="home-tab>" tabindex="0">


															</div>

														</div>
													</div>
													<input type="button" name="previous" style="float:left" class="previous action-button-previous" value="Previous" />
													<input type="button" name="next" style="float:right" class="next action-button mx-3" value="Next" />
												</fieldset>



												<fieldset class="steps">
													<div class="form-card">
														<div class="row justify-content-center">

															<div class="row g-0">
																<div class="col-lg-12 mx-auto" style="background-color:#f5f5f5;padding: 18px;">
																	<h3 class="fw-bold mb-0 text-black pb-3">Request Summary</h3>

																	<div id="event_details">

																	</div>



																	<div id="request-summary-container">


																	</div>




																</div>
															</div>

														</div>
													</div>

													<input type="button" name="previous" class="previous action-button-previous" style="float:left" value="Previous" />
													<input type="button" name="next" class="btn btn-success mx-3" style="background-color: var(--main-color-new-theme); padding: 13px 19px; color: #ffffff; border-radius: 6px !important; font-size: 14px; font-weight: 1000; border: 0px !important; margin: 10px 0px; float: right;" onclick="CartCheckLogin('facilities')" value="<?= $formAction == 'REQUEST WITH PAYMENT' || $formAction == "BOOKING WITH PAYMENT" ? 'Book Now' : 'Send Request' ?>" />
												</fieldset>
											</form>
										</div>
									</div>
								</div>
							</div>



							<!-- Modal T&C -->
							<div class="modal modal-lg fade" id="term_and_conditions" tabindex="-1" aria-labelledby="term_and_conditionsLabel" aria-hidden="true">
								<div class="modal-dialog modal-dialog-scrollable">
									<div class="modal-content">
										<div class="modal-body">

											<div id="rules-regulations">
												<h2>Terms and Conditions for Use of <?= camelcase(GetProjectName()); ?>'s Facilities</h2>
												<ol>
													<li>
														This is a sample text only. Please specify your temple's specific Rentals details to be replaced here.
													</li>


											</div>
											<div class="modal-footer">
												<div class="row" style="width: 100%;">

													<div class="col-sm text-start" style="width: 50%;">
														<input type="button" name="next" class="btn btn-danger" style="width: 100px;height: 45px;border-radius: 5px !important;" id="cancel" value="Cancel" />
													</div>
													<div class="col-sm text-end" style="width: 50%;">
														<input type="button" name="next" class="btn btn-success" id="accept" style="width: 100px;height: 45px;background-color: #198754 !important;border-radius: 5px !important;" value="Accept" />

													</div>
												</div>



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

							</div>


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

				<!-- <input type="text" class="timeSum"> -->

	</section>
	<!-- End Coming Soon -->


	<div class="modal fade" id="paymentModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true" data-keyboard="false" data-backdrop="static">
		<div class="modal-dialog modal-dialog-centered" role="document">
			<div class="modal-content">


				<div class="modal-header text-center">
					<h5 class="modal-title bottomborder modatTitle">CHECKOUT</h5>
					<button type="button" class="btn-close modalCloseBtn <?= @$modalClbtn; ?>" data-bs-dismiss="modal" aria-label="Close"></button>
				</div>
				<div class="modal-body">
					<div class="container">
						<img src="<?= ApiBaseUrl()['url'] . @$header_data[0]['leftImage'] ?>" class="img-fluid mb-4" height="100px" width="100px" style="display: block;margin-left: auto;margin-right: auto;">
						<div class="row d-flex justify-content-center align-items-center" style="margin-left: 50px;margin-right: 50px;">
							<div class="col-xl-12">
								<div class="row g-0">
									<div class="col-xl-12">
										<div class="row">
											<div class="col-md-12 mb-4">
												<table class="table table-responsive table-bordered text-center">

													<tbody>
														<tr>
															<th>
																<h5 class="h5-title">Amount to Pay</h5>
															</th>

															<td id="edittable">

															</td>
														</tr>
													</tbody>
												</table>
											</div>
										</div>

										<div class="">
											<div class="row">

												<div class="col-md-12">


													<?php if (isset($paymentSetting) && $paymentSetting == 'PAYPAL' && $paymentSeverOn == 1) { ?>

														<div class="oooooookkakak" id="paypal-button-container-membership"></div>

													<?php } else if (isset($paymentSetting) && ($paymentSetting == 'MPI' || $paymentSetting == 'MPITEST') && $paymentSeverOn == 1) { ?>


														<link rel="stylesheet" href="<?= base_url('assets/css/mpi-form.css'); ?>">

														<form id="paymentForm" action="https://www.bridgepaynetsecuretx.com/WebSecurity/echo.aspx" method="post" style=" max-width: 500px;margin: auto;">
															<div class="row px-0">
																<div class="col-md-12 px-0">
																	<h6 class="text-center">Card Details</h6>
																	<div id="card" class="mx-0" style="width: 100%!important;height: 150px;"></div>
																	<div id="errorMessage" style="margin-bottom: 10px; color: #c0392b;"></div>
																</div>
																<div class="col-md-12 px-0">
																	<!-- <h6 class="text-center">Billing Address</h6> -->
																	<p for="fname" style="text-align: justify;margin-bottom: 0px;font-weight: 600;">Name on Card <span class="text-danger">*</span></p>
																	<input type="text" class="form-control" id="fname" name="firstname" placeholder="Enter Your Full Name*" required style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= @$current_user->refDataName; ?>">
																	<!-- <input type="email" id="email" class="form-control" name="email" placeholder="Enter Your Email Address*" required style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= base64_decode(@$current_user->email); ?>" oninput="this.value = this.value.toLowerCase();"> -->
																	<!-- <input type="text" class="form-control" id="address" name="address" placeholder="Enter Your Street Address" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= @$current_user->addressLine1; ?>"> -->
																	<p for="zipcode" style="text-align: justify;margin-bottom: 0px;font-weight: 600;">ZIP Code <span class="text-danger">*</span></p>
																	<input type="number" class="form-control" id="mpizipcode" name="mpizipcode" placeholder="Enter Your Zipcode" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= @$current_user->zip; ?>">

																	<!-- <div class="row m-0 p-0">
																			<div class="col-md-12 px-0">
																				<input type="text" id="state" name="state" placeholder="State" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= @$current_user->stateTypes; ?>">
																			</div> -->
																	<!-- <div class="col-md-12 px-0">
																				<input type="text" id="city" name="city" placeholder="City" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= @$current_user->cityTypes; ?>">
																			</div>
																		</div> -->

																	<center>
																		<button type="submit" class="btn btn-success" style="max-width: 500px;margin: auto;border-radius: 4px!important;font-weight: 800;padding: 8px 24px;background: #e78b00;border: 0;text-shadow: 1px 1px 0px black;">PAY NOW</button>
																	</center>
																</div>
															</div>

														</form>

														</form>



													<?php } else if (isset($paymentSetting) && $paymentSetting == 'CHARGEANYWHERE' && $paymentSeverOn == 1) { ?>


														<iframe id="paymentIframe" title="Payment Page" width="100%" height="600px"></iframe>

													<?php } ?>

													<button type="button" class="btn PaymentClosebtn btn-danger ms-2" data-dismiss="modal" hidden>CLOSE</button>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>

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

</main><!-- End #main -->
<?php
$TempleAddress = getclientInfoById()['data'][0];
$TempleAddress = $TempleAddress['addressLineOne'] . ' ' . $TempleAddress['addressLinetwo'] . ' ' . $TempleAddress['state'] . ' ' . $TempleAddress['city'] . ' ' . $TempleAddress['zipCode'];
?>


<?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>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script>

<script type="text/javascript">
	function submitEventDetailsForm() {

		var formData = $('#msform').serialize();

		$.ajax({
			type: "POST",
			url: "<?= base_url('facilitiesContollers/Facilities/SubmitEventForm'); ?>",
			data: formData,
			success: function(result) {
				console.log(result);
			}
		});
	}


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



	$('#accept').click(function() {

		$('#term_and_conditions').modal('hide');

		$("#action-button").click();
	});




	var current_fs, next_fs, previous_fs;
	var opacity;
	var current = 1;
	var steps = $(".steps").length;

	setProgressBar(current);

	$(".next").click(function() {



		if ($("#eventName").val() == "") {
			alert("Please add event name!");
			return false;
		}
		if ($("#eventDate").val() == "") {
			alert("Please add event date!");
			return false;
		}

		if ($("#eventTime").val() == "") {
			alert("Please add event from time!");
			return false;
		}

		// if($("#eventEndTime").val() == ""){
		//   alert("Please add event to time!");
		//   return false;
		// }

		if ($("#adults").val() == "") {
			alert("Please add Estimated Number of Attendees!");
			return false;
		}
		if ($('input[name="add_service"]:checked').length <= 0) {
			alert("Please select Would you like to add Priest Services to your Facility Booking?");
			return false;
		}

		// if($("#children").val() == ""){
		//   alert("Please add Estimated Number of Children!");
		//   return false;
		// }

		// $('input[name="add_service"]').on('change', function () {
		// Check if the selected radio button has value "YES"
		if ($('input[name="add_service"]:checked').val() === "YES") {
			// alert($("#priestName").val());
			if ($("#serviceName").val() == "" || $("#serviceName").val() == null || $("#serviceName").val() == undefined) {
				alert("Please select service!");
				return false;
			}


			if ($("#serviceAmountBoxNew").val() == "") {
				alert("Please select service!");
				return false;
			}


			if ($("#serviceTime").val() == "") {
				alert("Please select service time!");
				return false;
			}

			if ($("#priestName").val() == "" || $("#priestName").val() == null || $("#priestName").val() == undefined) {
				alert("Please select priest!");
				return false;
			}


		}
		// });




		$(".datepicker-services").val($("#eventDate").val());



		// $(".time_picker_start").val($("#eventTime").val());
		// $(".time_picker_end").val($("#eventEndTime").val());


		if (current == 1) {
			loader.on();

			$.ajax({
				type: "POST",
				url: "<?= base_url('facilitiesContollers/Facilities/getfacilityAvailbility'); ?>",
				data: {
					serviceDate: $("#eventDate").val(),
					targetTime: $("input[name='eventTime']").val(),
					facilityId: '',
					participant: $("input[name='adults']").val()
				},
				success: function(result) {
					// Load the result into the target element
					$("#home-tab-pane").html(result);
					$(".datepicker-services").val($("#eventDate").val());
					loader.off();
					// Ensure the time pickers are initialized after the content is loaded
					setTimeout(function() {
						// Initialize time picker for dynamically loaded fields
						let minTime = calculateMinTime();
						$('#home-tab-pane .time_picker_start').timepicker({
							timeFormat: 'h:mm p', // 12-hour format with AM/PM
							interval: 30, // Interval of 30 minutes
							// minTime: '12:00 AM', // Minimum time (optional)
							minTime: minTime, // Minimum time (optional)
							maxTime: '11:00 PM', // Maximum time (optional)
							dynamic: false, // Whether the time options change dynamically
							dropdown: true, // Enable dropdown menu for time options
							scrollbar: true, // Add a scrollbar
							change: function(time) { // Callback function when time is changed
								console.log('Selected Time: ', formatTime(time));
								let service_id = $(this).attr('data-id');
								setTimeManually(this, service_id);
							},
							// Format the dropdown options
							beforeShow: function(input, inst) {
								// Get all dropdown options and format them
								setTimeout(function() {
									inst.timepicker.timeList.each(function() {
										var $this = $(this);
										var formattedTime = formatTime(new Date('1970-01-01T' + $this.text()));
										$this.text(formattedTime);
									});
								}, 10);
							}
						});

						$('#home-tab-pane .time_picker_end').timepicker({
							timeFormat: 'h:mm p', // 12-hour format with AM/PM
							interval: 30, // Interval of 30 minutes
							// minTime: '12:30 AM', // Minimum time (optional)
							minTime: $("input[name='eventTime']").val(), // Minimum time (optional)
							maxTime: '11:00 PM', // Maximum time (optional)
							dynamic: false, // Whether the time options change dynamically
							dropdown: true, // Enable dropdown menu for time options
							scrollbar: true, // Add a scrollbar
							change: function(time) { // Callback function when time is changed
								console.log('Selected Time: ', formatTime(time));
								// alert("ok");'
								console.log('Selected Time: ', formatTime(time));
								let service_id = $(this).attr('data-id');
								setTimeManually(this, service_id);
							},
							// Format the dropdown options
							beforeShow: function(input, inst) {
								// Get all dropdown options and format them
								setTimeout(function() {
									inst.timepicker.timeList.each(function() {
										var $this = $(this);
										var formattedTime = formatTime(new Date('1970-01-01T' + $this.text()));
										$this.text(formattedTime);
									});
								}, 10);
							}
						});
					}, 500); // Delay initialization by 500 milliseconds to ensure DOM is ready
				}
			});





		} else if (current == 2) {
			var checkboxes = $("input[name='services_id\\[\\]']:checked");
			// alert(checkboxes.length);
			if (checkboxes.length <= 0) {
				alert("Please choose at least one rental option.");
				return false;
			}

			submitEventDetailsForm();

			var html = '<fieldset class="border-2 bg-white"><div class="row">';


			var dataObject = {
				"Event Name": $("#eventName").val(),
				"Event Date": $("#eventDate").val(),
				// "Event Time": $("#eventTime").val(),
				// "Event End Time": $("#eventEndTime").val(),
				"Event Address": $("#eventLocation").val(),
				"Event State": $("#stateSelect").val(),
				"Event City": $("#city").val(),
				"Event Language": $("#preferredLanguage").val(),
				"Adults": $("#adults").val(),
				// "Children": $("#children").val(),
				"Zip": $("#zipcode").val(),
				"Event Description": $("#eventDescription").val()
			};


			$.each(dataObject, function(key, value) {
				if (value !== '' && value !== null) {


					html += '<div class="col-md-4"> <fieldset class="border"> <legend  class="legend-inner float-none w-auto">' + key + '</legend> <div class="input-group"> <input type="text" class="form-control form-control2" value="' + value + '" readonly disabled> <span class="mandate"></span> </div> </fieldset> </div>';
				}
			});

			html += '</div></fieldset>';

			$("#event_details").html(html);
			loader.on();
			$.ajax({
				type: "POST",
				url: "<?= base_url('facilitiesContollers/Checkout/updateRequestDetailsWithoutReloadingPage'); ?>",
				success: function(result) {


					$("#request-summary-container").html(result);

					loader.off();

				}
			});
		}




		current_fs = $(this).parent();
		next_fs = $(this).parent().next();

		$("#progressbar li").eq($(".steps").index(next_fs)).addClass("active");

		next_fs.show();



		current_fs.animate({
			opacity: 0
		}, {
			step: function(now) {
				opacity = 1 - now;

				current_fs.css({
					'display': 'none',
					'position': 'relative'
				});
				next_fs.css({
					'opacity': opacity
				});
			},
			duration: 500
		});
		setProgressBar(++current);




	});




	$(".previous").click(function() {

		current_fs = $(this).parent();
		previous_fs = $(this).parent().prev();

		$("#progressbar li").eq($(".steps").index(current_fs)).removeClass("active");

		previous_fs.show();

		current_fs.animate({
			opacity: 0
		}, {
			step: function(now) {
				opacity = 1 - now;

				current_fs.css({
					'display': 'none',
					'position': 'relative'
				});
				previous_fs.css({
					'opacity': opacity
				});
			},
			duration: 500
		});
		setProgressBar(--current);
	});


	function calculateMinTime() {
		const eventTime = $("input[name='eventTime']").val(); // Get the event time value
		if (!eventTime) return '12:00 AM'; // Default fallback if no time is selected

		const timeParts = eventTime.match(/(\d+):(\d+)\s*(AM|PM)/); // Extract hours, minutes, and AM/PM
		if (!timeParts) return '12:00 AM'; // Default fallback if parsing fails

		let hours = parseInt(timeParts[1], 10);
		let minutes = parseInt(timeParts[2], 10);
		const meridian = timeParts[3];

		// Add 30 minutes
		minutes += 30;
		if (minutes >= 60) {
			minutes -= 60;
			hours += 1;
		}

		// Handle 12-hour clock overflow
		if (hours > 12) hours -= 12;
		if (hours === 12) {
			if (meridian === 'AM') return `${hours}:${minutes.toString().padStart(2, '0')} PM`;
			else return `${hours}:${minutes.toString().padStart(2, '0')} AM`;
		}

		return `${hours}:${minutes.toString().padStart(2, '0')} ${meridian}`;
	}

	function setProgressBar(curStep) {
		var percent = parseFloat(100 / steps) * curStep;
		percent = percent.toFixed();
		$(".progress-bar")
			.css("width", percent + "%")
	}


	// });


	$(document).ready(function() {

		$('#cancel').click(function() {

			$('#term_and_conditions').modal('hide');
		});
	});

	$(document).ready(function() {

		$('.servicesDataTable').paging({
			limit: 20
		});
		$("[data-page='0']").click();
	});


	function showSection(selectElement, id) {
		loader.on();

		const selectedOption = selectElement.options[selectElement.selectedIndex];
		const selectedKey = selectedOption.getAttribute('key');
		const SelectedPrice = parseFloat(selectElement.value).toFixed(2);

		// Clear existing values for time inputs
		$("#start_time" + id).val('');
		$("#end_time" + id).val('');

		// Check if a shift key is provided
		if (selectedKey) {
			const shift = selectedKey.trim().toUpperCase();

			// Fetch shift timings
			$.ajax({
				type: "POST",
				url: "<?= base_url('facilitiesContollers/Facilities/getShiftTimings'); ?>",
				data: {
					shift: shift,
					facilities_shift: <?= json_encode($facilities_shift) ?>,
					serviceTime: $("#eventTime").val()
					// serviceTime: $("#serviceTime").val()
				},
				dataType: "json",
				success: function(result) {
					// Set shift start and end times
					// console.log("result=====");
					// console.log(result);
					// $("#start_time" + id).val(result.startTime);
					$("#start_time" + id).val(result.startTime ? result.startTime : $("#eventTime").val());

					// $("#start_time" + id).val($("#serviceTime").val());
					$("#end_time" + id).val(result.endTime);
					$("#time_section_" + id).removeClass('d-none');
					$("#date_section_" + id).removeClass('d-none');
					// $("#time_section_" + id).attr('required',true);
					// $("#date_section_" + id).attr('required',true);
					// console.log("fetchShiftTimingRules");
					// If the selected shift is not a full day part, fetch timing rules
					if (!['morning', 'afternoon', 'evening', 'full day', 'half day', 'hourly'].includes(selectedKey.trim().toLowerCase())) {
						// console.log("fetchShiftTimingRules");
						$("#start_time" + id).prop('disabled', true);
						$("#end_time" + id).prop('disabled', false);
						fetchShiftTimingRules(id, shift, SelectedPrice, selectedKey);
					} else if (['morning', 'afternoon', 'evening', 'full day', 'half day'].includes(selectedKey.trim().toLowerCase())) {
						// console.log("fetchShiftTimingRules");
						$("#start_time" + id).prop('disabled', true);
						$("#end_time" + id).prop('disabled', true);
					} else {
						// console.log("clearTimingRuleAttributes");
						$("#start_time" + id).prop('disabled', false);
						$("#end_time" + id).prop('disabled', false);

						var eventTime = result.startTime ? result.startTime : $("#eventTime").val();
						var eventDate = $("#eventDate").val();
						var eventDateTime = new Date(eventDate + ' ' + eventTime);

						var maxSelectableTime = new Date(eventDateTime.getTime() + 0.5 * 60 * 60 * 1000);
						var maxTimeFormatted = formatTime(maxSelectableTime);
						$("#end_time" + id).timepicker('destroy').timepicker({
							timeFormat: 'h:mm p', // 12-hour format with AM/PM
							interval: 30, // Interval of 5 minutes
							minTime: maxTimeFormatted, // Dynamically set minTime
							maxTime: '11:30 PM', // Dynamically set minTime
							dynamic: false,
							dropdown: true,
							scrollbar: true,
							change: function(time) { // Callback function when time is changed
								console.log('Selected Time: ', formatTime(time));
								// alert("ok");'
								console.log('Selected Time: ', formatTime(time));
								CheckAValibilityTime(id);
								setTimeManually(this, id);
							},
							// Format the dropdown options
							beforeShow: function(input, inst) {
								// Get all dropdown options and format them
								setTimeout(function() {
									inst.timepicker.timeList.each(function() {
										var $this = $(this);
										var formattedTime = formatTime(new Date('1970-01-01T' + $this.text()));
										$this.text(formattedTime);
									});
								}, 10);
							}
						});
						// Clear timing rule attributes for non-hourly selections
						clearTimingRuleAttributes(id);
					}

					// Update total price and checkbox attributes
					updatePriceAndCheckboxAttributes(id, SelectedPrice, selectedKey);
				}
			});
		} else {

			$("#date_section_" + id).removeClass('d-none');
			$("#time_section_" + id).addClass('d-none');
			// $("#time_section_" + id).attr('required',false);
			// $("#date_section_" + id).attr('required',false);
		}

		loader.off();
	}

	// Separate function to fetch shift timing rules and set attributes
	function fetchShiftTimingRules(id, shift, SelectedPrice, selectedKey) {
		$.ajax({
			type: "POST",
			url: "<?= base_url('facilitiesContollers/Facilities/getShiftTimingsRules'); ?>",
			data: {
				shift: shift,
				facilities_shift: <?= json_encode($facilities_shift) ?>,
				hourlyBookingRules: <?= json_encode($hourlyBookingRules) ?>,
				serviceTime: $("#eventTime").val()
			},
			dataType: "json",
			success: function(result) {
				$("#checkbox_" + id).attr("disabled", true);
				$("#start_time" + id).val(result.StartTimeValue);
				$("#end_time" + id).val(result.EndTimeValue);
				// console.log(result);
				// console.log("#start_time ftime= " + result.hourFrom);
				var eventTime = $("#eventTime").val();
				var eventDate = $("#eventDate").val();
				$("#start_time" + id).prop('disabled', true);
				if (result.hourFrom == result.hourTo && result.hourTo > 0) {
					$("#end_time" + id).prop('disabled', true);
				}
				$("#start_time" + id).attr('data-hourFrom', result.hourFrom).attr('data-hourTo', result.hourTo);
				$("#end_time" + id).attr('data-hourFrom', result.hourFrom).attr('data-hourTo', result.hourTo);

				var eventDateTime = new Date(eventDate + ' ' + eventTime); // Parse into Date object
				console.log("eventDateTime: " + eventDateTime);
				loader.on();
				getfacilityAvailbilityStatus(id, result.StartTimeValue, result.EndTimeValue);
				if (!isNaN(eventDateTime.getTime())) {
					var maxSelectableTime = new Date(eventDateTime.getTime() + result.hourFrom * 60 * 60 * 1000);
					var maxTimeFormatted = formatTime(maxSelectableTime);
					$("#end_time" + id).timepicker('destroy').timepicker({
						timeFormat: 'h:mm p', // 12-hour format with AM/PM
						interval: 30, // Interval of 5 minutes
						minTime: result.EndTimeValue, // Dynamically set minTime
						maxTime: maxTimeFormatted, // Dynamically set minTime
						dynamic: false,
						dropdown: true,
						scrollbar: true,
						change: function(time) { // Callback function when time is changed
							console.log('Selected Time: ', formatTime(time));
							// alert("ok");'
							console.log('Selected Time: ', formatTime(time));
							getfacilityAvailbilityStatus(id, result.StartTimeValue, time);
							setTimeManually(this, id);

						},
						// Format the dropdown options
						beforeShow: function(input, inst) {
							// Get all dropdown options and format them
							setTimeout(function() {
								inst.timepicker.timeList.each(function() {
									var $this = $(this);
									var formattedTime = formatTime(new Date('1970-01-01T' + $this.text()));
									$this.text(formattedTime);
								});
							}, 10);
						}
					});
					console.log("Max Time Formatted: " + maxTimeFormatted);
				} else {
					$("#end_time" + id).timepicker('destroy').timepicker({
						timeFormat: 'h:mm p', // 12-hour format with AM/PM
						interval: 30, // Interval of 5 minutes
						minTime: result.EndTimeValue, // Dynamically set minTime
						maxTime: "11:00 PM", // Dynamically set minTime
						dynamic: false,
						dropdown: true,
						scrollbar: true
					});
				}







			}
		});
	}

	function CheckAValibilityTime(id) {
		console.log("CheckAValibilityTime" + id);
		var StartTimeValue = $("#start_time" + id).val();
		var EndTimeValue = $("#end_time" + id).val();
		console.log(StartTimeValue);
		console.log(EndTimeValue);
		if (StartTimeValue && EndTimeValue) {
			getfacilityAvailbilityStatus(id, StartTimeValue, EndTimeValue);
		}
	}

	// Clear timing rule attributes
	function clearTimingRuleAttributes(id) {
		// console.log("#start_time e time" + id);

		$("#start_time" + id).attr('data-hourFrom', "").attr('data-hourTo', "");
		$("#end_time" + id).attr('data-hourFrom', "").attr('data-hourTo', "");
	}

	// Update price and checkbox attributes
	function updatePriceAndCheckboxAttributes(id, SelectedPrice, selectedKey) {
		const spanId = "Totalprice_" + id;
		const checkboxId = "checkbox_" + id;

		$("#" + spanId).text('$ ' + SelectedPrice);
		$("#start_time" + id).attr('initial-hourly-amt', SelectedPrice);
		$("#end_time" + id).attr('initial-hourly-amt', SelectedPrice);

		$("#" + checkboxId).attr('data-price', SelectedPrice);
		$("#" + checkboxId).attr('data-servicedesc', selectedKey);
	}

	function getfacilityAvailbilityEndStatus(endTime, id) {
		var startTime = $("#start_time" + id).val();
		getfacilityAvailbilityStatus(facilityId, startTime, endTime);
	}

	function getfacilityAvailbilityStatus(facilityId, targetTime, targetEndTime) {
		loader.on();
		$.ajax({
			type: "POST",
			url: "<?= base_url('facilitiesContollers/Facilities/getfacilityAvailbilityStatus'); ?>",
			data: {
				serviceDate: $("#eventDate").val(),
				targetTime: targetTime,
				targetEndTime: targetEndTime,
				facilityId: facilityId,
				participant: $("input[name='adults']").val()
			},
			success: function(result) {
				loader.off();
				if (result == 1) {
					$("#checkbox_" + facilityId).removeAttr("disabled");
					$("#checkbox_" + facilityId).removeClass("d-none");
					$("#avlDiv" + facilityId).addClass("d-none");
				} else {
					$("#checkbox_" + facilityId).prop("disabled", true);
					$("#checkbox_" + facilityId).prop("checked", false);
					// $("#checkbox_" + facilityId).addClass("d-none");
					$("#avlDiv" + facilityId).removeClass("d-none");
					addTocart();
					alert("Service not available for selected date and time");
				}
			}
		});
	}

	function addTocart(element) {

		var totalPrice = 0;
		var cart_type = 'FACILITIES';
		var ids = [];
		var qty = [];
		var ctg = [];
		var serviceTypes = [];
		var serviceName = [];
		var startDate = [];
		var startTime = [];
		var serviceAmount = [];
		var description = [];
		var image = [];
		var bookingTypes = [];
		var start_time = [];
		var end_time = [];
		var service_desc = [];
		var is_membership_discount = [];
		var membershipDiscountedAmt = [];
		var initial_amt_hourly = [];

		var checked_id = $(element).attr('data-id');


		var bookingType_id = "booking_type" + checked_id;
		var start_time_id = "start_time" + checked_id;
		var end_time_id = "end_time" + checked_id;


		if ($("#" + bookingType_id).length > 0) {
			console.log(bookingType_id);
			var bookingTypeValue = $("#" + bookingType_id).val();

			if (bookingTypeValue === null || bookingTypeValue === "") {
				$(element).prop('checked', false);
				$("#" + bookingType_id).focus();
				$("#" + bookingType_id).notify(
					"Please select shift!", {
						position: "right"
					}
				);
				return false;
			}
		}

		if ($("#" + start_time_id).length > 0) {
			console.log(start_time_id);

			var start_timeValue = $("#" + start_time_id).val();

			if (start_timeValue === null || start_timeValue === "") {
				$(element).prop('checked', false);
				$("#" + start_time_id).focus();
				$("#" + start_time_id).notify(
					"Please select start time!", {
						position: "right"
					}
				);
				return false;
			}
		}

		if ($("#" + end_time_id).length > 0) {
			console.log(end_time_id);
			var end_timeValue = $("#" + end_time_id).val();

			if (end_timeValue === null || end_timeValue === "") {
				$(element).prop('checked', false);
				$("#" + end_time_id).focus();
				$("#" + end_time_id).notify(
					"Please select end time!", {
						position: "right"
					}
				);
				return false;
			}
		}

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

			var init_qty = parseInt($("#quantity-input" + id).val());
			init_qty = init_qty ? parseInt(init_qty) : 1;
			totalPrice = parseFloat(totalPrice) + (parseFloat($(this).attr('data-price')) * init_qty);
			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'));

			description.push($(this).attr('data-description').replace(/['"`]/g, ''));


			var keyAttribute = $(this).attr("data-servicedesc");


			bookingTypes.push(keyAttribute);
			start_time.push($("#start_time" + id).val());
			end_time.push($("#end_time" + id).val());

			startDate.push($("#datepicker_" + id).val());
			startTime.push($("#timepicker_" + id).val());
			serviceAmount.push($(this).attr('data-price'));
			ids.push($(this).attr('data-id'));
			qty.push(init_qty);
			is_membership_discount.push($(this).attr('is_membership_discount'));
			membershipDiscountedAmt.push($(this).attr('membership_discount_amt'));
			initial_amt_hourly.push($("#start_time" + id).attr('initial-hourly-amt'));


			service_desc.push($(this).attr('data-servicedesc'));
		});
		console.log("totalPrice");
		console.log(totalPrice);
		$(".cart-count").text(ids.length);
		$(".allPrice").text((totalPrice / 1).toFixed(2));
		$.ajax({
			type: "POST",
			url: "<?= base_url('facilitiesContollers/Facilities/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,
				bookingTypes: bookingTypes,
				start_time: start_time,
				end_time: end_time,
				is_membership_discount: is_membership_discount,
				is_membershipDiscountedAmt: membershipDiscountedAmt,
				service_desc: service_desc,
				initial_amt_hourly: initial_amt_hourly
			},
			success: function(result) {
				console.log(result);

			}
		});
	}

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

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

	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 subTotal = init_qty * initialResultAmt;

			$("#Totalprice_" + id).text("$ " + subTotal.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 subTotal = init_qty * initialResultAmt;


		$("#Totalprice_" + id).text("$ " + subTotal.toFixed(2));
		addTocart();
	}


	function ViewCart() {
		// if ($(".cart-count").text() > 0) {
		// 	window.location.href = "<?= base_url('facilitiesContollers/Facilities/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) {

		$('#term_and_conditions').modal('show');


		$('#accept').click(function() {

			if (parseInt($(".cart-count").text()) > 0) {


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


						if (data == 0) {
							var res = openLoginModal(page_name);

						} else {

							BookNow();

						}

					}
				});

			} 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');
	}




	var tithiDates = [];

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

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

	$(document).on('click', '.datepicker-services', function() {
		var dayVal = $(this).attr('daytype');
		var nclickF = $(this);

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



				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) {
								$(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"];

								if (dayOfWeek.toUpperCase() === dayVal.toUpperCase()) {
									return [true];
								} else if (tithis.includes(dayVal.toUpperCase())) {

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




									var startDatearray = tithiDates.split(" ").pop().split(",");
									return [startDatearray.includes(dateInMMDDYYFormat)];



								} else {
									return [false];
								}
							}
						});
					}
				}

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

			}
		});

	});



	var $beginService = $('#serviceTime');


	var timeOptionsService = {
		interval: 5,
		minTime: $("#eventTime").val() != '' ? $("#eventTime").val() : '12:00 AM', // Dynamically set minTime
		maxTime: '11:00 PM',
		dropdown: true,
		change: function(time) {
			var $this = $(this);
			var service_id = $this.attr('data-id');
			fetchPriestAvailability();

		}
	};
	$beginService.timepicker(timeOptionsService);

	var $begin = $('.hasTimepicker.start');
	var $end = $('.hasTimepicker.end');

	var startTime, endTime;

	var timeOptions = {
		interval: 30,
		dropdown: true,
		change: function(time) {
			var $this = $(this);
			var service_id = $this.attr('data-id');
			getfacilityAvailbilityStatus(id, result.StartTimeValue, result.EndTimeValue);
			// Check if the booking type is "HOURLY"
			// let selectElement = document.getElementById("booking_type" + service_id);
			// let selectedOption = selectElement ? selectElement.options[selectElement.selectedIndex] : null;
			// let bookingType = selectedOption ? selectedOption.getAttribute("key").toUpperCase() : null;
			let selectElement = "";
			let selectedOption = "";
			let bookingType = "";
			// console.log("bookingType");
			// console.log("eventEndTime:" + $this.attr('id'));
			// end_time672c6b57317169e372ae155e
			if ($this.attr('id') != "eventEndTime" && $this.attr('id').substring("end_time".length) != "end_time") {
				var uniqueId = $this.attr('id').substring("start_time".length);
				// console.log(uniqueId);
				// console.log("uniqueId");
				var $startTimeElement = $("#start_time" + uniqueId);
				// console.log("Element:", $startTimeElement);

				var hourFrom = $startTimeElement.attr('initial-hourly-amt');
				var hourTo = $startTimeElement.attr('data-hourto');

				// alert("hourFrom:", hourFrom);
				// console.log("hourTo:", hourTo);
				// if (bookingType === "HOURLY") {
				selectElement = $("#booking_type" + uniqueId).get(0); // Get the native DOM element

				if (selectElement) { // Check if the element exists
					bookingType = selectElement.options[selectElement.selectedIndex].getAttribute("key").toUpperCase();
					// console.log("bookingType: " + bookingType);timeOptions
				} else {
					console.warn("Element #booking_type" + uniqueId + " not found.");
				}
				// 'hourly'
				if (['hourly'].includes(bookingType.trim().toLowerCase())) {
					console.log("djfhdjg");
					sumHours(service_id);
				} else if (!['morning', 'afternoon', 'evening', 'full day', 'half day', 'hourly'].includes(bookingType.trim().toLowerCase())) {
					// alert(bookingType);
					console.log("djfhdjg");
					if ($this.hasClass('start')) {
						var startTime = $this.val();
						setTimeManually(service_id, startTime);
					} else if ($this.hasClass('end')) {
						var endTime = $this.val();
					}
					// alert(service_id);
					// Calculate hours and update price only if booking type is HOURLY
					sumHours(service_id);
				}
			}
		}
	};

	$begin.timepicker(timeOptions);


	$end.timepicker();

	$end.on('focus', function() {
		$(this).select();
	});

	$begin.on("click focus", function() {
		$(this).select();
	});



	function setTimeManually($this, service_id) {
		let selectElement = $("#booking_type" + service_id).get(0);
		let bookingType = "";

		// Check for the booking type
		if (selectElement) {
			bookingType = selectElement.options[selectElement.selectedIndex].getAttribute("key").toUpperCase();
		}

		// Perform actions based on the booking type
		if (['hourly'].includes(bookingType.trim().toLowerCase())) {
			sumHours(service_id);
		} else if (!['morning', 'afternoon', 'evening', 'full day', 'half day'].includes(bookingType.trim().toLowerCase())) {
			if ($this.hasClass('start')) {
				// If it's the start time, update the end time options
				startTime = $this.val();
				updateEndTimeOptions(service_id, startTime);
			} else if ($this.hasClass('end')) {
				// If it's the end time, get the value of the end time
				endTime = $this.val();
			}

			// After setting the time, calculate the hours and update the price
			sumHours(service_id);
		}
	}


	function updateEndTimeOptions(service_id, startTime = '') {
		// console.log("Initial startTime:", startTime);

		// Check if startTime is provided
		if (startTime) {
			// Retrieve hourFrom and hourTo values from the HTML element
			var hourFrom = parseInt($("#start_time" + service_id).attr('data-hourfrom'), 10);
			var hourTo = parseInt($("#start_time" + service_id).attr('data-hourto'), 10);

			// Parse the start time
			var startParsed = parseTime(startTime);

			console.log("Parsed start time:", startParsed);
			console.log("hourFrom:", hourFrom);
			console.log("hourTo:", hourTo);

			// Check if all values are valid
			if (startParsed && !isNaN(hourFrom) && !isNaN(hourTo)) {
				// Calculate the next available time by adding hourTo as minutes to startParsed
				var nextTime = new Date(startParsed.getTime() + hourTo * 60 * 60 * 1000);
				var formattedNextTime = formatTime(nextTime);

				// Calculate the max selectable time by adding hourFrom as hours to startParsed
				var maxSelectableTime = new Date(startParsed.getTime() + hourFrom * 60 * 60 * 1000);
				var maxTimeFormatted = formatTime(maxSelectableTime);
				// console.log("maxSelectableTime: "+maxSelectableTime);
				// console.log("maxTimeFormatted: "+maxTimeFormatted);
				// Apply these times to the time picker
				$("#end_time" + service_id).timepicker('option', 'minTime', formattedNextTime);
				$("#end_time" + service_id).timepicker('option', 'maxTime', maxTimeFormatted);

				// Optionally, set the end time input to start from the next available time
				$("#end_time" + service_id).val(formattedNextTime);

				// console.log("Next available time (minTime):", formattedNextTime);
				// console.log("Max selectable time (maxTime):", maxTimeFormatted);
			} else {
				console.error("Invalid values detected:");
				// if (!startParsed) console.error("Parsed start time is invalid:", startParsed);
				// if (isNaN(hourFrom)) console.error("hourFrom is not a number:", hourFrom);
				// if (isNaN(hourTo)) console.error("hourTo is not a number:", hourTo);

				var nextTime = new Date(startParsed.getTime() + (30 * 60000)); // Add 30 minutes
				var formattedNextTime = formatTime(nextTime);
			}
		} else {
			console.error("Start time is missing; cannot proceed with updating end time options.");
			return; // Exit if no start time is provided
		}
	}




	function sumHours(service_id) {
		endTime = $("#end_time" + service_id).val();
		startTime = $("#start_time" + service_id).val();
		// alert(endTime);
		// alert(startTime);
		var hourFrom = $("#start_time" + service_id).attr('data-hourfrom');
		var hourTo = $("#start_time" + service_id).attr('data-hourto');
		console.log("hourTo: " + hourTo + "hourFrom: " + hourFrom);
		if ((isNaN(hourFrom) && isNaN(hourTo)) || ((hourTo == "" || hourTo == null) && (hourFrom == "" || hourFrom == null))) {
			if (startTime && endTime) {
				console.log("okkkkkkkkkkkkkkk");
				var startParsed = parseTime(startTime);
				var endParsed = parseTime(endTime);

				var formattedStartTime = formatTime(startParsed);
				var formattedEndTime = formatTime(endParsed);

				// alert('Start Time: ' + formattedStartTime);
				// alert('End Time: ' + formattedEndTime);

				var diff = (Math.abs(endParsed - startParsed) / 36e5).toFixed(2); // Difference in hours
				// alert(diff);

				var one_hour_amt = $("#start_time" + service_id).attr('initial-hourly-amt');
				// one_hour_amt = one_hour_amt.replace('$', '').trim();
				// alert("#start_time" + service_id);

				// Convert the hourly rate to a number
				var hourlyRate = parseFloat(one_hour_amt);

				// Calculate the total price
				var totalPrice = (diff * hourlyRate).toFixed(2);


				$("#Totalprice_" + service_id).text('$ ' + totalPrice);
				$("#checkbox_" + service_id).attr('data-price', totalPrice);

				// alert('Total Price: $' + totalPrice);

				// Optionally, set the total price to an input field
				// $input.val(totalPrice);
				addTocart();
			}
		}
	}

	function parseTime(time) {
		if (typeof time !== 'string') {
			console.error("Invalid time format:", time);
			return null; // Return null if time is not a string
		}
		var parts = time.match(/(\d+):(\d+) (\w+)/);
		var hours = parseInt(parts[1], 10);
		var minutes = parseInt(parts[2], 10);
		var period = parts[3].toLowerCase();

		if (period === 'pm' && hours < 12) {
			hours += 12;
		}
		if (period === 'am' && hours === 12) {
			hours = 0;
		}

		return new Date(1970, 0, 1, hours, minutes);
	}

	function formatTime2(date) {
		var hours = date.getHours();
		var minutes = date.getMinutes();
		var seconds = '00'; // Assuming no seconds in input time
		var period = 'AM';

		if (hours >= 12) {
			period = 'PM';
			if (hours > 12) {
				hours -= 12;
			}
		} else if (hours === 0) {
			hours = 12;
		}

		var formattedTime = ('0' + hours).slice(-2) + ':' +
			('0' + minutes).slice(-2) + ':' +
			seconds + ' ' + period;

		return formattedTime;
	}

	function formatTime(date) {
		var hours = date.getHours();
		var minutes = date.getMinutes();
		var period = 'AM';

		// Convert to 12-hour format
		if (hours >= 12) {
			period = 'PM';
			if (hours > 12) {
				hours -= 12;
			}
		} else if (hours === 0) {
			hours = 12;
		}

		// Add leading zero to hours and minutes if needed
		var formattedTime = ('0' + hours).slice(-2) + ':' +
			('0' + minutes).slice(-2) + ' ' + period;

		return formattedTime;
	}






	$(document).ready(function() {
		$('.event-timepicker').mdtimepicker();
	});



	$(document).on('click', '.event-datepicker', function() {
		if (!$(this).hasClass('hasDatepicker')) {
			$(this).datepicker({
				dateFormat: "mm/dd/yy",
				multidate: true, // Enable multiple dates selection if using a compatible plugin
				minDate: 0,
				onSelect: function(dateText) {
					// Set the value in serviceDate if the radio button with value "YES" is checked
					if ($('input[name="add_service"]:checked').val() === "YES") {
						$('#serviceDate').val(dateText);
						fetchPriestAvailability();
					}
				}
			});
		}
		$(this).datepicker('show');
	});



	$(".phone").on('input', function() {

		var phoneField = this;
		var phoneValue = phoneField.value;
		var output;
		phoneValue = phoneValue.replace(/[^0-9]/g, '');
		var area = phoneValue.substr(0, 3);
		var pre = phoneValue.substr(3, 3);
		var tel = phoneValue.substr(6, 4);
		if (area.length < 3) {
			output = "(" + area;
		} else if (area.length == 3 && pre.length < 3) {
			output = "(" + area + ")" + " " + pre;
		} else if (area.length == 3 && pre.length == 3) {
			output = "(" + area + ")" + " " + pre + " - " + tel;
		}
		phoneField.value = output;

	});




	function BookNow() {





		var formAction = '<?= $formAction ?>';

		if (formAction == 'REQUEST WITH PAYMENT' || formAction == "BOOKING WITH PAYMENT") {
			/* swal({
			  title: "Confirmation?",
			  text: "Please confirm your Facility Booking Request!",
			  type: "warning",
			  showCancelButton: true,
			  confirmButtonColor: "var(--main-color-new-theme)",
			  confirmButtonText: "Yes",
			  closeOnConfirm: false,
			  showLoaderOnConfirm: false
			},
			function() {*/

			var amt = parseFloat($("#inputAmount").val());
			console.log("amt====");
			console.log(amt);
			console.log($("#serviceAmount").val());
			// amt += parseFloat($("#serviceAmount").val());
			$("#edittable").html('<h4 id="servicePrice">' + amt.toFixed(2) + '</h4><input type="hidden" name="" value="' + amt.toFixed(2) + '" id="serviceAmt">');
			loader.off();
			$("#paymentModal").modal("show");
			// });
		} else {
			swal({
					title: "Confirmation?",
					text: "Please confirm your Facility Booking Request!",
					type: "warning",
					showCancelButton: true,
					confirmButtonColor: "var(--main-color-new-theme)",
					confirmButtonText: "Yes",
					closeOnConfirm: false,
					showLoaderOnConfirm: true
				},
				function() {
					var bookingType = '<?= $formAction ?>';
					$.ajax({
						url: "<?= base_url('facilitiesContollers/Facilities/BookFacilities') ?>",
						type: "POST",
						dataType: "json",
						data: {
							'paymentSource': "",
							'paymentStatus': "PENDING",
							'transactionId': "",
							'totalPrice': amt,
							'paymentType': '',
							'bookingType': bookingType,
						},
						success: function(response) {

							if (response.statusCode == 1) {
								swal({
										html: true,
										title: "Order No: " + response.data[0].invoiceNo,
										text: "Facility Booking Request submitted successfully. You will receive further communications from Temple Manager",
										type: "success",
										confirmButtonText: 'OK',
										confirmButtonColor: 'var(--main-color-new-theme)',
									},
									function() {
										window.location.href = "<?= base_url(); ?>";
									});


							} 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();
									});
							}

						}
					});

				});
		}






	}

	$(document).ready(function() {
		$("#checkoutButton").click(function() {
			var eventDetails = $("#eventName").val();
			var eventDate = $("#eventDate").val();
			$("#eventdetailsForm").submit();

		});

		$("#eventdetailsForm").submit(function(e) {
			e.preventDefault();
			if (this.checkValidity()) {
				BookNow();
			}
		});
	});



	function disableE(event) {
		var keyCode = event.keyCode || event.which;
		var char = String.fromCharCode(keyCode);
		if (char.toLowerCase() === 'e') {
			event.preventDefault();
		}
	}
</script>




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


<?php if ($paymentSeverOn == 1 && $paymentSetting == 'PAYPAL') { ?>
	<script type="text/javascript">
		<?php if ($isIncludeSankalpam_result == 'YES') { ?>
			$(document).ready(function() {
				var isNoSpouseChecked = '<?= @$userDetails->noSpouse ?>';

				if (isNoSpouseChecked == 'true') {
					$("#No_Spouse").prop("checked", true);
					$(".spouseSection").hide();
				} else {
					$("#No_Spouse").prop("checked", false);
					$(".spouseSection").show();
					var isNoFamilyChecked = '<?= @$userDetails->noFamily ?>';

					if (isNoFamilyChecked == 'true') {
						$("#No_Family_Member").prop("checked", true);
						$(".familyMemberSection").hide();
					} else {
						$("#No_Family_Member").prop("checked", false);
						$(".familyMemberSection").show();
					}

				}
			});




			$(document).ready(function() {
				$("#No_Family_Member").change(function() {
					if ($(this).is(":checked")) {
						$(".familyMemberSection").hide();
						$("#No_Family_Member").val('checked');
					} else {
						$(".familyMemberSection").show();
						$("#No_Family_Member").val('');
					}
				});
			});


			$(document).ready(function() {
				$("#No_Spouse").change(function() {
					if ($(this).is(":checked")) {
						$(".spouseSection").hide();
						$("#No_Spouse").val('checked');
					} else {
						$(".spouseSection").show();
						$("#No_Spouse").val('');
					}
				});
			});



			$(document).ready(function() {
				// Initially hide the PayPal button container
				$("#paypal-button-container").hide();

				// Function to check if the form is filled
				function isFormFilled() {
					var fname = $("#fname").val();
					var lname = $("#lname").val();
					var gothram = $("#gothram").val();
					var stars = $("#stars").val();
					var spouseName = $("#spouseName").val();
					var spouseStars = $("#spouseStars").val();
					var familyMember = $("#familyMember").val();
					var nakshtra = $("#nakshtra").val();
					var No_Family_Member = $("#No_Family_Member").is(":checked");
					var No_Spouse = $("#No_Spouse").is(":checked");

					// Check conditions based on checkbox states
					if (No_Family_Member && No_Spouse) {
						return fname && lname && gothram;
					} else if (No_Family_Member) {
						return fname && lname && gothram && spouseName
					} else if (No_Spouse) {
						return fname && lname && gothram && familyMember
					} else {
						return fname && lname && gothram && spouseName && familyMember;
					}
				}

				function updatePayPalButtonVisibility() {
					if (isFormFilled()) {
						$("#paypal-button-container").show();
						$("#error-alert").html('');
					} else {
						$("#paypal-button-container").hide();
						$("#error-alert").html('<div class="alert alert-danger d-flex align-items-center" role="alert"> <i class="fa fa-warning"></i> <div> Please fill all required fields then the PayPal button will be automatically displayed. </div> </div>');
					}
				}
				$("#No_Family_Member, #No_Spouse").change(function() {
					updatePayPalButtonVisibility();
				});
				$("#sankalpamForm input, #sankalpamForm select").on("input", function() {
					updatePayPalButtonVisibility();
				});
				window.onload = function() {
					updatePayPalButtonVisibility();
				};
			});

		<?php } ?>






		$(document).ready(function() {
			var $totalPrice = $('#serviceAmountBox');


			<?php if (@$GeneralSettings['AcharyaSambhavana'] == 1) { ?>
				var $acharyaInput = $('#acharya-sambhavana-input');
				$acharyaInput.on('input', updateTotalPrice);

			<?php } ?>

			<?php if (@$GeneralSettings['GeneralDonationAmount'] == 1) { ?>
				var $generalInput = $('#general-donation-input');
				$generalInput.on('input', updateTotalPrice);
			<?php } ?>



			// Function to update the total price based on the input values
			function updateTotalPrice() {
				// Get the input values
				var acharyaValue = 0;
				var generalValue = 0;
				<?php if (@$GeneralSettings['AcharyaSambhavana'] == 1) { ?>
					var acharyaValue = parseFloat($acharyaInput.val().replace(/[^\d.-]/g, '')) || 0;
				<?php } ?>
				<?php if (@$GeneralSettings['GeneralDonationAmount'] == 1) { ?>
					var generalValue = parseFloat($generalInput.val().replace(/[^\d.-]/g, '')) || 0;
				<?php } ?>



				// Get the initial total price
				// var initialTotalPrice = parseFloat(<?= @$payNowTotalAmount; ?>) || 0;
				var initialTotalPrice = parseFloat(<?= @$s_total; ?>) || 0;

				// Calculate the new total price
				var newTotalPrice = initialTotalPrice + acharyaValue + generalValue;

				// Update the total price element
				$totalPrice.text('<?= $currencySymbol ?> ' + newTotalPrice.toFixed(2));
			}

			// Call updateTotalPrice once to include the initial total price
			updateTotalPrice();


			<?php if (@$GeneralSettings['AcharyaSambhavana'] == 1) { ?>
				// Disable arrow key inputs
				$acharyaInput.on('keydown', function(e) {
					if (e.which === 38 || e.which === 40) {
						e.preventDefault();
					}
				});
				// Add validation to prevent input of negative values
				$acharyaInput.on('keydown', function(e) {
					if (e.key === '-' || e.key === '+') {
						e.preventDefault();
					}
				});

				// Add validation to prevent input of "+" and "e" characters
				$acharyaInput.on('input', function() {
					$acharyaInput.val($acharyaInput.val().replace(/[+e]/gi, ''));
				});
			<?php } ?>
			<?php if (@$GeneralSettings['GeneralDonationAmount'] == 1) { ?>
				$generalInput.on('keydown', function(e) {
					if (e.which === 38 || e.which === 40) {
						e.preventDefault();
					}
				});

				$generalInput.on('keydown', function(e) {
					if (e.key === '-' || e.key === '+') {
						e.preventDefault();
					}
				});

				$generalInput.on('input', function() {
					$generalInput.val($generalInput.val().replace(/[+e]/gi, ''));
				});
			<?php } ?>

		});


		const paypalButtonsComponent = paypal.Buttons({
			style: {
				shape: 'rect',
				color: 'gold',
				layout: 'vertical',
				label: 'paypal',

			},

			createOrder: (data, actions) => {



				<?php if ($isIncludeSankalpam_result == 'YES') { ?>

					var familyMembers = [];
					var nakshtras = [];
					var rashi = [];
					var relationship = [];
					var dob = [];
					var anniversaryDate = [];


					$("input[name='family_member[]']").each(function() {
						var value = $(this).val();
						familyMembers.push(value);
					});

					$("select[name='nakshtra[]']").each(function() {
						var value = $(this).val();
						nakshtras.push(value);
					});

					$("input[name='dob[]']").each(function() {
						var value = $(this).val();
						dob.push(value);
					});

					$("select[name='rashi[]']").each(function() {
						var value = $(this).val();
						rashi.push(value);
					});

					$("select[name='relationship[]']").each(function() {
						var value = $(this).val();
						relationship.push(value);
					});

					$("input[name='anniversaryDate[]']").each(function() {
						var value = $(this).val();
						anniversaryDate.push(value);
					});


					var fname = $("#fname").val();
					var lname = $("#lname").val();
					var gothram = $("#gothram").val();
					var stars = $("#stars").val();


					var spouseName = $("#spouseName").val();
					var spouseStars = $("#spouseStars").val();


					var No_Family_Member = $("#No_Family_Member").val();
					var No_Spouse = $("#No_Spouse").val();


					$.ajax({
						url: "<?= base_url('UpdateProfileGlobal/UpdateProfile') ?>",
						type: "POST",
						dataType: "json",
						data: {

							'familyMembers': familyMembers,
							'nakshtras': nakshtras,
							'dob': dob,
							'rashi': rashi,
							'relationship': relationship,
							'anniversaryDate': anniversaryDate,
							'fname': fname,
							'lname': lname,
							'gothram': gothram,
							'stars': stars,
							'spouseName': spouseName,
							'spouseStars': spouseStars,
							"noSpouse": No_Spouse,
							"noFamily": No_Family_Member
						},
						success: function(response) {


							console.log(response);

						}
					});

				<?php } ?>


				var currency = "USD";

				amt = parseFloat($('#serviceAmountBox').text().replace('<?= $currencySymbol ?> ', '')) || 0;

				var paymentSource = data.paymentSource;

				var status = 'TEMP';

				var totalPrice = amt;

				var acharya_sambhavana = parseFloat($('#acharya-sambhavana-input').val()) || 0;
				var general_donation = parseFloat($('#general-donation-input').val()) || 0;



				var cart_data = SubmitformData;

				$.ajax({
					url: "<?= base_url('Services/AddToCart') ?>",
					type: "POST",
					dataType: "json",
					data: {

						'status': status,
						'paymentSource': paymentSource,
						'totalPrice': totalPrice,
						'acharya_sambhavana': acharya_sambhavana,
						'general_donation': general_donation,
						'cart_data': cart_data,
					},
					success: function(response) {

						loader.off();
						console.log(response);

					}
				});






				const createOrderPayload = {
					purchase_units: [{
						amount: {
							currency_code: currency,
							value: amt
						}
					}]
				};

				return actions.order.create(createOrderPayload);
			},


			onApprove: (data, actions) => {

				const captureOrderHandler = (details) => {



					loader.on();






					var status = 'COMPLETED';
					var transaction_id = details.purchase_units[0].payments.captures[0].id;

					$.ajax({
						url: "<?= base_url('Services/updateTransactionStatus') ?>",
						type: "POST",
						dataType: "json",
						data: {

							'status': status,
							'transaction_id': transaction_id,
							'paymentDescription': details
						},
						success: function(response) {
							loader.off();

							if (response.statusCode == 1) {

								swal({
										html: true,
										title: "Service Booking Confirmed!",
										text: "<span style='font-weight: 600;margin:5px;padding:5px;font-size: 27px !important;'>Receipt #: " + response.envoiceNo + '</span>',
										type: "success",
										confirmButtonText: 'OK',
										confirmButtonColor: 'var(--main-color-new-theme)',
									},

									function() {


										// window.location.reload();
										window.location.href = "<?= base_url('services') ?>";

									});

							} else {
								swal({
										html: true,
										title: "Failed!",
										text: "<span>Transaction Failed!<span><br><span style='font-weight: 600;margin:5px;padding:5px;font-size: 27px !important;'>Receipt #: " + response.envoiceNo + '</span>',
										type: "error",
										confirmButtonText: 'OK',
										confirmButtonColor: 'var(--main-color-new-theme)',
									},
									function() {
										window.location.reload();
									});
							}

						}
					});

				};

				return actions.order.capture().then(captureOrderHandler);
			},

			onError: (err) => {

				console.log(err);
				alert('Transaction Failed');

			}
		});

		paypalButtonsComponent
			.render("#paypal-button-container")
			.catch((err) => {
				console.log('PayPal Buttons failed to render');
			});

		function BookNow() {
			loader.on();
			swal({
					title: "Confirmation?",
					text: "Are you sure 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",
							success: function(response) {
								loader.off();
								if (response.statusCode == 1) {
									swal({
											html: true,
											title: "Service Request 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();
		}
	</script>

<?php } ?>










<?php

if (isset($paymentSetting) && ($paymentSetting == 'MPITEST' || $paymentSetting == 'MPI') && $paymentSeverOn == 1) { ?>

	<?php $mpiTokenPayId = @getclientInfoById()['data'][0]['MPItokenPay'];
	$MpiPayUrl = base_url('MPI_Payments/Paynow');
	if (isset($mpiTokenPayId) && $mpiTokenPayId != '' && $paymentSetting == 'MPI') {
		$TokenPay = $mpiTokenPayId;
	?>
		<script type="text/javascript" src="https://www.bridgepaynetsecuretx.com/Bridgepay.WebSecurity/TokenPay/js/tokenPay.js"></script>
	<?php
	} else {
		$TokenPay = 'tokenpay10579api20211508121542285';
		$MpiPayUrl = base_url('MPI_Payments/PaynowTest');
	?>
		<script type="text/javascript" src="https://www.bridgepaynetsecuretest.com/WebSecurity/TokenPay/js/tokenPay.js"></script>
	<?php
	}

	?>
	<script>
		var tokenpay = TokenPay('<?= $TokenPay ?>');
		tokenpay.initialize({
			dataElement: '#card',
			errorElement: '#errorMessage',
			amountElement: '#amount',
			useStyles: false,
			useACH: false,
			disableZip: true,
			disableCvv: false
		});

		var form = document.getElementById('paymentForm');
		form.addEventListener('submit', function(event) {


			loader.on();



			var formData1 = $("#serviceRequestForm").serializeArray();
			console.log("Serialized Form Data:", formData1);

			var cart_data = '<?= json_encode($cartList, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>';


			event.preventDefault();
			tokenpay.createToken(function(result) {

				console.log(result);


				var totalPriceText = $("#inputAmount").val();
				var mpi_zipcode = $("#mpizipcode").val();
				var mpi_fname = $("#fname").val();
				var mpi_address = $("#address").val();

				var numericValue = totalPriceText.replace(/[^0-9.]/g, '');
				var numericAmount = parseFloat(numericValue);

				var totolAmt = numericAmount;


				if (result.status == 'auth_success') {


					console.log("cart_data");
					console.log(cart_data);
					$.ajax({
						url: "<?= $MpiPayUrl ?>",
						type: "POST",
						dataType: "json",
						data: {
							'token': result.token,
							'totolAmt': totolAmt,
							// 'totolAmt': 5,
							'name': mpi_fname,
							'address': mpi_address,
							'zipcode': mpi_zipcode,
							'cart_data': cart_data
						},
						success: function(mpicardpayment_response) {

							console.log(mpicardpayment_response.data);
							var paymentSource = 'MPI';

							var status = 'TEMP';

							var totalPrice = totolAmt;






							if (mpicardpayment_response.data.responseCode == 00000) {

								var status = 'COMPLETED';
								var trnxId = "Payment completed~" + mpicardpayment_response.data.ReferenceNumber + "~" + mpicardpayment_response.data.cardType + "~" + mpicardpayment_response.data.maskedAccountNumber;

								function responces() {
									var status = 'COMPLETED';
									var trnxId = "Payment completed~" + mpicardpayment_response.data.ReferenceNumber + "~" + mpicardpayment_response.data.cardType + "~" + mpicardpayment_response.data.maskedAccountNumber;
								}
								var bookingType = '<?= $formAction ?>';
								$.ajax({
									url: "<?= base_url('facilitiesContollers/Facilities/BookFacilities') ?>",
									type: "POST",
									dataType: "json",
									data: {
										'paymentSource': paymentSource,
										'paymentStatus': status,
										'transactionId': trnxId,
										'totalPrice': totalPrice,
										'paymentType': 'CREDIT CARD',
										'bookingType': bookingType,
									},
									success: function(addtocart_response) {

										console.log(mpicardpayment_response);
										console.log("addtocart_response");
										console.log(addtocart_response);

										if (addtocart_response.statusCode == 1) {


											swal({
													html: true,
													title: "Order No: " + addtocart_response.data[0].invoiceNo,
													text: "Facility Booking successfully",
													type: "success",
													confirmButtonText: 'OK',
													confirmButtonColor: 'var(--main-color-new-theme)',
												},
												function() {
													loader.on();
													window.location.href = "<?= base_url(); ?>";
												});

											// loader.off();




										} else {
											swal({
													html: true,
													title: "Something went wrong!",
													text: "",
													type: "error",
													confirmButtonText: 'OK',
													confirmButtonColor: 'var(--main-color-new-theme)',
												},
												function() {
													// window.location.reload();
													// window.location.href = "<?= base_url('services') ?>";
												});

											loader.off();
										}
									}
								});

							} else {




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


								loader.off();
							}

						}
					});
				} else {
					alert('Please enter valid details');
				}

			}, function(result) {
				loader.off();
				console.log("error@@@: " + result.token);
			});
		});
	</script>




<?php } ?>


<?php

if (isset($paymentSetting) && $paymentSetting == 'CHARGEANYWHERE' && $paymentSeverOn == 1) { ?>

	<script type="text/javascript">
		/*Acharya sambhawana And General Donation  Start*/
		$(document).ready(function() {



			var $totalPrice = $('#serviceAmountBox');
			var amountString = $('#serviceAmountBox').text();
			var finalAmtWithoutDollar = amountString.replace("$", "");
			var finalAmt = parseInt(finalAmtWithoutDollar);




			var iframe = document.getElementById('paymentIframe');



			var url = "https://www.chargeanywhere.com/APIs/PayOnline.aspx?Version=2.0&MerchantId=<?= $CAW_MerchantId ?>&TerminalId=<?= $CAW_TerminalId ?>&Amount=" + finalAmt + "&Mode=0";


			// var url = "https://www.chargeanywhere.com/APIs/PayOnline.aspx?Version=2.0&MerchantId=27680&TerminalId=0001&Amount=" + finalAmt + "&Mode=0";



			iframe.src = url;



			<?php if (@$GeneralSettings['AcharyaSambhavana'] == 1) { ?>
				var $acharyaInput = $('#acharya-sambhavana-input');
				$acharyaInput.on('input', updateTotalPrice);
			<?php } ?>

			<?php if (@$GeneralSettings['GeneralDonationAmount'] == 1) { ?>
				var $generalInput = $('#general-donation-input');
				$generalInput.on('input', updateTotalPrice);
			<?php } ?>



			// Function to update the total price based on the input values
			function updateTotalPrice() {
				// Get the input values
				var acharyaValue = 0;
				var generalValue = 0;
				<?php if (@$GeneralSettings['AcharyaSambhavana'] == 1) { ?>
					var acharyaValue = parseFloat($acharyaInput.val().replace(/[^\d.-]/g, '')) || 0;
				<?php } ?>
				<?php if (@$GeneralSettings['GeneralDonationAmount'] == 1) { ?>
					var generalValue = parseFloat($generalInput.val().replace(/[^\d.-]/g, '')) || 0;
				<?php } ?>



				// Get the initial total price
				var initialTotalPrice = parseFloat(<?= @$s_total; ?>) || 0;

				// Calculate the new total price
				var newTotalPrice = initialTotalPrice + acharyaValue + generalValue;

				// Update the total price element
				$totalPrice.text('<?= $currencySymbol ?> ' + newTotalPrice.toFixed(2));


				var iframe = document.getElementById('paymentIframe');
				var url = "https://www.chargeanywhere.com/APIs/PayOnline.aspx?Version=2.0&MerchantId=<?= $CAW_MerchantId ?>&TerminalId=<?= $CAW_TerminalId ?>&Amount=" + newTotalPrice.toFixed(2) + "&Mode=0";



				iframe.src = url;

			}

			// Call updateTotalPrice once to include the initial total price
			updateTotalPrice();


			<?php if (@$GeneralSettings['AcharyaSambhavana'] == 1) { ?>
				// Disable arrow key inputs
				$acharyaInput.on('keydown', function(e) {
					if (e.which === 38 || e.which === 40) {
						e.preventDefault();
					}
				});
				// Add validation to prevent input of negative values
				$acharyaInput.on('keydown', function(e) {
					if (e.key === '-' || e.key === '+') {
						e.preventDefault();
					}
				});

				// Add validation to prevent input of "+" and "e" characters
				$acharyaInput.on('input', function() {
					$acharyaInput.val($acharyaInput.val().replace(/[+e]/gi, ''));
				});
			<?php } ?>
			<?php if (@$GeneralSettings['GeneralDonationAmount'] == 1) { ?>
				$generalInput.on('keydown', function(e) {
					if (e.which === 38 || e.which === 40) {
						e.preventDefault();
					}
				});

				$generalInput.on('keydown', function(e) {
					if (e.key === '-' || e.key === '+') {
						e.preventDefault();
					}
				});

				$generalInput.on('input', function() {
					$generalInput.val($generalInput.val().replace(/[+e]/gi, ''));
				});
			<?php } ?>

		});
		/*Acharya sambhawana And General Donation  End*/


		window.addEventListener('message', handleMessage, false);
		window.addEventListener('message', chargeanywher, false);

		function handleMessage(event) {

			if (event.origin != "https://www.chargeanywhere.com") {
				return;
			}

			var customData = event.data;


		}



		function chargeanywher(event) {

			loader.on();

			if (event.origin != "https://www.chargeanywhere.com") {
				return;
			}

			// console.log(event);

			var customData = event.data;


			console.log(customData);


			var cart_data = SubmitformData;
			var paymentSource = 'CREDIT CARD';


			var grand_totalPrice = customData.GrandTotal;


			var cleanedPrice = grand_totalPrice.replace(/[,$\s]/g, '');


			var totalPrice = parseFloat(cleanedPrice);


			var acharya_sambhavana = parseFloat($('#acharya-sambhavana-input').val()) || 0;
			var general_donation = parseFloat($('#general-donation-input').val()) || 0;


			if (customData.ResponseCode === "000") {

				var status = 'COMPLETED';

				<?php if ($isIncludeSankalpam_result == 'YES') { ?>

					var familyMembers = [];
					var nakshtras = [];
					var rashi = [];
					var relationship = [];
					var dob = [];
					var anniversaryDate = [];


					$("input[name='family_member[]']").each(function() {
						var value = $(this).val();
						familyMembers.push(value);
					});

					$("select[name='nakshtra[]']").each(function() {
						var value = $(this).val();
						nakshtras.push(value);
					});

					$("input[name='dob[]']").each(function() {
						var value = $(this).val();
						dob.push(value);
					});

					$("select[name='rashi[]']").each(function() {
						var value = $(this).val();
						rashi.push(value);
					});

					$("select[name='relationship[]']").each(function() {
						var value = $(this).val();
						relationship.push(value);
					});

					$("input[name='anniversaryDate[]']").each(function() {
						var value = $(this).val();
						anniversaryDate.push(value);
					});


					var fname = $("#fname").val();
					var lname = $("#lname").val();
					var gothram = $("#gothram").val();
					var stars = $("#stars").val();


					var spouseName = $("#spouseName").val();
					var spouseStars = $("#spouseStars").val();


					var No_Family_Member = $("#No_Family_Member").val();
					var No_Spouse = $("#No_Spouse").val();


					$.ajax({
						url: "<?= base_url('UpdateProfileGlobal/UpdateProfile') ?>",
						type: "POST",
						dataType: "json",
						data: {

							'familyMembers': familyMembers,
							'nakshtras': nakshtras,
							'dob': dob,
							'rashi': rashi,
							'relationship': relationship,
							'anniversaryDate': anniversaryDate,
							'fname': fname,
							'lname': lname,
							'gothram': gothram,
							'stars': stars,
							'spouseName': spouseName,
							'spouseStars': spouseStars,
							"noSpouse": No_Spouse,
							"noFamily": No_Family_Member
						},
						success: function(response) {


							console.log(response);

						}
					});

				<?php } ?>


				$.ajax({
					url: "<?= base_url('Services/AddToCart') ?>",
					type: "POST",
					dataType: "json",
					data: {

						'status': status,
						'paymentSource': paymentSource,
						'totalPrice': totalPrice,
						'acharya_sambhavana': acharya_sambhavana,
						'general_donation': general_donation,
						'cart_data': cart_data,
					},
					success: function(addtocart_response) {

						console.log(addtocart_response);



						if (addtocart_response.statusCode == 1) {

							var status = 'COMPLETED';

							var cardTypeCode = customData.CardType;
							var cardTypeName = getCardTypeName(cardTypeCode);

							var trnxId = "Payment completed~" + customData.ReferenceNumber + "~" + cardTypeName + "~" + customData.CardNumber;
							$.ajax({
								url: "<?= base_url('Services/updateTransactionStatus') ?>",
								type: "POST",
								dataType: "json",
								data: {

									'status': status,
									'transaction_id': trnxId,
									'paymentDescription': customData
								},
								success: function(update_transactionstatus_response) {
									if (update_transactionstatus_response.statusCode == 1) {


										swal({
												html: true,
												title: "Service Booking Confirmed!",
												text: "<span style='font-weight: 600;margin:5px;padding:5px;font-size: 27px !important;'>Receipt #: " + update_transactionstatus_response.envoiceNo + "</span>",
												type: "success",
												confirmButtonText: 'OK',
												confirmButtonColor: 'var(--main-color-new-theme)',
											},
											function() {
												// window.location.reload();
												window.location.href = "<?= base_url('services') ?>";
											});

										loader.off();
									}

								}
							});

						}
					}
				});



			} else {

				$.ajax({
					url: "<?= base_url('Services/AddToCart') ?>",
					type: "POST",
					dataType: "json",
					data: {

						'status': 'TEMP',
						'paymentSource': paymentSource,
						'totalPrice': totalPrice,
						'acharya_sambhavana': acharya_sambhavana,
						'general_donation': general_donation,
						'cart_data': cart_data,
					},
					success: function(addtocart_response) {
						console.log(addtocart_response);

						if (addtocart_response.statusCode == 1) {
							var status = 'FAILED';

							var cardTypeCode = customData.CardType;
							var cardTypeName = getCardTypeName(cardTypeCode);


							var trnxId = "Payment failed~0~" + customData.ResponseText + "~" + cardTypeName + "~" + customData.CardNumber;


							$.ajax({
								url: "<?= base_url('Services/updateTransactionStatus') ?>",
								type: "POST",
								dataType: "json",
								data: {

									'status': status,
									'transaction_id': trnxId,
									'paymentDescription': customData
								},
								success: function(update_transactionstatus_response) {
									if (update_transactionstatus_response.statusCode == 1) {

										var original_string = update_transactionstatus_response.message;
										var substring_to_replace = "Payment failed~0~"

										var new_string = original_string.replace(substring_to_replace, "");

										swal({
												html: true,
												title: "Failed!",
												text: "<span>" + new_string + "!<span><br><span style='font-weight: 600;margin:5px;padding:5px;font-size: 27px !important;'>Receipt #: " + update_transactionstatus_response.envoiceNo + "</span>",
												type: "error",
												confirmButtonText: 'OK',
												confirmButtonColor: 'var(--main-color-new-theme)',
											},
											function() {
												window.location.reload();
											});

										loader.off();
									}

								}
							});

						}
					}
				});
			}


			// alert(JSON.stringify(customData, null, 2));
		}
	</script>

<?php } ?>

<script>
	/* $(document).ready(function() {
    $('input[name="add_service"]').on('change', function() {
      // console.log($("#eventTime").val());
      if ($('#radio-show').is(':checked')) {
        alert($('#radio-show').is(':checked'));
        if ($("#eventName").val() == "") {
      alert("Please add event name!");
      return false;
    }else if ($("#eventDate").val() == "") {
      alert("Please add event date!");
      return false;
    }else if ($("#eventTime").val() == "") {
      alert("Please add event from time!");
      return false;
    }else if ($("#adults").val() == "") {
      alert("Please add Estimated Number of Attendees!");
      return false;
    }else{
      $('#toggleDiv').removeClass('hidden');
    }
        
      } else if ($('#radio-hide').is(':checked')) {
        $('#toggleDiv').addClass('hidden');
      }
    });
  });*/

	$('#serviceName').change(function() {

		var serviceType = $('option:selected', this).attr('serviceType');
		var membershipDiscount = $('option:selected', this).attr('membershipDiscount');
		var membershipDiscountAmt = $('option:selected', this).attr('membershipDiscountAmt');

		$("#serviceType").val(serviceType);
		$("#serviceMembershipDiscount").val(membershipDiscount);
		$("#serviceMembershipDiscountAmt").val(membershipDiscountAmt);

		var startDate = $('option:selected', this).attr('startDate');
		if (startDate != '') {

			$("#serviceDate").val(startDate);
			$("#serviceDate").attr('disabled', 'true');

		}


		var startTime = $('option:selected', this).attr('startTime');
		if (startTime != '') {
			$("#serviceTime").val(startTime);
			$("#serviceTime").attr('disabled', 'true');
		}

		var serviceId = $('option:selected', this).attr('serviceId');
		if (serviceId != '') {
			$("#serviceId").val(serviceId);
		}


		if (serviceId == 0) {

			$("#serviceDetailsBox").css('display', 'block');
			$("#serviceDetailsBox").html('<fieldset class="border"><legend  class="legend-inner float-none w-auto required">Service Details<span class="mandate">*</span></legend><div class="input-group"><input type="text"  class="form-control2 form-control" name="serviceDetails" id="serviceDetails" placeholder="Specify Service Details" required></div></fieldset>');

			var serviceAmount = $('option:selected', this).attr('serviceAmount');
			$("#serviceAmountBoxNew").val('TBD By Priest');

		} else {
			$("#serviceDetailsBox").css('display', 'none');
			$("#serviceDetailsBox").html('');
			var serviceAmount = $('option:selected', this).attr('serviceAmount');
			$("#serviceAmountBoxNew").val('$ ' + serviceAmount + '.00');
			$("#serviceAmount").val(serviceAmount);
		}
	});



	$(document).ready(function() {
		// Listen for changes on the radio button


		// Example: Adding datepicker functionality for eventDate
		// $('.event-datepicker').datepicker({
		//   dateFormat: "mm/dd/yy",
		//   onSelect: function(dateText) {
		//     // Optionally, set the value in serviceDate if the radio button is checked
		//     if ($('input[name="add_service"]:checked').val() === "YES") {
		//       $('#serviceDate').val(dateText);
		//     }
		//   }
		// });
	});

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

	$('input[name="add_service"]').on('change', function() {
		// Check if the radio button is selected and its value is "YES"
		if ($(this).is(':checked') && $(this).val() === "YES") {
			$(this).prop("checked", false);
			if ($("#eventName").val() == "") {
				alert("Please add event name!");
				return false;
			} else if ($("#eventDate").val() == "") {
				alert("Please add event date!");
				return false;
			} else if ($("#eventTime").val() == "") {
				alert("Please add event from time!");
				return false;
			} else if ($("#adults").val() == "") {
				alert("Please add Estimated Number of Attendees!");
				return false;
			} else {
				$(this).prop("checked", true);
				$("#serviceDiv").removeClass('d-none');
				$("#serviceName").attr("requried", true);
				$("#serviceAmountBoxNew").attr("requried", true);
				$("#serviceTime").attr("requried", true);
				$("#priestName").attr("requried", true);
				$('#serviceAddress').val('<?= $TempleAddress ?>');
				// Get the value from eventDate
				var eventDateValue = $('#eventDate').val();
				// $('#serviceTime').val($("#eventTime").val());

				const selectedTime = $("#eventTime").val();
				const updatedMinTime = calculateMinTime(); // Calculate minTime with a 30-minute offset

				// Safely update serviceTime
				const $serviceTime = $('#serviceTime');

				if ($serviceTime.data('timepicker')) {
					// If already initialized, update its options
					$serviceTime.timepicker('destroy').timepicker('option', {
						minTime: updatedMinTime, // Dynamically update minTime
						maxTime: '11:00 PM',
						change: function(time) {
							var $this = $(this);
							var service_id = $this.attr('data-id');
							fetchPriestAvailability();

						}
					});
				} else {
					// Initialize the serviceTime timepicker
					$serviceTime.timepicker('destroy').timepicker({
						timeFormat: 'h:mm p', // 12-hour format with AM/PM
						interval: 5, // Interval of 5 minutes
						minTime: updatedMinTime, // Dynamically set minTime
						maxTime: '11:00 PM', // Dynamically set minTime
						dynamic: false,
						dropdown: true,
						scrollbar: true,
						change: function(time) {
							var $this = $(this);
							var service_id = $this.attr('data-id');
							fetchPriestAvailability();

						}
					});
				}

				// Set the value of serviceTime to match eventTime
				$serviceTime.val(selectedTime);

				// Set the value to serviceDate
				$('#serviceDate').val(eventDateValue);
				console.log("okkkkk9898");
				fetchPriestAvailability();
			}
		} else {

			$("#serviceDiv").addClass('d-none');
			$("#serviceName").attr("requried", false);
			$("#serviceAmountBoxNew").attr("requried", false);
			$("#serviceTime").attr("requried", false);
			$("#priestName").attr("requried", false);
			// Clear the serviceDate field if the condition isn't met
			$('#serviceDate').val('');
			$("#serviceName").val('');
			$("#serviceAmountBoxNew").val('');
			$("#serviceTime").val('');
			$("#priestName").val('');
			$("#addtionalInfo").val('');
			$("#serviceId").val('');
			$("#serviceAmount").val('');
			$("#serviceType").val('');
			$("#priestId").val('');
			$("#priestEmail").val('');
			$("#priestPhone").val('');
			$("#serviceMembershipDiscount").val('');
		}
	});


	// $('#serviceTime').mdtimepicker();

	$('#eventTime').mdtimepicker();

	$('#eventTime').on('timechanged', function(e) {
		console.log("Event time selected:", e.value);
		// alert($("#eventTime").val());
		if ($('input[name="add_service"]:checked').val() === "YES") {
			// $('#serviceTime').val($("#eventTime").val());
			const selectedTime = $("#eventTime").val();
			const updatedMinTime = calculateMinTime(); // Calculate minTime with a 30-minute offset

			// Safely update serviceTime
			const $serviceTime = $('#serviceTime');

			if ($serviceTime.data('timepicker')) {
				// If already initialized, update its options


				// $serviceTime.timepicker('destroy').timepicker({
				// 	minTime: updatedMinTime,
				// 	maxTime: '11:00 PM',
				// 	change: function(time) {
				// 		fetchPriestAvailability();

				// 	}
				// });

				$serviceTime.timepicker('destroy'); // Destroy old instance

				$serviceTime.timepicker({ // Reinitialize with updated minTime
					minTime: updatedMinTime,
					maxTime: '11:00 PM',
					change: function(time) {
						console.log("Service time changed:", time);
						fetchPriestAvailability();
					}
				});

				// **Manually bind change event again**
				$serviceTime.off('change').on('change', function() {
					console.log("Service time manually changed:", $(this).val());
					fetchPriestAvailability();
				});


			} else {
				// Initialize the serviceTime timepicker
				// $serviceTime.timepicker('destroy').timepicker({
				//   timeFormat: 'h:mm p', // 12-hour format with AM/PM
				//   interval: 5, // Interval of 5 minutes
				//   minTime: updatedMinTime, // Dynamically set minTime
				//   maxTime: '11:00 PM', // Dynamically set minTime
				//   dynamic: false,
				//   dropdown: true,
				//   scrollbar: true,
				// 	change: function(time) {
				//       fetchPriestAvailability();

				//     }
				// });
				$serviceTime.timepicker('destroy'); // Destroy old instance

				$serviceTime.timepicker({ // Reinitialize with updated minTime
					timeFormat: 'h:mm p',
					interval: 5,
					minTime: updatedMinTime,
					maxTime: '11:00 PM',
					dynamic: false,
					dropdown: true,
					scrollbar: true,
					change: function(time) {
						console.log("Service time changed:", time);
						fetchPriestAvailability();
					}
				});

				// **Manually bind change event again**
				$serviceTime.off('change').on('change', function() {
					console.log("Service time manually changed:", $(this).val());
					fetchPriestAvailability();
				});

			}
			fetchPriestAvailability();
		}

	});


	function fetchPriestAvailability() {
		console.log("ok");
		var serviceDate = $('#serviceDate').val();
		var serviceTime = $('#serviceTime').val();

		if (serviceDate != '' && serviceTime != '') {
			$("#priestName").empty();
			$.ajax({
				url: '<?= base_url('Home/GetPriestAvailibility') ?>',
				type: 'POST',
				data: {
					serviceDate: serviceDate,
					serviceTime: serviceTime
				},
				success: function(response) {
					// console.log(response);
					$("#priestName").empty();
					$("#priestName").append(response);
				},
				error: function(xhr, status, error) {
					console.error(xhr.responseText);
				}
			});
		} else {
			console.log('Please fill both service date and service time.');
		}
	}

	$("#serviceDate").on("input change", fetchPriestAvailability);
	// $("#eventDate").on("input change", fetchPriestAvailability);
	// $("#serviceTime").on("input change", fetchPriestAvailability);
	// $("#eventDate").on("input change", fetchPriestAvailability);


	$(".mdtp__button").click(function() {
		let eventTime = $("#eventTime").val();
		const $serviceTime = $('#serviceTime');
		$serviceTime.timepicker('destroy').timepicker({
			minTime: eventTime,
			maxTime: '11:00 PM',
			change: function(time) {
				fetchPriestAvailability();

			}
		});

		$("#serviceTime").val(eventTime);
		fetchPriestAvailability();
	});

	// });

	$('#priestName').change(function() {

		var priestEmail = $(this).children(":selected").attr("email");
		var priestPhone = $(this).children(":selected").attr("phone");
		var priestId = $(this).children(":selected").attr("priestID");

		$("#priestEmail").val(priestEmail);
		$("#priestPhone").val(priestPhone);
		$("#priestId").val(priestId);

	});
</script>