<?php $this->load->view('includes/head') ?>
<?php $this->load->view('includes/topbar') ?>
<?php $this->load->view('includes/header') ?>
<style>
	.search-container {
		position: relative;
		display: flex;
		align-items: center;
		margin-top: 1rem !important;
		/* margin-top: 4rem !important; */
	}

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

	.active-btn {
		background: var(--main-color-new-theme) !important;
		border-color: #fcfcfc !important;
		color: #fcfcfc !important;
	}

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

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

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

	.top-bar {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		/* Badi screen par right side */
		gap: 20px;
		/* Elements ke beech spacing */
		padding: 10px;
		flex-wrap: wrap;
	}

	.search-container {
		display: flex;
		align-items: center;
	}

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

	.paymentBtn {
		padding: 10px 20px;
		font-size: 16px;
	}


	@media only screen and (max-width: 399px) {
		.custom-btn {
			font-size: 12px !important;

		}
	}

	.amount-input-donations::placeholder {
		color: #d6fff7 !important;
	}

	/* Choti screen par search icon center me dikhane ke liye */
	@media (max-width: 768px) {
		.top-bar {
			flex-direction: column;
			/* Mobile view me vertical layout */
			align-items: center;
			/* Center me dikhane ke liye */
			margin-top: -26px;
			width: 100% !important;
		}


		.search-container {
			justify-content: center;
		}
	}

	@media only screen and (max-width: 768px) and (min-width: 277px) {

		.justify-content-end {

			justify-content: center !important;

		}
	}

	/* .no-scroll-alert {
    overflow: hidden !important;
    max-width: 90vw;
} */


	@media only screen and (max-width: 768px) {

		.col-md-12 i {
			display: block !important;
			text-align: center !important;
			margin-top: 0px !important;
			font-size: 18px !important;

		}
	}



	.active-btn {
		background: var(--main-color-new-theme) !important;
		;
		border-color: #fcfcfc !important;
		;
		color: #fcfcfc !important;
	}

	@media only screen and (max-width: 444px) {

		.col-md-12 i {
			font-size: 18px !important;

		}
	}

	@media only screen and (max-width: 360px) {
		.col-md-12 i {
			font-size: 15px !important;
		}
	}

	@media (max-width: 615px) and (min-width: 300px) {
		img.border-img {
			height: 25px !important;
			width: 100% !important;
		}
	}
</style>
<script type="text/javascript" src="<?= base_url('admin_assets/js/sweetalert2.all.min.js') ?>"></script>
<link href="<?= base_url('assets/css/lightbox.min.css'); ?>" rel="stylesheet" />
<script src="<?= base_url('assets/js/lightbox-plus-jquery.min.js'); ?>"></script>


<link href="<?= base_url('admin_assets/css/sweetalert2.min.css') ?>" rel="stylesheet">
<style>
	.notifyjs-bootstrap-base {
		color: black !important;
	}
</style>
<?php
$header_data = getWebSyncsData('Header Settings', 'headerSettings', '');
$currencySymbol = getCurrencySymbol(); ?>

<link rel="stylesheet" type="text/css" href="<?= base_url('assets/css/services-cart.css') ?>">
<?php



$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 = 'PAYMENT';
$formAction = SettingsApi()['result']['data'][0]['serviceRequestSettings']['bookingTypes'];
$membershipDetails = membershipStatusCheck();

$setting =  SettingsApi();
$membershipDiscount = $setting['result']['data'][0]['membershipSettings']['membershipDiscount'];
$discountType = $setting['result']['data'][0]['membershipSettings']['discountType'];
// $discountType='SERVICE LEVEL';
?>
<main id="main">
	<!-- ======= Coming Soon ======= -->
	<?php
	// echo '<pre>';
	// print_r(SettingsApi()['result']['data'][0]['membershipSettings']);

	if ((@$this->uri->segment(3) == 'outside-temple' || @$this->uri->segment(3) == 'inside-temple') && $this->session->userdata('logged_in') == 1 && $this->session->userdata('userType') == 'Devotee') {
		$parts = explode(" ", @$userDetails->refDataName);
		$lastname = array_pop($parts);
		$firstname = implode(" ", $parts);

		$enable_service_request_form = true;
	} else if (@$this->uri->segment(3) == 'aparakarya' && $this->session->userdata('logged_in') == 1 && $this->session->userdata('userType') == 'Devotee') {

		$parts = explode(" ", @$userDetails->refDataName);
		$lastname = array_pop($parts);
		$firstname = implode(" ", $parts);

		$enable_service_request_form = true;
	} else {
		$enable_service_request_form = false;
	}


	if ($this->session->userdata('logged_in') == 1 && $this->session->userdata('userType') == 'Devotee') {
		$enable_service_request_btnlink = true;
	} else {
		$enable_service_request_btnlink = false;
	}


	?>
	<style>
		.row {
			margin-right: 0px !important;
			margin-left: 0px !important;
		}
	</style>
	<section class="temple-services" style="background-image: url(<?= base_url('assets/img/bg-main-page.jpg') ?>);">
		<!-- ======================= -->

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

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

			</center>


		</div>

		<!-- ======================= -->
		<div class="row">


			<?php
			// var_dump($this->session->userdata('service_cart'));

			if ($enable_service_request_form == false) { ?>

				<?php
				$cartList = $this->session->userdata('service_cart');
				if (isset($cartList['includeSankalpam'])) {
					$includeSankalpam = checkForYesValue($cartList['includeSankalpam']);
				} else {

					$includeSankalpam = 'NO';
				}

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

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


				$GeneralSettings = GeneralSettings();

				$serivce_Types = getServiceTypes();

				$serivce_Types = sortBySequenceId($serivce_Types);

				// echo '<pre>';
				// print_r($cartList);


				// $serivce_Types = ArrReverse($serivce_Types);
				?>
		</div>

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


							<!-- <div class="col-md-12" id="search_col">
							<div class="search-container">
								<input type="search" name="q" id="search" class="search-input search-text searchKey d-none" placeholder="Search..." autocomplete="off" style="">
								<span class="search-icon" id="searchIcon">🔍</span>
							</div> -->

							<!-- <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 mt-5" style="display: flex; flex-direction: row; align-content: flex-end; align-items: flex-end;"> -->


							<!-- <div class="d-flex justify-content-end align-items-end" style="border-bottom: 20px;">
								<div class="row px-0 mx-0"> -->
							<!-- <div class="col-md-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-3 text-center">


										<h2 class="text-center mb-0" style="font-weight:bold!important;font-size: 25px!important;">BOOK A SERVICE</h2>
										<img src="<?= base_url('assets/img/border.png'); ?>" class="img-fluid" style="width: 50%;max-width: 50%;">
									</div> -->

							<!-- <div class="col-md-5"> -->
							<div class="d-flex justify-content-end align-items-end" id="RightField">
								<div class="top-bar">
									<!-- 🔍 Search Icon -->
									<div class="search-container">
										<span class="search-icon" id="searchIcon">🔍</span>
										<input type="search" name="q" id="search" class="search-input search-text searchKey d-none" placeholder="Search..." autocomplete="off">
									</div>
									<div class="text-white px-4">
										<div class="row">
											<div class="col-md-9 text-start text-dark">
												<span class="fw-bold" style="padding-left: 42px;">Total Amount</span>
											</div>
										</div>



										<!-- 🛒 Cart -->
										<span style="position: relative;">
											<a href="javaScript:void(0)" onclick="ViewCart()">
												<i class="fa fa-shopping-cart fa-2x" style="color:#000030;"></i>
												<!-- <span class="cart-count text-dark" style="position: absolute; top: -28px; right: 7px; 
                            	color: black !important; font-size: 15px!important; 
                            	padding: 2px 6px; border-radius: 50%;"> -->
												<span class="cart-count text-dark" style="font-size: 20px !important;">
													<?= $cart_count ?>
												</span>
											</a>
										</span>

										<!-- 💰 Total Price -->
										<label class="label label-primary price-span">
											<?= $currencySymbol; ?>&nbsp;<span class="allPrice"><?= number_format($cartList['totalPrice'], 2); ?></span>
										</label>

										<!-- 🛍️ Proceed to Checkout -->
										<?php if ((isset($GeneralSettings['isMultipleSelect']) && $GeneralSettings['isMultipleSelect'] == 'YES')) { ?>
											<a href="javaScript:void(0)" class="btn btn-success paymentBtn" onclick="CartCheckLogin('services')">
												<?= isset($GeneralSettings['payNowText']) && $GeneralSettings['payNowText'] != '' ?
													$GeneralSettings['payNowText'] : 'Proceed to Checkout'; ?>
											</a>
										<?php } else if (isset($GeneralSettings['isMultipleSelect']) && $GeneralSettings['isMultipleSelect'] == 'NO') { ?>
											<a href="javaScript:void(0)" class="btn btn-success paymentBtn" onclick="CartCheckLogin('services')">
												<?= isset($GeneralSettings['payLetterText']) && $GeneralSettings['payLetterText'] != '' ?
													$GeneralSettings['payLetterText'] : 'BOOK NOW'; ?>
											</a>
										<?php } else { ?>
											<a href="javaScript:void(0)" class="btn btn-success paymentBtn" onclick="CartCheckLogin('services')">
												<?= isset($GeneralSettings['payNowText']) && $GeneralSettings['payNowText'] != '' ?
													$GeneralSettings['payNowText'] : 'Proceed To Checkout'; ?>
											</a>
										<?php } ?>
									</div>
								</div>
							</div>
						</div> <!-- col-md-12 -->





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

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

							<div class="responsive-container">
								<ul class="nav nav-tabs">

									<?php
									$s = 1;
									if (!empty($serivce_Types)) {

										foreach ($serivce_Types as $key => $val) {

											if ($val['refDataName'] == 'IN-TEMPLE') {

												// $displayName = $val['refDataName'] == 'IN-TEMPLE' ? 'IN TEMPLE' : ($val['refDataName'] == 'AWAY-TEMPLE' ? 'OUTSIDE TEMPLE' : '');
									?>


												<li class="nav-item mt-3 rounded" style="padding-right:15px">


													<!-- <button class="custom-btn btn-15 <?= ($s == 1) ? 'serviceTypes1 active' : ''; ?>" tab="<?= ($key + 1); ?>" id="home-tab<?= $val['_id']; ?>" data-bs-toggle="tab" data-bs-target="#home-tab-pane<?= $val['_id']; ?>" type="button" role="tab" aria-controls="home-tab-pane<?= $val['_id']; ?>" aria-selected="true" style="font-weight: 700; font-size: 16px; background-size: cover; border-radius: 5px !important;padding: 12px 23px 12px 23px; color: white; box-shadow: 1px 1px 10px #ffc1075e; margin-bottom: 10px; background: #000d8c; border: 2px solid #ffc107;"><?= $val['displayName']; ?></button> -->
													<button class="custom-btn btn-15 <?= ($s == 1) ? 'serviceTypes1 active active-btn' : ''; ?>" tab="<?= ($key + 1); ?>" id="home-tab<?= $val['_id']; ?>" data-bs-toggle="tab" data-bs-target="#home-tab-pane<?= $val['_id']; ?>" type="button" role="tab" aria-controls="home-tab-pane<?= $val['_id']; ?>" aria-selected="true">INSIDE TEMPLE</button>




												</li>

									<?php $s++;
											}
										}
									} ?>

									<?php if ($enable_service_request_btnlink == true) {  ?>


										<li class="nav-item mt-3 rounded" id="right" style="padding-right:15px">
											<a href="<?php echo base_url('services/request/outside-temple'); ?>" class="custom-btn btn-15 <?= @$this->uri->segment(3) == 'outside-temple' ? 'active-btn' : 'normal-btn'; ?> <?= ($s == 1) ? 'serviceTypes1 active' : ''; ?>" tab="<?= ($key + 1); ?>" id="home-tab<?= $val['_id']; ?>" data-bs-target="#home-tab-pane<?= $val['_id']; ?>" type="button" role="tab" aria-controls="home-tab-pane<?= $val['_id']; ?>" aria-selected="true">OUTSIDE TEMPLE</a>
										</li>



									<?php } else { ?>

										<li class="nav-item mt-3 rounded" id="right" style="padding-right:15px">
											<a href="javaScript:void(0)" class="custom-btn btn-15 <?= ($s == 1) ? 'serviceTypes1 active' : ''; ?> <?= ($s == 1) ? 'serviceTypes1 active' : ''; ?> <?= @$this->uri->segment(2) == 'serviceRequest' ? 'active-btn' : 'normal-btn'; ?>" tab="<?= ($key + 1); ?>" id="home-tab<?= $val['_id']; ?>" data-bs-target="#home-tab-pane<?= $val['_id']; ?>" type="button" role="tab" aria-controls="home-tab-pane<?= $val['_id']; ?>" aria-selected="true" onclick="checkLoginStatus('OUTSIDE')">OUTSIDE TEMPLE</a>
										</li>


									<?php } ?>

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

									<?php $s = 1;
									if (!empty($serivce_Types)) {
										foreach ($serivce_Types as $key => $val) {

											if ($val['refDataName'] == 'IN-TEMPLE') { ?>

												<div class="tab-pane table-responsive fade shadow panettttttttt<?= $val['_id']; ?> show <?= ($s == 1) ? 'active' : ''; ?>" id="home-tab-pane<?= $val['_id']; ?>" role="tabpanel" aria-labelledby="home-tab<?= $val['_id']; ?>" tabindex="0">

													<?php $services = getServicesByServiceType($val['refDataName'], $cartList);
													echo $services;
													?>
													<div id="emptyServices" style="padding: 4px 66px; font-size: 21px; font-weight: 700;"></div>
												</div>
									<?php $s++;
											}
										}
									} ?>

								</div>
							</div>
							<!-- ////////// availabel service list  //////////-->
							<div class="modal fade" id="showServiceListModal" tabindex="-1" role="dialog" aria-labelledby="showServiceListModalTitle" aria-hidden="true" data-keyboard="false" data-backdrop="static">
								<div class="modal-dialog modal-lg " role="document">
									<div class="modal-content modal-dialog-scrollable">


										<form action="#" method="post">
											<div class="modal-header text-center" style="background: #910000;">
												<h5 class="modal-title bottomborder modatTitle" style="color: #ffffff!important;font-size: 23px!important;" id="service_titlt_vadamala">Service Availability List</h5>

												<button type="button" class="btn-close m-0" data-bs-dismiss="modal" aria-label="Close" style="filter: invert(100%) brightness(1000%) contrast(1000%);font-size: 16px; border: 2px solid black;"></button>
											</div>
											<div class="modal-body">
												<div class="container">

													<table class="table table-responsive table-bordered table-hover table-stripe border-dark" style="background: #fff6be;">
														<thead class="service-list-header">
															<tr>
																<th style="padding: 10px 33px;">Date <span id="headerMonths"></span></th>
																<th style="margin-right: 28px;text-align: end;padding: 7px 60px;">Availability</th>
															</tr>
														</thead>

														<tbody>
														</tbody>
													</table>


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

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

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

	<?php } ?>



	<?php if ($enable_service_request_form == true) { ?>
		<div class="px-5">
			<a href="javaScript:void(0)" class="btn" onclick="window.history.back()" style="background-color:var(--main-color-new-theme);color: white!important;border-radius: 1px!important;">← Back</a>
			<style type="text/css">
				.form-control:focus {
					box-shadow: none !important;
				}
			</style>
		</div>
		<div class="container-fluid">
			<div class="row py-4 ">
				<?php echo $this->session->flashdata('success'); ?>
				<div class="col-md-12 mx-auto d-block card shadow-lg p-5 my-2">
					<?php

					if ($formAction == 'BOOKING WITH PAYMENT' || $formAction == 'REQUEST WITH PAYMENT') {
					?>
						<?= form_open(base_url('admin/service-request-with-payment'), 'method="post" id="serviceRequestForm"'); ?>
					<?php
					} else {
					?>

						<?= form_open(base_url('admin/service-request'), 'method="post" id="serviceRequestForm"'); ?>
					<?php
					}
					?>

					<fieldset class="border-2">
						<legend class="legend-outer  float-none w-auto"> Request for Puja Service </legend>

						<input type="hidden" name="page_name" value="<?= $this->uri->segment(3); ?>">
						<fieldset class="border-2">
							<div class="row justify-content-between m-0 p-5">
								<div class="col-md-3 m-0 p-5">
									<fieldset class="border" style="background-color: #e7e6e6;">
										<legend class="legend-inner float-none w-auto required">First Name<span class="mandate">*</span></legend>
										<div class="input-group">
											<i class="fa fa-user fa2"></i>
											<input type="text" class="form-control form-control2" style="color:black!important;background-color: #e7e6e6;" name="fname" id="fname" placeholder="First Name*" value="<?= set_value('fname', @$firstname) ?>" required readonly>
										</div>
									</fieldset>
								</div>
								<div class="col-md-3 m-0 p-5">
									<fieldset class="border" style="background-color: #e7e6e6;">
										<legend class="legend-inner float-none w-auto required">Last Name<span class="mandate">*</span></legend>
										<div class="input-group">
											<i class="fa fa-user fa2"></i>
											<input type="text" class="form-control2 form-control " name="lname" style="background-color: #e7e6e6;" id="lname" placeholder="Last Name" value="<?= set_value('lname', @$lastname) ?>" required readonly>
										</div>
									</fieldset>
								</div>


								<div class="col-md-3 m-0 p-5">
									<fieldset class="border" style="background-color: #e7e6e6;">
										<legend class="legend-inner float-none w-auto required">Email<span class="mandate">*</span></legend>
										<div class="input-group">
											<i class="fa fa-envelope fa2"></i>
											<input type="email" class="form-control2 form-control " style="color:black!important;background-color: #e7e6e6!important;" id="email" name="email" placeholder="Email ID*" value="<?= set_value('email', base64_decode(@$userDetails->email)) ?>" readonly required oninput="this.value = this.value.toLowerCase();">
										</div>
									</fieldset>
								</div>
								<div class="col-md-3 m-0 p-5">
									<fieldset class="border" style="background-color: #e7e6e6;">
										<legend class="legend-inner float-none w-auto required">Phone<span class="mandate">*</span></legend>
										<div class="input-group">
											<i class="fa fa-phone fa2"></i>
											<input type="text" class="form-control2 form-control " id="phone" name="phoneNumber" placeholder="Phone Number*" value="<?= set_value('phoneNumber', formatPhoneNumber(base64_decode(@$userDetails->phone))) ?>" style="color:black!important;background-color: #e7e6e6!important;" readonly required>
										</div>
									</fieldset>
								</div>

								<?php

								$gotra_data = getGotra()['data'];
								$rashi_data = getRashi()['data'];
								$nakshtra_data = getNakshtra()['data'];

								?>

								<div class="col-md-4 m-0 p-5">
									<fieldset class="border">
										<legend class="legend-inner float-none w-auto required">Gotram<span class="text-danger fw-bold" style="font-size: 20px;"></span></legend>
										<div class="input-group">
											<i class="fa fa-user fa2"></i>
											<input type="text" class="form-control2 form-control " style="color:black!important;border: 0;" id="gotra" name="gotra" placeholder="Gotram" value="<?= set_value('gotra', @$userDetails->gotraName) ?>">
										</div>
									</fieldset>
								</div>
								<div class="col-md-4 m-0 p-5">
									<fieldset class="border">
										<legend class="legend-inner float-none w-auto required">Nakshatra<span class="text-danger fw-bold" style="font-size: 20px;"></span></legend>
										<div class="input-group">
											<!-- <i class="fa fa-user fa2"></i> -->

											<select id="stars" name="stars" style="color:black!important;border: 0;" class="form-control rounded  form-select">
												<option value=" " selected disabled>Select Nakshtra</option>
												<?php
												$selected_option = '';
												if (!empty(@$userDetails->Nakshtra) && @replaceSingleQuotesWithBackticks($userDetails->Nakshtra) !== replaceSingleQuotesWithBackticks("DON'T KNOW")) {
													$selected_option = '<option value="' . @replaceSingleQuotesWithBackticks($userDetails->Nakshtra) . '" selected>' . @replaceSingleQuotesWithBackticks($userDetails->Nakshtra) . '</option>';
												}

												foreach ($nakshtra_data as $key => $item) { ?>

													<?= $key == 0 ? $selected_option : ''; ?>


													<option value="<?= @replaceSingleQuotesWithBackticks($item['refDataName']); ?>" <?= @replaceSingleQuotesWithBackticks($item['refDataName']) == @replaceSingleQuotesWithBackticks($userDetails->Nakshtra) ? 'selected' : '' ?>><?= @replaceSingleQuotesWithBackticks($item['refDataName']); ?></option>


													<?php } ?>>
											</select>

											<!-- <input type="text" class="form-control2 form-control " name="stars" placeholder="Nakshatra" value="<?= set_value('stars', @$userDetails->Nakshtra); ?>" style="color:black!important;background-color: #e7e6e6;" readonly required> -->
										</div>
									</fieldset>
								</div>
								<div class="col-md-4 m-0 p-5">
									<fieldset class="border">
										<legend class="legend-inner float-none w-auto required">Rashi<span class="text-danger fw-bold" style="font-size: 20px;"></span></legend>
										<div class="input-group">
											<!-- <i class="fa fa-user fa2"></i> -->

											<select id="rashi" name="rashi" style="color:black!important;border: 0;" class="form-control rounded  form-select">
												<option value=" " selected disabled>Select Rashi</option>

												<?php
												$selected_option = '';
												if (!empty(@$userDetails->rashi) && @replaceSingleQuotesWithBackticks($userDetails->rashi) !== replaceSingleQuotesWithBackticks("DON'T KNOW")) {
													$selected_option = '<option value="' . @replaceSingleQuotesWithBackticks($userDetails->rashi) . '" selected>' . @replaceSingleQuotesWithBackticks($userDetails->rashi) . '</option>';
												}

												foreach ($rashi_data as $key => $item) { ?>

													<?= $key == 0 ? $selected_option : ''; ?>


													<option value="<?= @replaceSingleQuotesWithBackticks($item['refDataName']); ?>" <?= @replaceSingleQuotesWithBackticks($item['refDataName']) == @replaceSingleQuotesWithBackticks($userDetails->rashi) ? 'selected' : '' ?>><?= @replaceSingleQuotesWithBackticks($item['refDataName']); ?></option>


												<?php } ?>
											</select>
										</div>
									</fieldset>
								</div>

							</div>
							<div class="row m-0 p-0 <?= empty(@$userDetails->addressLine2) && empty(@$userDetails->addressLine1) ? '' : 'd-none' ?>">
								<div class="col-md-6">
									<fieldset class="border">
										<legend class="legend-inner float-none w-auto">Address Line 1<span class="fw-bold text-danger" style="font-size: 20px;">*</span></legend>
										<div class="input-group">
											<i class="fa fa2 fa-map-marker"></i>
											<input type="text" class="form-control form-control2" name="address_line1" id="address_line1" value="<?= set_value('address_line1', @$userDetails->addressLine1) ?>" placeholder="Address Line 1" onchange="SetAddress()" aria-label="address_line1" required>
										</div>
									</fieldset>
								</div>
								<div class="col-md-6">
									<fieldset class="border">
										<legend class="legend-inner float-none w-auto">Address Line 2<span class="fw-bold text-danger" style="font-size: 20px;">*</span></legend>
										<div class="input-group">
											<i class="fa fa2 fa-map-marker"></i>
											<input type="text" class="form-control form-control2" name="address_line2" id="address_line2" value="<?= set_value('address_line2', @$userDetails->addressLine2) ?>" onchange="SetAddress()" placeholder="Address Line 2" aria-label="address_line2" required>
										</div>
									</fieldset>
								</div>


								<div class="col-md-6 d-none">
									<fieldset class="border">
										<legend class="legend-inner float-none w-auto">County<span class="text-danger fw-bold" style="font-size: 20px;">&nbsp;</span></legend>
										<div class="input-group">
											<i class="fa fa2 fa-map-marker"></i>
											<input type="text" class="form-control form-control2" name="county" id="county" value="<?= set_value('county', @$userDetails->county) ?>" onchange="SetAddress()" placeholder="County" aria-label="county" required>
										</div>
									</fieldset>
								</div>

							</div>
							<div class="row  m-0 p-0 <?= empty(@$userDetails->addressLine2) && empty(@$userDetails->addressLine1) ? '' : 'd-none' ?>">
								<div class="col-md-4">
									<fieldset class="border">
										<legend class="legend-inner float-none w-auto">State<span class="fw-bold text-danger" style="font-size: 20px;">*</span></legend>
										<div class="input-group">
											<select class="form-control form-control2 select2 rounded form-select pt-0" onchange="SetAddress()" name="stateTypes" id="stateSelect" required>
												<option value="" selected>Select State</option>
												<?php

												// print_r($userDetails);

												$keys = array_column($GetState, 'refDataName'); /// Multidiamensional array sort by key
												array_multisort($keys, SORT_ASC, $GetState);

												foreach ($GetState as $state) { ?>
													<option value="<?= @replaceSingleQuotesWithBackticks($state->refDataName) ?>" <?= @replaceSingleQuotesWithBackticks($state->refDataName) == @replaceSingleQuotesWithBackticks($userDetails->stateTypes) ? 'selected' : ''; ?>><?= @replaceSingleQuotesWithBackticks($state->refDataName) ?></option>
												<?php } ?>
											</select>
										</div>
									</fieldset>
								</div>
								<div class="col-md-4">
									<fieldset class="border">
										<legend class="legend-inner float-none w-auto">City<span class="fw-bold text-danger" style="font-size: 20px;">*</span></legend>
										<div class="input-group">
											<select class="form-control form-control2 rounded select3 form-select pt-0" onchange="SetAddress()" name="cityTypes" id="cityTypes" required>
												<option value="" selected disabled>Select City</option>
											</select>
										</div>
									</fieldset>
								</div>
								<div class="col-md-4">
									<fieldset class="border">
										<legend class="legend-inner float-none w-auto">Zip Code<span class="fw-bold text-danger" style="font-size: 20px;">*</span></legend>
										<div class="input-group">
											<i class="fa fa-file"></i>
											<input type="number" class="form-control form-control2" onchange="SetAddress()" onKeyPress="if(this.value.length==6) return false;" name="zip" id="zip" value="<?= set_value('zip', @$userDetails->zip) ?>" placeholder="Zip Code" aria-label="zip" aria-describedby="basic-addon1" required>
										</div>
									</fieldset>
								</div>
							</div>


							<div class="row m-0 p-5 <?= !empty(@$userDetails->addressLine2) || !empty(@$userDetails->addressLine1) ? '' : 'd-none' ?>">
								<?php
								$addressLine = '';
								if (isset($userDetails->addressLine1) && !empty($userDetails->addressLine1)) {
									$addressLine .= !empty($addressLine) ? ', ' . $userDetails->addressLine1 : $userDetails->addressLine1;
								}
								if (isset($userDetails->addressLine2) && !empty($userDetails->addressLine2)) {
									$addressLine .= !empty($addressLine) ? ', ' . $userDetails->addressLine2 : $userDetails->addressLine2;
								}
								if (isset($userDetails->cityTypes) && !empty($userDetails->cityTypes)) {
									$addressLine .= !empty($addressLine) ? ', ' . $userDetails->cityTypes : $userDetails->cityTypes;
								}
								if (isset($userDetails->stateTypes) && !empty($userDetails->stateTypes)) {
									$addressLine .= !empty($addressLine) ? ', ' . $userDetails->stateTypes : $userDetails->stateTypes;
								}
								if (isset($userDetails->zip) && !empty($userDetails->zip)) {
									$addressLine .= !empty($addressLine) ? ', ' . $userDetails->zip : $userDetails->zip;
								}

								?>
								<div class="col-md-12 m-0 p-5">
									<fieldset class="border">
										<legend class="legend-inner float-none w-auto required">Street Address<span class="mandate">*</span></legend>
										<div class="input-group">
											<input type="text" class="form-control2 form-control " onchange="SetVenueAddressBox()" name="streetAddress" id="streetAddress" placeholder="Street Address*" style="color:black!important;" required value="<?= set_value('streetAddress', @$addressLine); ?>">
										</div>
									</fieldset>
								</div>

							</div>
						</fieldset>

						<div class="col-md-4 d-none">
							<fieldset class="border">
								<legend class="legend-inner float-none w-auto required">State<span class="mandate">*</span></legend>
								<div class="input-group">
									<input type="text" name="state" id="state" class="form-control2 form-control" placeholder="State" value="<?= set_value('state', @$userDetails->stateTypes); ?>">
								</div>
							</fieldset>
						</div>
						<div class="col-md-4 d-none">
							<fieldset class="border">
								<legend class="legend-inner float-none w-auto required">City<span class="mandate">*</span></legend>
								<div class="input-group">
									<input type="text" name="city" id="city" class="form-control2 form-control" placeholder="City" value="<?= set_value('city', @$userDetails->cityTypes); ?>">
								</div>
							</fieldset>
						</div>

						<div class="col-md-4 d-none">
							<fieldset class="border">
								<legend class="legend-inner float-none w-auto required">Zip Code<span class="mandate">*</span></legend>
								<div class="input-group">
									<input type="text" class="form-control2 form-control" style="color:black!important;" name="zipcode" id="zipcode" placeholder="Zip Code*" value="<?= set_value('zipcode', @$userDetails->zip) ?>" required>
								</div>
							</fieldset>
						</div>

						<fieldset class="border-2">
							<div class="row">
								<?php
								// var_dump($preferredLocations);
								?>
								<div class="col-md-4 m-0 p-5">
									<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" required>
												<option value=" " selected disabled style="color:black!important;">Preferred Location</option>
												<?php

												// $preferredLocations = sortBySequenceId($preferredLocations);

												foreach ($preferredLocations as $item) {

													if ($item->refDataName == 'IN-TEMPLE') {
														$catName = 'IN TEMPLE';
													} else if ($item->refDataName == 'SHRAADHAM') {

														$catName = 'APARAKARYA';
													} else if ($item->refDataName == 'AWAY-TEMPLE') {
														$catName = 'OUTSIDE TEMPLE';
													} else {
														$catName = @$item->refDataDesc;
													}
												?>
													<option
														value="<?= htmlspecialchars(@$item->refDataName, ENT_QUOTES, 'UTF-8'); ?>" data-serviceType="<?= @$item->serviceType ?>" data-exemptedServiceType="<?= @$item->exemptedServiceType ?>"
														<?=
														($this->uri->segment(3) == 'outside-temple' && $catName == 'OUTSIDE TEMPLE'  && @$item->serviceType != 'OUT OF TOWN') ? 'selected' : (($this->uri->segment(3) == 'aparakarya' && $catName == 'APARAKARYA') ? 'selected' : (($this->uri->segment(3) == 'inside-temple' && $catName == 'IN TEMPLE') ? 'selected' : '')
														);
														?>>
														<?= htmlspecialchars(@$item->refDataDesc, ENT_QUOTES, 'UTF-8'); ?>
													</option>


												<?php } ?>
											</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" required>
												<option value=" " selected disabled>Select Service</option>
											</select>
											<input type="hidden" id="serviceType" name="serviceType">
											<input type="hidden" id="serviceAmount" name="serviceAmount">
											<input type="hidden" id="discountedAmount" name="discountedAmount">
											<input type="hidden" id="oldServiceAmount" name="oldServiceAmount">
											<input type="hidden" id="couponCode" name="couponCode">
											<input type="hidden" id="couponId" name="couponId">
											<input type="hidden" name="serviceId" id="serviceId">
										</div>
									</fieldset>
								</div>

								<div class="col-md-12 m-0 p-5" style="display: none;" id="serviceDetailsBox">


								</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="serviceAmountBox" id="serviceAmountBox" placeholder="Service Amount*" value="" readonly required style="background-color: #e7e6e6;">
										</div>
									</fieldset>
								</div>


								<div class="col-md-3 m-0 p-5">
									<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 required>
										</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='form-control2 form-control' name="serviceTime" id="serviceTime" placeholder='00:00' required>

										</div>
									</fieldset>

								</div>

								<div class="col-md-3 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" required>
												<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">
									<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" required>
												<option value=" " selected disabled>Select Venue</option>
												<option value="Same as Home Address">Same as Home Address</option>
												<option value="Same as Temple Address">Same as Temple Address</option>
												<option value="Other">Other</option>
											</select>

										</div>
									</fieldset>

								</div>

								<div class="col-md-12 m-0 p-5">
									<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">
									<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 add details about puja as per discussion with priest."></textarea>

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

						<div style="display: flex; justify-content: center;">
							<a href="javaScript:void(0)" class="btn btn-primary" id="submitRequestForm" style="border-radius: 3px!important; background: var(--main-color-new-theme)!important; border-color: var(--main-color-new-theme)!important; box-shadow: 1px 1px 10px black; margin-bottom: 18px;" onclick="submitForm()"><?= $formAction == 'BOOKING WITH PAYMENT' ? 'Book Now' : 'Send Request' ?> <i class="fa fa-paper-plane"></i></a>
						</div>
						</form>
				</div>

			</div>
		</div>
		</div>
		<div class="modal fade" id="membershipModal" 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">
								<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">
														<thead>
															<tr>
																<th>
																	<h5 class="h5-title">Service Name</h5>
																</th>
																<th>
																	<h5 class="h5-title">Amount to Pay</h5>
																</th>
															</tr>
														</thead>
														<tbody>
															<tr>
																<td id="serviceNameedittable">

																</td>

																<td id="edittable">

																</td>
															</tr>

														</tbody>
													</table>
												</div>
												<div class="col-sm-12" id="serviceNameedittableBody">

												</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> -->
																		<input type="text" class="form-control" id="mpi_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; ?>"> -->

																		<input type="number" class="form-control" id="mpi_zipcode" name="mpi_zipcode" 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>
		<?php

		$booking = getBookingTimes(); // ['startTime' => '09:00 AM', 'endTime' => '09:00 PM']

		$TempleAddress = getclientInfoById()['data'][0];
		$TempleAddress =  $TempleAddress['addressLineOne'] . ' ' . $TempleAddress['addressLinetwo'] . ' ' . $TempleAddress['state'] . ' ' . $TempleAddress['city'] . ' ' . $TempleAddress['zipCode'];
		?>
		<script type="text/javascript" src="<?= base_url('assets/js/time-picker.js') ?>"></script>
		<script src="<?= base_url('assets/js/jquery-ui.min.js'); ?>"></script>
		<link href="<?= base_url('assets/css/select2.min.css'); ?>" rel="stylesheet" />
		<script src="<?= base_url('assets/js/select2.min.js'); ?>"></script>
		<script type="text/javascript" src="<?= base_url('admin_assets/js/jquery.validate.js'); ?>"></script>
		<script type="text/javascript">
			$('#serviceRequestForm').keypress(function(e) {
				if (e.which == 13) {
					$('#serviceRequestBtn').click();
					return false;
				}
			});
			const bookingStartTime = "<?php echo $booking['startTime']; ?>"; // 09:00 AM
			const bookingEndTime = "<?php echo $booking['endTime']; ?>"; // 09:00 PM
			$(function() {

				$("#serviceAddressBox").hide();
				$otherField = $("#serviceAddressBox");
				$otherFieldval = $("#serviceAddress");

				$('#preferredLocation').on('change', function() {
					// alert();
					if (this.value == 'AWAY-TEMPLE') {



						$otherFieldval.val("");
						$otherField.show();
						$('#serviceAddress').prop('readonly', false);
					} else if (this.value == 'IN-TEMPLE') {
						var templeAddress = "<?= $TempleAddress ?>";

						$otherField.show();
						$('#serviceAddress').prop('readonly', true);
						$otherFieldval.val(templeAddress);

					} else {
						$otherFieldval.val("");
						$otherField.show();
						$('#serviceAddress').prop('readonly', false);
					}

				});


				// $('#serviceTime').mdtimepicker();
				function convertTo24HourMinutes(timeStr) {
					if (!timeStr || typeof timeStr !== 'string') return 0;
					let [time, meridian] = timeStr.trim().split(" ");
					if (!time || !meridian) return 0;

					let [hh, mm] = time.split(":").map(Number);
					if (meridian.toLowerCase() === 'pm' && hh !== 12) hh += 12;
					if (meridian.toLowerCase() === 'am' && hh === 12) hh = 0;

					return hh * 60 + mm;
				}

				$('#serviceTime').on('focus', function() {
					const dateSelected = $('#serviceDate').val();
					if (!dateSelected || dateSelected.trim() === '') {
						$("#serviceDate").notify("Please select a date first.", {
							position: "bottom",
							className: "error",
						});
						$(this).blur();
						return;
					}

					const selectedDate = new Date(dateSelected);
					const today = new Date();
					const formatDate = d => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
					const isToday = formatDate(selectedDate) === formatDate(today);

					const startMinutes = convertTo24HourMinutes(bookingStartTime);
					const endMinutes = convertTo24HourMinutes(bookingEndTime);

					let minMinutes = startMinutes;
					if (isToday) {
						const now = new Date();
						const currentMinutes = now.getHours() * 60 + now.getMinutes();
						minMinutes = Math.max(currentMinutes + 1, startMinutes); // +1 min buffer
					}

					const minHr = Math.floor(minMinutes / 60);
					const minMin = minMinutes % 60;
					const maxHr = Math.floor(endMinutes / 60);
					const maxMin = endMinutes % 60;

					let timepickerOptions = {
						timeFormat: 'hh:mm tt',
						theme: 'blue',
						readOnly: true,
						minTime: `${String(minHr).padStart(2, '0')}:${String(minMin).padStart(2, '0')}`,
						maxTime: `${String(maxHr).padStart(2, '0')}:${String(maxMin).padStart(2, '0')}`
					};

					$('#serviceTime').mdtimepicker('destroy');
					$('#serviceTime').mdtimepicker(timepickerOptions);
				});

				// Validation inside timechanged
				$("#serviceTime").off('timechanged').on('timechanged', function(e) {
					const selectedTime = e.time;
					if (!selectedTime) return;

					let selectedHour = 0;
					let selectedMinute = 0;

					if (selectedTime.includes(" ")) {
						let [time, meridian] = selectedTime.split(" ");
						if (!meridian || !time) return; // Prevent undefined error

						let [hh, mm] = time.split(":");
						hh = parseInt(hh);
						mm = parseInt(mm);

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

					const selectedTotalMinutes = selectedHour * 60 + selectedMinute;

					const selectedDate = new Date($('#serviceDate').val());
					const today = new Date();
					const formatDate = d => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
					const isToday = formatDate(selectedDate) === formatDate(today);

					const minAllowed = convertTo24HourMinutes(bookingStartTime);
					const maxAllowed = convertTo24HourMinutes(bookingEndTime);

					if (isToday) {
						const now = new Date();
						const currentMinutes = now.getHours() * 60 + now.getMinutes();
						if (selectedTotalMinutes <= currentMinutes) {
							// $("#serviceTime").notify("Please select a time after the current time.", {
							// 	position: "bottom",
							// 	className: "error",
							// });


							Swal.fire('Please select a time after the current time.', '', 'warning');


							$("#serviceTime").val('');
							return;
						}
					}

					if (selectedTotalMinutes < minAllowed || selectedTotalMinutes > maxAllowed) {
						// $("#serviceTime").notify(`Please select a time between ${bookingStartTime} and ${bookingEndTime}.`, {
						// 	position: "bottom",
						// 	className: "error",
						// });
						Swal.fire(`Please select a time between ${bookingStartTime} and ${bookingEndTime}.`, '', 'warning');
						$("#serviceTime").val('');
						return;
					}

					// Valid time selected
					// addTocart();
				});

				$(document).on('click', '.mdtp__button', function() {
					console.log("sdgdfg");
					fetchPriestAvailability();
				});

				function fetchPriestAvailability() {
					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) {
								$("#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.');
					}
				}


				$("input[id^='serviceDate']").on('change', function() {
					$("#serviceTime").val('');
				});
			});




			function checkValue(str, max) {
				if (str.charAt(0) !== '0' || str == '00') {
					var num = parseInt(str);
					if (isNaN(num) || num <= 0 || num > max) num = 1;
					str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString();
				};
				return str;
			};

			$('#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);

			});

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


				var param = $(this).val();
				var serviceCatTypes = $(this).find(':selected').data('servicetype'); // Selected option ka data attribute
				var exemptedServiceType = $(this).find(':selected').data('exemptedservicetype');
				// console.log("exemptedServiceType: "+exemptedServiceType);
				// console.log("serviceCatTypes: "+serviceCatTypes);
				if (param == 'AWAY-TEMPLE' || param == 'OUT OF TOWN') {
					$("#selectVenue").html('<option value=" " disabled selected>Select Venue</option><option value="Same as Home Address">Same as Home Address</option><option value="Other">Other</option>');

					$('#selectVenue').prop('disabled', false);
				} else if (param == 'SHRAADHAM') {

					$("#selectVenue").html('<option value=" " disabled selected>Select Venue</option><option value="Same as Home Address">Same as Home Address</option><option value="Same as Temple Address">Same as Temple Address</option><option value="Other">Other</option>');

					$('#selectVenue').prop('disabled', false);

				} else {
					$("#selectVenue").html(`
													<option value="Same as Temple Address" selected>Same as Temple Address</option>
													`);

					$('#selectVenue').prop('disabled', true);
				}




				$.ajax({
					url: "<?= base_url('admin/GetServicesByCategory') ?>",
					type: "POST",
					data: {
						'param': param,
						'serviceCatTypes': serviceCatTypes,
						'exemptedServiceType': exemptedServiceType
					},
					success: function(data) {
						if (data == '') {
							$('#serviceName').html('<option value=" " disabled selected>No Service Available On This Location.</option>');
						} else {
							$('#serviceName').html(data);
						}


						$('#serviceName').select2();


					}
				});

			});



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

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

				$("#serviceType").val(serviceType);

				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');
					$("#serviceAmountBox").val('TBD By Priest');

				} else {
					$("#serviceDetailsBox").css('display', 'none');
					$("#serviceDetailsBox").html('');
					var serviceAmount = $('option:selected', this).attr('serviceAmount');
					var membership_discount_amt = $('option:selected', this).attr('membership_discount_amt');
					var membershipStatus = '<?= $membershipDetails['membershipStatus'] ?>';

					let discount = 0;
					if (is_membership_discount == 'YES' && membershipStatus == 'ACTIVE') {
						var membershipType = '<?= $membershipDetails['membershipType'] ?>';
						let membershipDiscount = <?= $membershipDiscount ?>;
						if ('<?= $discountType ?>' == 'FLAT') {

							if (serviceAmount > membershipDiscount) {
								discount = serviceAmount - membershipDiscount;
							}
						} else if ('<?= $discountType ?>' == 'SERVICE LEVEL') {
							discount = membership_discount_amt > 0 ? serviceAmount - membership_discount_amt : 0;
						} else {
							discount = (serviceAmount * membershipDiscount) / 100;
						}
					}
					let discountedAmount = (parseFloat(serviceAmount) - parseFloat(discount)).toFixed(2);
					console.log("discountedAmount: " + discountedAmount);
					console.log("Amount: " + serviceAmount);
					$("#serviceAmount").val(discountedAmount);
					$("#serviceAmountBox").val('$ ' + parseFloat(serviceAmount).toFixed(2));
					$("#oldServiceAmount").val(parseFloat(serviceAmount).toFixed(2));
					$("#discountedAmount").val(discount);
					$("#couponCode").val(membershipType);
					$("#couponId").val('');
				}
			});


			$(document).ready(function() {
				$('#preferredLocation option[selected]').parent().change();

			});
			/*	$('#serviceName').change(function() {

					var serviceAmount = $('option:selected', this).attr('serviceAmount');


					var finalPrice = (serviceAmount / 1).toFixed(2);

					$("#serviceAmount").val(finalPrice);

				});*/


			$(document).ready(function() {
				$("#serviceRequestForm").validate({

					submitHandler: function(form) {
						form.submit();
					}

				});
			});

			$("#serviceDate").datepicker({
				dateFormat: "mm/dd/yy",
				minDate: 0
			});




			$(document).ready(function() {
				$('#inlineCheckbox').change(function() {
					var isChecked = $(this).prop('checked');
					var select = $('#priestName');
					var anyPriestOption = select.find('option[value="Any Priest"]');

					if (isChecked) {
						anyPriestOption.remove();
						$("#serviceTime").attr('required', true);
						$("#serviceDate").attr('required', true);
					} else {
						select.append('<option value="Any Priest" email="" phone="">Any Priest</option>');
						$("#serviceTime").attr('required', false);
						$("#serviceDate").attr('required', false);
					}
				});


				$('#selectVenue').change(function() {
					var selectedOption = $(this).val();
					var addressInput = $('#serviceAddress');

					if (selectedOption === 'Same as Home Address') {
						var homeAddress = "<?= @$userDetails->addressLine1; ?>";
						// addressInput.val(homeAddress);
						var address = $("#streetAddress").val();
						$("#serviceAddress").val(address);
						addressInput.prop('readonly', true);
					} else if (selectedOption === 'Same as Temple Address') {
						var templeAddress = "<?= $TempleAddress ?>";
						addressInput.val(templeAddress);
						addressInput.prop('readonly', true);
					} else if (selectedOption === 'Other') {
						addressInput.val('');
						addressInput.prop('readonly', false);
						// addressInput.prop('disabled', false);
					}
				});
			});

			function submitForm() {
				let htmlContent = `
					<ol style="text-align: left; font-size: 0.9em; line-height: 1.7;">
					<li style="font-size: 16px !important;">This is a sample text only. Please specify your temple's specific services details to be replaced here.</li>
					</ol>`;

				if ('<?= $formAction ?>' === 'BOOKING WITH PAYMENT') {
					htmlContent += `
					<li style="color: var(--main-color-new-theme)!important; list-style: none; font-size: 18px !important; font-weight: bold;">
						Do you want to book this service to Temple?
					</li>`;
				} else {
					htmlContent += `
					<li style="color: var(--main-color-new-theme)!important; list-style: none; font-size: 18px !important; font-weight: bold;">
						Do you want to proceed with the request?
					</li>`;
				}
				Swal.fire({
					title: `
					<div style="display: flex; align-items: center; gap: 17px; margin-top: -35px; margin-bottom: -50px;">
						<img src="https://sreedevipeetham-pre.vaaptech.com/assets/img/img.png" alt="Logo" style="width: 80px; height: auto; margin-top: -7px;">
						<span style="font-size: 1.0em !important;">DISCLOSURE</span>
					</div>`,
					html: htmlContent,
					showCancelButton: true,
					confirmButtonText: 'Send',
					cancelButtonText: 'Cancel',
				}).then((result) => {
					if (result.isConfirmed) {
						// Validate form fields
						let isValid = true;
						const fields = [{
								id: "streetAddress",
								message: "Street Address is required."
							},
							{
								id: "preferredLocation",
								message: "Preferred Location is required."
							},
							{
								id: "serviceName",
								message: "Service Name is required."
							},
							{
								id: "serviceAmountBox",
								message: "Service Amount is required."
							},
							{
								id: "serviceDate",
								message: "Service Date is required."
							},
							{
								id: "serviceTime",
								message: "Service Time is required."
							},
							{
								id: "priestName",
								message: "Priest Name is required."
							},
							{
								id: "selectVenue",
								message: "Venue selection is required."
							},
							{
								id: "serviceAddress",
								message: "Service address is required."
							}
						];

						fields.forEach(field => {
							const $input = $("#" + field.id); // Find the input field
							if ($input.length > 0) { // Ensure it exists
								// alert(field.id+" "+$input.val());
								if (!$input.val() || !$input.val().trim()) {
									isValid = false;
									const $errorLabel = $("#" + field.id + "-error");
									if ($errorLabel.length === 0) {
										$input.after(`<label id="${field.id}-error" class="error">${field.message}</label>`);
									}
									$input.addClass("is-invalid");
								} else {
									$("#" + field.id + "-error").remove();
									$input.removeClass("is-invalid");
								}


							} else {
								console.error(`Element with ID #${field.id} not found in the DOM.`);
							}
						});

						if (isValid) {
							const formAction = "<?= $formAction ?>"; // Adjust this as needed
							if (formAction == "REQUEST WITH PAYMENT" || formAction == "BOOKING WITH PAYMENT") {
								var amt = $("#serviceAmount").val();
								var oldAmt = $("#oldServiceAmount").val();
								var distAmt = $("#discountedAmount").val();
								var serviceName = $("#serviceName").val();
								console.log("serviceName: " + serviceName);
								$("#serviceNameedittable").html('<h4 id="serviceType">' + serviceName + '</h4><input type="hidden" name="" value="' + serviceName + '" id="serviceType">');
								$("#edittable").html('<h4 id="servicePrice">' + oldAmt + '</h4><input type="hidden" name="" value="' + oldAmt + '" id="serviceAmt"><input type="hidden" name="" value="' + serviceName + '" id="serviceType">');
								if (oldAmt > amt) {
									var distType = '( ' + <?= $membershipDiscount ?> + '% )';
									if ('<?= $discountType ?>' == 'FLAT' || '<?= $discountType ?>' == 'SERVICE LEVEL') {
										distType = '( $ ' + distAmt + ' )';
									}
									var newRow = '<div class="row"><div class="col-md-6"><h5 class="mb-0" style="font-weight:bold!important;">Subtotal</h5></div><div class="col-md-6 text-end"><span style="font-weight:bold!important;" id="subtle"><?= $currencySymbol ?>&nbsp;' + parseFloat(oldAmt).toFixed(2) + '</span></div></div>'
									newRow += '<hr><div class="row"><div class="col-md-6"><h5 class="mb-0" style="font-weight:bold!important;font-size: 16px;color:#b00000;"> Membership Discount Applied ' + distType + '</h5></div><div class="col-md-6 text-end"><span style="font-weight:bold!important;color:#b00000;" id="subtle"><?= $currencySymbol ?>&nbsp;' + parseFloat(distAmt).toFixed(2) + '</span></div></div>';
									newRow += '<hr><div class="row"><div class="col-md-6"><h5 class="mb-0" style="font-weight:bold!important;">Sale Total</h5></div><div class="col-md-6 text-end"><span style="font-weight:bold!important;color:#b00000;" id="subtle"><?= $currencySymbol ?>&nbsp;' + parseFloat(amt).toFixed(2) + '</span></div></div><hr>';

									$("#serviceNameedittableBody").empty().append(newRow);
								}
								$("#membershipModal").modal("show");
							} else {
								$("#serviceRequestForm").submit();
							}
						}
					} else if (result.isDenied) {
						Swal.fire('Changes are not saved', '', 'info');
					}
				});
			}






			function closeForm() {

				Swal.fire({
					title: 'Do you want to send request to temple?',
					showDenyButton: true,
					showCancelButton: true,
					showConfirmButton: false,
					cancelButtonText: 'No',
					denyButtonText: `Yes`,
				}).then((result) => {
					if (result.isConfirmed) {
						Swal.fire('Saved!', '', 'success')
					} else if (result.isDenied) {

						window.location.href = "<?= base_url('admin/my-service-request') ?>";
					}
				})
			}
		</script>

	<?php } ?>
	<!-- *************************Request Form Section End********************************* -->
	</section>



</main>
<input type="hidden" id="includeSankalpamModal" value="<?= @$includeSankalpam ?>">
<input type="hidden" id="datesArray" value="">

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

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

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

<script type="text/javascript">
	$(document).ready(function() {
		$("#searchIcon").click(function() {
			$("#search").toggleClass("open");

			if ($("#search").hasClass("open")) {
				$("#search").removeClass("d-none").focus();
			} else {
				$("#search").addClass("d-none").val('');
			}
		});

		// Click outside to close search bar
		$(document).click(function(event) {
			if (!$(event.target).closest("#searchIcon, #search").length) {
				$("#search").addClass("d-none").removeClass("open");
			}
		});
	});

	function OpenPayLaterPage(pageName) {
		window.location.href = "<?= base_url('services/payLater'); ?>";
	}

	$(document).ready(function() {

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

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

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

		const bookingStartTime = "<?php echo $booking['startTime']; ?>"; // 09:00 AM
		const bookingEndTime = "<?php echo $booking['endTime']; ?>"; // 09:00 PM
		function convertTo24HourMinutes(timeStr) {
			if (!timeStr || typeof timeStr !== 'string') return 0;
			let [time, meridian] = timeStr.trim().split(" ");
			if (!time || !meridian) return 0;

			let [hh, mm] = time.split(":").map(Number);
			if (meridian.toLowerCase() === 'pm' && hh !== 12) hh += 12;
			if (meridian.toLowerCase() === 'am' && hh === 12) hh = 0;

			return hh * 60 + mm;
		}

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

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

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

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

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

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

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

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

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

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

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

					let selectedHour = 0;
					let selectedMinute = 0;

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

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

					const selectedTotalMinutes = selectedHour * 60 + selectedMinute;

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

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



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

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

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


					// All good
					addTocart();
				});

			}


		});

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

	});

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

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

			if (noResults && value !== "") {
				$("#emptyServices").text("Service not found!").show();
			} else {
				$("#emptyServices").hide();
			}
		}).on("search", function() {
			if ($(this).val() === "") {
				$("#table tr").show();
				$("#emptyServices").hide();
			}
		});
	});




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

		var startDate = nclickF.attr('start_date');
		var endDate = nclickF.attr('end_date');


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



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


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


							beforeShowDay: function(date) {
								var dayOfWeek = $.datepicker.formatDate('DD', date);
								// console.log("dayOfWeek: "+dayOfWeek);
								// console.log("dayOfWeek: "+ getWeekdayOccurrence(date));
								var dateInMMDDYYFormat = $.datepicker.formatDate('yy-mm-dd', date);
								var today = new Date();
								var tithis = ["PRATIPADA", "DWITIYA", "TRITIYA", "CHATURTHI", "PANCHAMI", "SHASHDI", "SAPTAMI", "ASHTAMI", "NAVAMI", "DASHAMI", "EKADASHI", "DWADASHI", "TRAYODASHI", "CHATURDASHI", "PURNIMA", "AMAVASYA"];

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

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

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


								} else if (getWeekdayOccurrence(date) == dayVal.toUpperCase()) {


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



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

			}
		});

	});


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

		// Clear previously selected dates when opening the datepicker
		var selectedDates = []; // To store the selected dates

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

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

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

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

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


									}
									return nextDates;
								}

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

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


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

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

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

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

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


									}
									return nextDates;
								}

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

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


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

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

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


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

				// Show the datepicker
				$(nclickF).datepicker('show');
			}
		});
	});




	// Function to convert m/d/Y format to JavaScript Date object
	function parseDate(dateString) {
		if (dateString) {
			var parts = dateString.split('/');
			return new Date(parts[2], parts[0] - 1, parts[1]);
		} else {
			return null;
		}
	}

	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 addTocart() {

		var totalPrice = 0;
		var sankalpam_data = [];
		var cart_type = 'SERVICES';
		var ids = [];
		var qty = [];
		var ctg = [];
		var serviceTypes = [];
		var serviceName = [];
		var startDate = [];
		var startTime = [];
		var serviceAmount = [];
		var description = [];
		var image = [];
		var cart_ctg = [];
		var bookingtype = [];
		var includeSankalpam = [];
		var is_date_required = [];
		var isServicePaid = [];
		var is_membership_discount = [];
		var membership_discount_amt = [];
		var service_desc = [];
		var serviceOccurrencesNo = [];
		var fullPackage = [];
		var isDietySelected = [];
		var dietyName = [];
		var disclaimerText = [];

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


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

		var noDateSelected = 0;
		var addtoCartStatus = true;


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

			loader.on();

			var init_qty = parseInt($("#quantity-input" + id).val());
			var serviceoccurrencesno = parseFloat($(this).attr('data-serviceoccurrencesno'));

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

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

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


					addtoCartStatus = false;
					return false;
				} else {
					dietyName.push(selectedValue);
				}
			} else {
				dietyName.push('');
			}
			disclaimerText.push($(this).attr('disclaimerText'));
			if ($(this).attr('is_date_required') == 'YES') {
				if ($("#datepicker_" + id).val().length == 0) {
					$(this).prop('checked', false);
					$("#datepicker_" + id).focus();
					$("#datepicker_" + id).notify(
						"Please select date!", {
							position: "right"
						}
					);
					var dayVal = $("#datepicker_" + id).attr('daytype');
					var nclickF = $("#datepicker_" + id);

					$.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).multiDatesPicker('resetDates'); // Purana date hata dega
											$(this).multiDatesPicker('addDates', dateText);
											$(this).datepicker('show');
											addTocart();
										}
									});
								} else {

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


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

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

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

						}
					});

					addtoCartStatus = false;
					return false;
				}



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

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

				if (serviceoccurrencesno) {
					totalPrice = (parseFloat(totalPrice) + ((parseFloat($(this).attr('data-price')) * init_qty)));
					// $("#Totalprice_" + $(this).attr('data-id')).html("<?= $currencySymbol; ?>&nbsp;" + (parseFloat($(this).attr('data-price')) * init_qty).toFixed(2));
					let Price = parseFloat($(this).attr('data-price')) * init_qty;
					let formatted = Price.toLocaleString('en-US', {
						minimumFractionDigits: 2,
						maximumFractionDigits: 2
					});

					$("#Totalprice_" + $(this).attr('data-id')).html("<?= $currencySymbol; ?>&nbsp;" + formatted);

				} else {
					totalPrice = (parseFloat(totalPrice) + ((parseFloat($(this).attr('data-price')) * init_qty) * nDateSelectCount));
					// $("#Totalprice_" + $(this).attr('data-id')).html("<?= $currencySymbol; ?>&nbsp;" + (parseFloat($(this).attr('data-price')) * init_qty * nDateSelectCount).toFixed(2));
					let Price = parseFloat($(this).attr('data-price')) * init_qty * nDateSelectCount;
					let formatted = Price.toLocaleString('en-US', {
						minimumFractionDigits: 2,
						maximumFractionDigits: 2
					});


					$("#Totalprice_" + $(this).attr('data-id')).html("<?= $currencySymbol; ?>&nbsp;" + formatted);

				}




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

				// $("#Totalprice_" + $(this).attr('data-id')).html("<?= $currencySymbol; ?>&nbsp;" + (parseFloat($(this).attr('data-price')) * init_qty).toFixed(2));
				let Price = parseFloat($(this).attr('data-price')) * init_qty;
				let formatted = Price.toLocaleString('en-US', {
					minimumFractionDigits: 2,
					maximumFractionDigits: 2
				});
				$("#Totalprice_" + $(this).attr('data-id')).html("<?= $currencySymbol; ?>&nbsp;" + formatted);



				startDate.push('');
			}




			if ($(this).attr("booking_type") === 'PAY NOW') {

				isServicePaid.push("YES");

			} else if ($(this).attr("booking_type") === 'PAY LATER') {
				isServicePaid.push($(this).attr("NO"));

			} else {

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

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

				return `${formattedHour}:${formattedMinute}`;
			}
			if (time) {
				startTime.push(formattedTime);
			} else {
				startTime.push("");
			}


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


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

			bookingtype.push(booking_type);
			description.push($(this).attr('data-description').replace(/['"`]/g, ''));
			cart_ctg.push($(this).attr('cart_category'));
			if (serviceoccurrencesno) {
				// serviceAmount.push(parseFloat(parseFloat($(this).attr('data-price'))/serviceoccurrencesno).toFixed(2));
				fullPackage.push('true');
				serviceAmount.push(parseFloat(parseFloat($(this).attr('data-price')) / serviceoccurrencesno));
			} else {
				fullPackage.push('false');
				serviceAmount.push($(this).attr('data-price'));
			}

			ids.push($(this).attr('data-id'));
			includeSankalpam.push($(this).attr('includeSankalpam'));
			qty.push(init_qty);
			is_date_required.push($(this).attr('is_date_required'));
			is_membership_discount.push($(this).attr('is_membership_discount'));
			membership_discount_amt.push($(this).attr('membership_discount_amt'));
			service_desc.push($(this).attr('data-servicedesc'));
			serviceOccurrencesNo.push($(this).attr('data-serviceOccurrencesNo'));

		});


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

				$(".cart-count").text(noDateSelected);
			} else {
				// $(".cart-count").text(ids.length);
			}
			let formatted = totalPrice.toLocaleString('en-US', {
				minimumFractionDigits: 2,
				maximumFractionDigits: 2
			});
			$(".allPrice").text(formatted);
		}

		$.ajax({
			type: "POST",
			url: "<?= base_url('Services/addCart'); ?>",
			dataType: 'json',
			data: {
				ids: ids,
				totalPrice: totalPrice,
				qty: qty,
				ctg: ctg,
				serviceTypes: serviceTypes,
				serviceName: serviceName,
				startDate: startDate,
				startTime: startTime,
				serviceAmount: serviceAmount,
				cart_type: cart_type,
				image: image,
				description: description,
				cart_ctg: cart_ctg,
				bookingtype: bookingtype,
				includeSankalpam: includeSankalpam,
				is_date_required: is_date_required,
				is_membership_discount: is_membership_discount,
				membership_discount_amt: membership_discount_amt,
				service_desc: service_desc,
				serviceOccurrencesNo: serviceOccurrencesNo,
				fullPackage: fullPackage,
				dietyName: dietyName,
				isDietySelected: isDietySelected,
				disclaimerText: disclaimerText
			},
			success: function(result) {
				console.log(result);
				$("#includeSankalpamModal").val(result.includeSankalpam);
				// loader.off();
				updateCartCount();
			}
		});


	}




	function quantityMinusFunction(id) {

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

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

		addTocart();
	}

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

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

	}


	function ViewCart() {
		// if ($(".cart-count").text() > 0) {
		// 	window.location.href = "<?= base_url('Services/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) {
		// alert(parseInt($(".cart-count").text()));
		if (parseInt($(".cart-count").text()) > 0) {
			loader.on();

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

					if (data == 0) {
						openLoginModal(page_name);
					} else {
						if (page_name == 'services') {
							window.location.href = "<?= base_url('checkout/service') ?>";
						}

					}

				}
			});

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


		}
	}

	function changebtnStyles(id) {
		$(".styles").removeClass('active-services');
		$(".styles").addClass('services');
		$("#" + id).addClass('active-services');
		$("#" + id).removeClass('services');
	}


	function availabelServiceList(serviceID) {

		// loader.on();
		var serviceObject = $("input[value='" + serviceID + "']");
		var startDate = $(serviceObject).attr('data-start-date');
		var startTime = $(serviceObject).attr('data-start-time');
		var serviceName = $(serviceObject).attr('data-service-name');
		var endDate = $(serviceObject).attr('data-end-date');
		var endTime = $(serviceObject).attr('data-end-time');
		var daytype = $(serviceObject).attr('data-daytype');
		var cutofftime = $(serviceObject).attr('cutofftime');
		var holdingDates = $(serviceObject).attr('data-holdingDates');

		var BookingLimitPerDay = $(serviceObject).attr('data-BookingLimitPerDay');


		$.ajax({
			url: "<?= base_url('Services/checkServiceAvailibilty'); ?>",
			type: "POST",
			data: {
				startDate: startDate,
				startTime: startTime,
				serviceName: serviceName,
				endDate: endDate,
				endTime: endTime,
				daytype: daytype,
				cutofftime: cutofftime,
				BookingLimitPerDay: BookingLimitPerDay,
				serviceID: serviceID,
				holdingDates: holdingDates,
			},
			dataType: "json",
			success: function(data) {
				// loader.off();

				if (data.statusCode) {
					console.log("show");
					$("#service_titlt_vadamala").text(serviceName + " Service Availability List");
					$("#showServiceListModal").modal('show');
					$("#headerMonths").text(data.headerMonths);
					$("#showServiceListModal table tbody").html(data.servicesList);

				} else {

				}

			}
		});
	}


	function serviceAvailabilitybook(obj) {
		$("#showServiceListModal").modal('hide');
		var date = $(obj).attr('data-date');
		var serviceID = $(obj).attr('data-service-id');
		var noAvailability = $(obj).attr('data-availability');

		$("#datepicker_" + serviceID).val(date);
		$("#timepicker_" + serviceID).prop('required', true);
		$("#quantity-input" + serviceID).attr('max', noAvailability);

	}


	// ********************************
	$('.extra-fields-customer').click(function() {
		$('.customer_records').clone().appendTo('.customer_records_dynamic');
		$('.customer_records_dynamic .customer_records').addClass('single remove');
		$('.single .extra-fields-customer').remove();
		$('.single').append('<a href="#" class="btn btn-sm btn-danger remove-field btn-remove-customer mx-3 mb-3 mt-0" style="border-radius: 2px!important; margin-top: 8px; margin-right: 5px;">Remove Fields</a>');
		$('.customer_records_dynamic > .single').attr("class", "remove");

		$('.customer_records_dynamic input').each(function() {
			var count = 0;
			var fieldname = $(this).attr("name");
			$(this).attr('name', fieldname + count);
			count++;
		});

	});

	$(document).on('click', '.remove-field', function(e) {
		$(this).parent('.remove').remove();
		e.preventDefault();
	});

	function sendSankalpamToSession() {



		var formData = {};
		$('.form-group input').each(function() {
			var fieldName = $(this).attr('name');
			var fieldValue = $(this).val();
			formData[fieldName] = fieldValue;
		});



		$.ajax({
			url: "<?= base_url('Services/AddSankalpamToSession'); ?>",
			type: "POST",
			data: {
				formData: formData
			},
			dataType: "json",
			success: function(data) {


				if (data.statusCode == 1) {
					window.location.href = "<?= base_url('checkout/service') ?>";
				}

			}
		});


	}


	$(document).ready(function() {
		function fetchPriestAvailability() {
			var serviceDate = $('#serviceDate').val();
			var serviceTime = $('#serviceTime').val();

			if (serviceDate != '' && serviceTime != '') {
				$.ajax({
					url: '<?= base_url('Home/GetPriestAvailibility') ?>',
					type: 'POST',
					data: {
						serviceDate: serviceDate,
						serviceTime: serviceTime
					},
					success: function(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);
		// $("#serviceTime").on("input change", fetchPriestAvailability);
		$(".mdtp__button").click(function() {
			fetchPriestAvailability();
		});

	});




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

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

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

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

			var spanId = "Totalprice_" + id;

			var checkboxId = "checkbox_" + id;

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

			addTocart();
		});
	});

	function SetVenueAddressBox() {
		var venue = $("#selectVenue").val();
		if (venue == 'Same as Home Address') {
			var address = $("#streetAddress").val();
			$("#serviceAddress").val(address);
		}
	}

	function SetAddress() {
		var address_line1 = '',
			address_line2 = '',
			county = '',
			stateSelect = '',
			city = '',
			zipcode = '';
		address_line1 = $("#address_line1").val();
		address_line2 = $("#address_line2").val();
		county = $("#county").val();
		stateSelect = $("#stateSelect").val();
		city = $("#cityTypes").val();
		zipcode = $("#zip").val();
		var address = '';
		if (address_line1) {
			address = address_line1;
		}
		if (address_line2) {
			address = address + ', ' + address_line2;
		}
		if (county) {
			address = address + ', ' + county;
		}
		if (stateSelect) {
			address = address + ', ' + stateSelect;
		}
		if (city) {
			address = address + ', ' + city;
		}
		if (zipcode) {
			address = address + ', ' + zipcode;
		}
		// address=address_line1+', '+address_line2+', '+county+', '+stateSelect+', '+city+', '+zipcode;
		console.log(address);
		$("#streetAddress").val(address);
	}
	$('#stateSelect').change(function() {

		var stateCode = $(this).val();
		$.ajax({
			url: "<?= base_url('admin/getCityByState') ?>",
			type: "POST",
			// dataType: "json",
			data: {
				'stateCode': stateCode
			},
			success: function(data) {
				$("#cityTypes").html(data);
			}
		});

	});

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

		// Get the day of the week (0 = Sunday, 1 = Monday, ..., 6 = Saturday)
		const weekday = date.getDay();

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

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

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

		// Return the result
		return `${occurrences[occurrence]} ${weekdayNames[weekday]}`;
	}
</script>



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

<script>
	/*	var formData1 = $("#serviceRequestForm").serializeArray();
	console.log("Serialized Form Data:", formData1);

const SubmitformData = {
	fname:formData1.find(item => item.name === 'fname')?.value,
	lname:formData1.find(item => item.name === 'lname')?.value,
	email:formData1.find(item => item.name === 'email')?.value,
	phone:formData1.find(item => item.name === 'phone')?.value,
	gotra:formData1.find(item => item.name === 'gotra')?.value,
	stars:formData1.find(item => item.name === 'stars')?.value,
	rashi:formData1.find(item => item.name === 'rashi')?.value,
	streetAddress:formData1.find(item => item.name === 'streetAddress')?.value,
	preferredLocation:formData1.find(item => item.name === 'preferredLocation')?.value,
	serviceName:formData1.find(item => item.name === 'serviceName')?.value,
	serviceAmount:formData1.find(item => item.name === 'serviceAmountBox')?.value,
	serviceDate:formData1.find(item => item.name === 'serviceDate')?.value,
	serviceTime:formData1.find(item => item.name === 'serviceTime')?.value,
	priestName:formData1.find(item => item.name === 'priestName')?.value,
	selectVenue:formData1.find(item => item.name === 'selectVenue')?.value,
	serviceAddress:formData1.find(item => item.name === 'serviceAddress')?.value,
	addtionalInfo:formData1.find(item => item.name === 'addtionalInfo')?.value
};*/

	/*const SubmitformData = {
		fname:$("#fname").val(),
		lname:$("#lname").val(),
		email:$("#email").val(),
		phone:$("#phone").val(),
		gotra:$("#gotra").val(),
		stars:$("#stars").val(),
		rashi:$("#rashi").val(),
		streetAddress:$("#streetAddress").val(),
		preferredLocation:$("#preferredLocation").val(),
		serviceName:$("#serviceName").val(),
		serviceAmount:$("#serviceAmountBox").val(),
		serviceDate:$("#serviceDate").val(),
		serviceTime:$("#serviceTime").val(),
		priestName:$("#priestName").val(),
		selectVenue:$("#selectVenue").val(),
		serviceAddress:$("#serviceAddress").val(),
		addtionalInfo:$("#addtionalInfo").val()
	};*/
</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) { ?>

	<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> -->



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

			const formAction = "<?= $formAction ?>";
			console.log("formAction");
			console.log(formAction);

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

			const SubmitformData = {
				fname: formData1.find(item => item.name === 'fname')?.value,
				lname: formData1.find(item => item.name === 'lname')?.value,
				email: formData1.find(item => item.name === 'email')?.value,
				phone: formData1.find(item => item.name === 'phoneNumber')?.value,
				gotra: formData1.find(item => item.name === 'gotra')?.value,
				stars: formData1.find(item => item.name === 'stars')?.value,
				rashi: formData1.find(item => item.name === 'rashi')?.value,
				address_line1: formData1.find(item => item.name === 'address_line1')?.value,
				address_line2: formData1.find(item => item.name === 'address_line2')?.value,
				cityTypes: formData1.find(item => item.name === 'cityTypes')?.value,
				county: formData1.find(item => item.name === 'county')?.value,
				stateTypes: formData1.find(item => item.name === 'stateTypes')?.value,
				zip: formData1.find(item => item.name === 'zip')?.value,
				streetAddress: formData1.find(item => item.name === 'streetAddress')?.value,
				preferredLocation: formData1.find(item => item.name === 'preferredLocation')?.value,
				serviceName: formData1.find(item => item.name === 'serviceName')?.value,
				serviceDate: formData1.find(item => item.name === 'serviceDate')?.value,
				serviceTime: formData1.find(item => item.name === 'serviceTime')?.value,
				priestName: formData1.find(item => item.name === 'priestName')?.value,
				priestPhone: formData1.find(item => item.name === 'priestPhone')?.value,
				priestId: formData1.find(item => item.name === 'priestId')?.value,
				priestEmail: formData1.find(item => item.name === 'priestEmail')?.value,
				selectVenue: formData1.find(item => item.name === 'selectVenue')?.value,
				serviceAddress: formData1.find(item => item.name === 'serviceAddress')?.value,
				serviceType: formData1.find(item => item.name === 'serviceType')?.value,
				serviceAmount: formData1.find(item => item.name === 'serviceAmount')?.value,
				serviceId: formData1.find(item => item.name === 'serviceId')?.value,
				serviceId: formData1.find(item => item.name === 'serviceId')?.value,
				addtionalInfo: formData1.find(item => item.name === 'addtionalInfo')?.value,
				formAction: formAction
			};


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

				console.log(result);


				var totalPriceText = $("#serviceAmountBox").val();
				var mpi_zipcode = $("#mpi_zipcode").val();
				var mpi_fname = $("#mpi_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') {

					var cart_data = SubmitformData;


					console.log("cart_data");
					console.log(cart_data);
					$.ajax({
						url: "<?= $MpiPayUrl ?>",
						type: "POST",
						dataType: "json",
						data: {
							'token': result.token,
							'totolAmt': totolAmt,
							'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;



							var cart_data = SubmitformData;


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

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

										'status': status,
										'paymentSource': paymentSource,
										'paymentStatus': status,
										'transactionId': trnxId,
										'totalPrice': totalPrice,
										fname: formData1.find(item => item.name === 'fname')?.value,
										lname: formData1.find(item => item.name === 'lname')?.value,
										email: formData1.find(item => item.name === 'email')?.value,
										phone: formData1.find(item => item.name === 'phoneNumber')?.value,
										gotra: formData1.find(item => item.name === 'gotra')?.value,
										stars: formData1.find(item => item.name === 'stars')?.value,
										rashi: formData1.find(item => item.name === 'rashi')?.value,
										address_line1: formData1.find(item => item.name === 'address_line1')?.value,
										address_line2: formData1.find(item => item.name === 'address_line2')?.value,
										cityTypes: formData1.find(item => item.name === 'cityTypes')?.value,
										county: formData1.find(item => item.name === 'county')?.value,
										stateTypes: formData1.find(item => item.name === 'stateTypes')?.value,
										zip: formData1.find(item => item.name === 'zip')?.value,
										streetAddress: formData1.find(item => item.name === 'streetAddress')?.value,
										preferredLocation: formData1.find(item => item.name === 'preferredLocation')?.value,
										serviceName: formData1.find(item => item.name === 'serviceName')?.value,
										serviceDate: formData1.find(item => item.name === 'serviceDate')?.value,
										serviceTime: formData1.find(item => item.name === 'serviceTime')?.value,
										priestName: formData1.find(item => item.name === 'priestName')?.value,
										priestPhone: formData1.find(item => item.name === 'priestPhone')?.value,
										priestId: formData1.find(item => item.name === 'priestId')?.value,
										priestEmail: formData1.find(item => item.name === 'priestEmail')?.value,
										selectVenue: formData1.find(item => item.name === 'selectVenue')?.value,
										serviceAddress: formData1.find(item => item.name === 'serviceAddress')?.value,
										serviceAddress: formData1.find(item => item.name === 'serviceAddress')?.value,
										serviceType: formData1.find(item => item.name === 'serviceType')?.value,
										serviceAmount: formData1.find(item => item.name === 'serviceAmount')?.value,
										serviceId: formData1.find(item => item.name === 'serviceId')?.value,
										addtionalInfo: formData1.find(item => item.name === 'addtionalInfo')?.value,
										formAction: formAction
									},
									success: function(addtocart_response) {

										console.log(mpicardpayment_response);

										if (addtocart_response.statusCode == 1) {


											Swal.fire({
												icon: "success",
												title: "Service Booking Confirmed!",
												html: `<span style='font-weight: 600; display: inline-block; font-size: 22px !important; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;'>Receipt #: ${addtocart_response.requestNo}</span>`,
												confirmButtonText: 'OK',
												confirmButtonColor: 'var(--main-color-new-theme)',
												customClass: {
													popup: 'no-scroll-alert'
												}
											}).then(() => {
												window.location.href = "<?= base_url() . 'services' ?>";
											});


											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.fire({
									icon: "error",
									title: mpicardpayment_response.message,
									html: "",
									confirmButtonText: 'OK',
									confirmButtonColor: 'var(--main-color-new-theme)',
								}).then(() => {
									// window.location.href = "<?= base_url() . 'services' ?>";
								});


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