<?php $this->load->view('includes/head') ?>
<?php $this->load->view('includes/topbar') ?>
<?php $this->load->view('includes/header') ?>
<style>
    .card-title {
        font-size: 1.5rem !important;
        margin-bottom: 0.25rem !important;
        line-height: 1 !important;
    }

    .card-text {
        font-size: 1rem !important;
        font-weight: bolder !important;
    }

    h4,
    .h4 {
        font-size: calc(.7rem + 0.3vw) !important;
        font-weight: 900 !important;
    }

    .btn-toggle {
        display: inline-block;
        padding: 8px 16px;
        background-color: #dc3545;
        /* Bootstrap red */
        color: #fff;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }

    input[type="checkbox"]:checked+label.btn-toggle {
        background-color: #28a745;
        /* Bootstrap green */
    }

    .btn-toggle i {
        margin-right: 5px;
    }

    .body,
    p,
    label,
    span {
        font-family: sans-serif !important;
        /* color: black !important; */
    }

    .mdtp__time_holder span,
    .mdtp__digit.active span,
    .mdtp__am.active,
    .mdtp__pm.active {
        color: white !important;
    }

    label {
        font-weight: 600 !important;
        font-size: 16px;
    }

    h4 {
        font-family: sans-serif !important;
        font-weight: 700 !important;
        color: black !important;
        font-size: 16px !important;
    }

    .form-control {
        border: 1px solid #80808045 !important;
    }

    .hidden-div {
        display: none;
    }

    .form-control:disabled,
    .form-control[readonly] {
        background-color: #dbdbdb !important;
        opacity: 1;
    }

    .btn-toggle {
        font-weight: 600 !important;
        font-size: 14px;
        color: white !important;
    }

    .card-title {
        font-family: sans-serif !important;
    }
</style>
<style>
    @media only screen and (max-width:768px) {


        .img-div {
            width: 30% !important;
        }

        .details-div {
            width: 70% !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') ?>">

<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>
<?php
$currencySymbol = getCurrencySymbol();
$session_data = $this->session->userdata('prasadam_cart') ?? [];
if (!isset($session_data['ids'])) {
	$session_data['ids'] = [];
}
$addressLine1 = @$userDetails->addressLine1;
$addressLine2 = @$userDetails->addressLine2;
$cityTypes = @$userDetails->cityTypes;
$county = @$userDetails->county;
$stateTypes = @$userDetails->stateTypes;
$zip = @$userDetails->zip;
// var_dump($userDetails);
?>
<div class="container-fluid">

	<div class="row">


		<div class="col-sm-12 mt-3">

			<div class="header-body mt-4">
				<?php
				if ($this->uri->segment('2') == 'checkout_prasadam') {
				?>
					<form action="<?= base_url('Prasadam/AddToCart') ?>" id="addForm" method="post">
						<div class="row">
							<div class="col-sm-8">
								<div class="card">

									<div class="row" style="margin-right: 0px!important;margin-left: 0px!important;">
										<div class="col-sm-12 pt-3 pb-3">
											<h4>Checkout</h4>
											<hr>
											<div class="row">
												<div class="col-sm-6">
													<p><i class="fa fa-user"></i> Anshika Chaurasiya</p>
													<p><i class="fa fa-envelope" aria-hidden="true"></i> anshikachaurasiya2002@gmail.com</p>
													<p><i class="fa fa-mobile" aria-hidden="true"></i> 7394023581</p>
													<p><i class="fa fa-phone" aria-hidden="true"></i> 7394023582</p>
												</div>
												<div class="col-sm-3">
													<h3 class="text-danger" style="font-size: 17px;">Home Address</h3>
													<p>Test</p>
													<p>Test</p>
													<p>Test</p>
												</div>
												<div class="col-sm-3">
													<h3 class="text-danger" style="font-size: 17px;">Billing Address</h3>
													<p>Test</p>
													<p>Test</p>
													<p>Test</p>
												</div>
											</div>
											<hr>


											<div class="row">
												<div class="col-sm-12">
													<div class="mb-3 mt-3">
														<label for="delivery">Pickup/Delivery:</label>
														<input type="radio" class="form-radio" name="delivery" value="Carry Out" required> <span>Carry Out</span>&nbsp;
														<input type="radio" class="form-radio" name="delivery" value="Delivery" required> <span>Delivery</span>
													</div>
												</div>
												<div class="col-sm-6">

													<label for="deliveryDate">Pickup/Delivery Date <span class="text-danger">*</span> </label>
													<input type="text" class="form-control datepicker" readonly id="deliveryDate" placeholder="Pickup Date" name="deliveryDate" required>

												</div>
												<div class="col-sm-6">

													<label for="deliveryTime">Pickup/Delivery Time <span class="text-danger">*</span></label>
													<input type="text" class="form-control" id="deliveryTime" placeholder="Pickup Time" name="deliveryTime" required>

												</div>
												<div class="col-sm-12 hidden-div">
													<div class="mb-3 mt-3">
														<label for="Copyhomeadd">Copy Home address from Delivery:</label>
														<input type="radio" class="form-radio" name="Copyhomeadd" value="Yes"> <span>Yes</span>&nbsp;
														<input type="radio" class="form-radio" name="Copyhomeadd" value="No"> <span>No</span>
													</div>
												</div>

												<div class="col-sm-6 hidden-div">

													<label for="address">Address <span class="text-danger">*</span> </label>
													<input type="text" class="form-control" id="address" placeholder="Address" name="address">

												</div>
												<div class="col-sm-6 hidden-div">

													<label for="city">City <span class="text-danger">*</span></label>
													<input type="text" class="form-control" id="city" placeholder="City" name="City">

												</div>

												<div class="col-sm-6 mt-2 hidden-div">

													<label for="state">State <span class="text-danger">*</span> </label>
													<input type="text" class="form-control" id="state" placeholder="State" name="state">

												</div>
												<div class="col-sm-6 mt-2 hidden-div">

													<label for="zipcode">Zip Code <span class="text-danger">*</span></label>
													<input type="text" class="form-control" id="zipcode" placeholder="Zipcode" name="zipcode">

												</div>
												<div class="col-sm-12 mt-3 text-center">
													<button type="submit" class="btn btn-danger">Send Request</button>
												</div>
											</div>



										</div>

									</div>

								</div>
							</div>
							<div class="col-sm-4">
								<div class="card">

									<div class="row" style="margin-right: 0px!important;margin-left: 0px!important;background:#e3e3e3!important;">
										<div class="col-sm-12 pt-3 pb-3" style="background:#e3e3e3!important;">
											<h4>Order Summary</h4>
											<hr>
										</div>
										<?php
										$TotalAmt = 0;
										if (!empty($session_data['ids'])) {
											foreach ($session_data['ids'] as $i => $id) {
												$TotalAmt += (float)@$session_data['serviceAmount'][$i];
										?>
												<div class="col-sm-12 col-md-12 col-xl-12 col-lg-12 mb-3 px-1">
													<div class="card">
														<div class="row">
															<div class="col-md-4 d-flex justify-content-center align-items-center img-div">
																<img src="<?= ApiBaseUrl()['url'] . $session_data['image'][$i] ?>" class="img-fluid rounded-start" alt="<?= $session_data['serviceName'][$i] ?>" style="max-width: 70%!important;">
															</div>
															<div class="col-md-8 details-div">
																<div class="card-body">
																	<h5 class="card-title"><?= $session_data['serviceName'][$i] ?></h5>
																	<p class="card-text"><b>Unit Price : <?= $currencySymbol . $currencySymbol . price_format(@$session_data['serviceAmount'][$i], 2)  ?></b></p>

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

										<?php
											}
										}
										?>
										<div class="col-sm-12 pt-3 pb-3" style="background:#ffffff!important;">
											<div class="mb-2">
												<label for="etKitchenTIp">Kitchen Tip</label>
												<input type="text" class="form-control" name="etKitchenTIp" placeholder="Kitchen Tip" id="etKitchenTIp">
											</div>

											<input type="hidden" name="totalPrice" id="totalPrice" value="<?= $TotalAmt ?>">
											<h4 id="totalPriceH">Total: <?= $currencySymbol . price_format($TotalAmt, 2)  ?></h4>

											<a href="<?= base_url('admin/prasadam') ?>" type="button" class="btn btn-danger loader"> Review Cart</a>
										</div>
									</div>
								</div>
							</div>

						</div>
					</form>
				<?php
				} else {
				?>

					<div class="row">
						<div class="col-sm-8">
							<div class="card">

								<div class="row" style="margin-right: 0px!important;margin-left: 0px!important;background:#e3e3e3!important;">
									<div class="col-sm-12 pt-3 pb-3" style="background:#e3e3e3!important;">
										<h4>Prasadam Listing</h4>
										<hr>
										<div class="row">
											<div class="col-sm-6">
												<select class="form-control">
													<option value="" selected disabled>Select Category</option>
													<option value="">test</option>
													<option value="">test</option>
													<option value="">test</option>
													<option value="">test</option>
													<option value="">test</option>
													<option value="">test</option>
												</select>
											</div>
											<div class="col-sm-6">
												<input type="text" id="searchByName" class="form-control" placeholder="Name">
											</div>
										</div>
									</div>
									<?php

									foreach ($dailyMenu as $item) {
									?>
										<div class="col-sm-6 col-md-6 col-xl-6 col-lg-6 mb-3 px-1 prasadam-card" data-name="<?= strtolower($item->refDataName) ?>">
											<div class="card">
												<div class="row">
													<div class="col-md-4 d-flex justify-content-center align-items-center img-div">
														<img src="<?= ApiBaseUrl()['url'] . $item->image ?>" class="img-fluid rounded-start" alt="<?= $item->refDataName ?>" style="max-width: 70%!important;">
													</div>
													<div class="col-md-8 details-div">
														<div class="card-body">
															<h5 class="card-title"><?= $item->refDataName ?></h5>
															<!-- <p class="card-text"><?= $item->description ?></p> -->
															<p class="card-text">Unit Price : <?= $currencySymbol . price_format($item->unitPrice, 2)  ?></p>
															<!-- <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> -->
															<p class="">
																<!-- <button class="btn btn-danger"><i class="fa fa-plus" aria-hidden="true"></i> Add To Cart</button> -->
																<!-- Hidden checkbox -->
																<input type="checkbox" id="checkbox_<?= $item->_id ?>" <?= ((in_array($item->_id, $session_data['ids'])) ? 'checked' : '') ?> style="display: none;" value="<?= $item->_id ?>" data-id="<?= $item->_id ?>" data-category="<?= @$item->rentalCategory ?>" data-service-type="<?= $item->refDataCode ?>" data-start-time="<?= @$item->startTime ?>" data-start-date="<?= @$item->startDate ?>" data-service-name="<?= $item->refDataName ?>" data-price="<?= ((in_array($item->_id, $session_data['ids'])) ?  ($session_data['serviceAmount'][array_search($item->_id, $session_data['ids'])])  :  @$item->unitPrice) ?>" data-end-date="<?= @$item->endDate ?>" data-end-time="<?= @$item->endTime ?>" data-description="<?= replaceSingleQuotesWithBackticks(@$item->shortDescription) ?>" data-image="<?= @$item->image ?>" data-BookingLimitPerDay="<?= @$BookingLimitPerDay ?>" onchange="addTocart()" name="services_id[]" available_count="<?= @$item->AvailableCount ?>" data-servicedesc="<?= (in_array($item->_id, $session_data['ids']) ?   @$session_data['service_desc'][array_search($item->_id, $session_data['ids'])]  :  '') ?>" is_membership_discount="<?= @$item->membershipDiscount ?>" membership_discount_amt="<?= @$item->membershipAmount ?>" />

																<!-- Label styled as button -->
																<label for="checkbox_<?= $item->_id ?>" class="btn-toggle">
																	<i class="fa fa-plus" aria-hidden="true"></i> Add To Cart
																</label>
															</p>
														</div>
													</div>
												</div>
											</div>
										</div>

									<?php
									}
									?>
								</div>

							</div>
						</div>
						<div class="col-sm-4">
							<div class="card">

								<div class="row  pt-3 pb-3" style="margin-right: 0px!important;margin-left: 0px!important;background:#e3e3e3!important;" id="cart-preview-section">

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

					</div>
				<?php
				}
				?>
			</div>


		</div>

	</div>
</div>
<!-- End Main content-->
</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 $this->load->view('includes/script') ?>

<script>
	var addressLine1 = '<?= $addressLine1 ?>';
	var addressLine2 = '<?= $addressLine2 ?>';
	var address = addressLine1 + ', ' + addressLine2;
	var cityTypes = '<?= $cityTypes ?>';
	var county = '<?= $county ?>';
	var stateTypes = '<?= $stateTypes ?>';
	var zip = '<?= $zip ?>';

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

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

				}




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


				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);
			}
			$(".allPrice").text((totalPrice / 1).toFixed(2));
		}

		$.ajax({
			type: "POST",
			url: "<?= base_url('Prasadam/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();
				reloadCartPreview();
				// 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 reloadCartPreview() {
		$.ajax({
			url: '<?= base_url('Prasadam/getTempCart') ?>',
			type: 'GET',
			success: function(response) {
				$('#cart-preview-section').html(response);
			}
		});
	}
	reloadCartPreview();
	$(document).on('click', '.service-delete-row', function(e) {
		e.preventDefault();

		var row_id = $(this).data('row-id');
		var selected_date = $(this).data('selected-date');
		var current_row = $(this).closest('tr');
		var confirmDelete = confirm('Do you want to delete this service from your cart?');

		if (confirmDelete) {
			loader.on();
			$.ajax({
				url: '<?= base_url() ?>Prasadam/delete_cart_row',
				method: 'POST',
				data: {
					row_id: row_id,
					selected_date: selected_date
				},
				dataType: 'json',
				success: function(response) {
					if (response.status == 'success') {
						// remove the deleted row from the DOM
						current_row.remove();
						// update the cart amount
						// var updated_amount = response.updated_amount;
						// $('#cart-amount').text(updated_amount);
						location.reload();
						// loader.off();
					}
				},
				error: function() {
					loader.off();
					alert('Error deleting cart row. Please try again.');
				}
			});
		}
	});

	$(document).ready(function() {
		$('input[name="delivery"]').on('change', function() {
			console.log("etKitchenTIp");
			if ($(this).val() === 'Delivery') {
				$('.hidden-div').css("display", "block");
			} else {
				$('.hidden-div').css("display", "none");
			}
		});

		$('input[name="Copyhomeadd"]').on('change', function() {
			if ($(this).val() === 'Yes') {
				$("#address").val(address);
				$("#address").attr("readonly", true);
				$("#state").removeAttr("required");

				$("#city").val(cityTypes);
				$("#city").attr("readonly", true);
				$("#state").removeAttr("readonly");

				$("#state").val(stateTypes);
				$("#state").attr("readonly", true);
				$("#state").removeAttr("required");

				$("#zipcode").val(zip);
				$("#zipcode").attr("readonly", true);
				$("#state").removeAttr("required");
			} else {
				$("#address").val('');
				$("#address").attr("required", true);
				$("#address").removeAttr("readonly");

				$("#city").val('');
				$("#city").attr("required", true);
				$("#city").removeAttr("readonly");

				$("#state").val('');
				$("#state").attr("required", true);
				$("#state").removeAttr("readonly");

				$("#zipcode").val('');
				$("#zipcode").attr("required", true);
				$("#zipcode").removeAttr("readonly");
			}
		});
	});

	$(document).ready(function() {
		$('#searchByName').on('keyup', function() {
			var input = $(this).val().toLowerCase();

			$('.prasadam-card').each(function() {
				var name = $(this).data('name');

				if (name.includes(input)) {
					$(this).show();
				} else {
					$(this).hide();
				}
			});
		});
	});

	function ValidateCheckout() {
		loader.on();
		$.ajax({
			url: '<?= base_url('validate_prasadam_checkout') ?>', // PHP file that checks profile
			method: 'POST',
			dataType: 'json',
			success: function(response) {
				if (!response) {
					loader.off();
					Swal.fire({
						title: "Oops",
						text: "Minimum order value must be $10!",
						icon: "question"
					});
				} else {
					window.location.href = "<?= base_url('admin/checkout_prasadam') ?>";
				}
			}
		});
	}
</script>
<script>
	$(document).ready(function() {
		let baseTotal = parseFloat($('#totalPrice').val()) || 0;

		// Only allow numbers and one decimal point during input
		$('#etKitchenTIp').on('input', function() {
			this.value = this.value
				.replace(/[^0-9.]/g, '') // Remove non-numeric and non-dot
				.replace(/^(\d*\.?\d{0,2}).*$/, '$1'); // Limit to 2 decimal places
		});

		// Format to 2 decimals and update total when user leaves the field
		$('#etKitchenTIp').on('blur', function() {
			let tip = parseFloat(this.value) || 0;
			this.value = tip.toFixed(2); // Format tip to 2 decimals

			let newTotal = baseTotal + tip;

			$('#totalPrice').val(newTotal.toFixed(2)); // hidden input
			$('#totalPriceH').text('Total: ₹' + newTotal.toFixed(2)); // visible text
		});
		$(".datepicker").datepicker({
			dateFormat: 'mm/dd/yy', // Month/Day format
			changeMonth: true,
			changeYear: true, // Disable year change
			showButtonPanel: true,
			minDate: 0,

		});
		$('#deliveryTime').mdtimepicker();

		$('#addForm').on('submit', function(e) {
			e.preventDefault(); // Stop default form submit

			let isValid = true;

			// Clear previous error borders
			$('#addForm input').removeClass('is-invalid');

			// Check if any required input is empty
			$('#addForm [required]').each(function() {
				if (!$(this).val()) {
					$(this).addClass('is-invalid');
					isValid = false;
				}
			});

			if (isValid) {
				// If all validation passes, submit the form (either via AJAX or normal submit)
				this.submit(); // Or handle AJAX here
			} else {
				alert("Please fill all required fields.");
			}
		});

	});
</script>
