<?php $this->load->view('includes/head') ?>
<?php $this->load->view('includes/topbar') ?>
<?php $this->load->view('includes/header') ?>

<link rel="stylesheet" type="text/css" href="<?=base_url('assets/css/services-cart.css')?>">
<main id="main">
	<?php 
	$serviceDisplayGroup = $this->input->get('DisplayGroup');
	$deityName =  $this->input->get('deityName');

	$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
	{
		$cartDetelists = array();
		$cartDetelistsCount = 0;

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




		$cart_count = $cartDetelistsCount;
	}


	$currencySymbol = getCurrencySymbol();
	$GeneralSettings = GeneralSettings();
	?>
	<!-- ======= Coming Soon ======= -->
	<section id="temple-services" class="temple-services" style="background-image: url(<?=base_url('assets/img/elegant-background-with-mandala.png');?>);background-size: auto;">
		<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="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="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 class="px-2">
													<input type="search" name="q" id="search" class="search-text searchKey" placeholder="Search..." autocomplete="off" style="margin-left: 10px;     width: 400px;height: 56px;">
												</div> -->
											</div>
										</div> 
									</div>

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

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

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



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

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

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

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

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

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

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


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

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

								<div style="padding: 0px 50px;">
									<?php  
									$serivce_Types = getServiceTypesByDisplayGroupAndDeityName($serviceDisplayGroup);
									?>
									<!-- @@@@@@@@@@@@@@@@@@@@@@ Service Types @@@@@@@@@@@@@@@@@@@@@@@@@ -->

									<ul class="nav nav-tabs">

										<style type="text/css">
											.nav-link2.active {
												color: #fff!important;
												background: var(--main-color-new-theme)!important;
												border: 2px solid #f7c01b!Important;
												border-color: #f7c01b!Important;
												font-weight: 500;
											}
											.nav-link2 {
												padding: 8px 10px!important;
												font-size: 20px!important;
												color: #000!important;
												border-radius: 5px!important;
												font-weight: 500;
												margin-bottom: 18px!important;
												background: #c5c5c5!important;
												margin-right: 9px!important;

												font-family: system-ui!important;
											}
											.nav-tabs {
												--bs-nav-tabs-border-width: 0; 
												--bs-nav-tabs-border-radius: 0;  
											}

										</style>
										<?php  if(!empty($serivce_Types)){ foreach ($serivce_Types as $key => $val) { ?>


											<li class="nav-item mt-3">
												<button class="nav-link nav-link2 <?= ($key==0)?'serviceTypes1 active':''; ?>" 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"><?= (@$val['displayName'] ? @$val['displayName'] : $val['refDataName']); ?></button>
											</li>

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

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


											<div class="tab-pane table-responsive fade shadow panettttttttt<?= $val['_id']; ?> show <?= ($key==0)?'active':''; ?>" id="home-tab-pane<?= $val['_id']; ?>" role="tabpanel" aria-labelledby="home-tab<?= $val['_id']; ?>" tabindex="0">
												<?php
												$services = FilterServicesByDisplayGroupAndDeityName($val['refDataName'], $deityName, $cartList);
												echo $services;
												?>
											</div>
											<div id="emptyServices" style="padding: 4px 66px; font-size: 21px; font-weight: 700;"></div>
										<?php }} ?> 
									</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;">Service Availability List</h5>

													<button type="button" class="btn-close m-0" data-bs-dismiss="modal" aria-label="Close"></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>



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


	</main><!-- End #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>


	<script type="text/javascript">


		$(document).ready(function() {

			$("#search").on("keyup", function() {
				var value = $(this).val().toLowerCase();
				var $tableRows = $("#table tr");
				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("No service found!").show();
				} else {
					$("#emptyServices").hide();
				}
			}).on("search", function() {
				if ($(this).val() === "") {
					$("#table tr").show();
					$("#emptyServices").hide();
				}
			});
			var Page_limit = $("#pageLength").val();
			if (Page_limit > 20) {
				$('.servicesDataTable').paging({limit:Page_limit});
			}
			$("[data-page='0']").click();

			$('.timepicker-services').mdtimepicker();
		});




		var tithiDates = []; 

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

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

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

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



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


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

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


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

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

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

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




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



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

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

				}
			});

		});


		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 includeSankalpam = [];
			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 payment_btn_check = [];


			var noDateSelected = 0;
			var addtoCartStatus = true;

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


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


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

				loader.on();

			

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

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

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

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


				var init_qty = parseInt($("#quantity-input"+id).val());
				startDate.push($("#datepicker_"+id).val()); 
				startTime.push($("#timepicker_"+id).val()); 

				var dateArray = startDate[0].split(', ');
				var count    = dateArray.length;

				var nDateSelectCount = ($("#datepicker_"+id).val()).split(', ');
				nDateSelectCount     = nDateSelectCount.length;

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


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



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

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


				var payment_type_check =  '';

				if ($(this).attr('payment-btn-check') == 'PAY NOW') {
					payment_type_check = 'PAY-NOW';
				}else if($(this).attr('payment-btn-check') == 'PAY LATER'){
					payment_type_check = 'PAY-LATER';
				}else if($(this).attr('payment-btn-check') == 'SERVICE REQUEST'){
					payment_type_check = 'SERVICE-REQUEST';
				}


				payment_btn_check.push(payment_type_check); 
				description.push($(this).attr('data-description').replace(/['"`]/g, '')); 
				cart_ctg.push($(this).attr('cart_category')); 
				serviceAmount.push($(this).attr('data-price')); 
				ids.push($(this).attr('data-id')); 
				includeSankalpam.push($(this).attr('includeSankalpam'));
				qty.push(init_qty); 

			});


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

			$.ajax({
				type: "POST", 
				url: "<?= base_url('Services/addCart'); ?>", 
				data: {ids: ids, totalPrice:totalPrice, qty: qty, ctg: ctg, serviceTypes: serviceTypes, serviceName: serviceName, startDate: startDate, startTime: startTime, serviceAmount: serviceAmount, cart_type: cart_type, image: image, description: description, cart_ctg: cart_ctg, payment_btn_check: payment_btn_check, includeSankalpam: includeSankalpam}, 
				success: function(result){
					console.log(result);
					 $("#includeSankalpamModal").val(result.includeSankalpam);
					loader.off();
				}});


		}


		function PaymentAddTocart()
		{

			var totalPrice = 0;
			var cart_type = 'PAYMENTS';
			var ids = [];
			var qty = [];
			var ctg = [];
			var serviceTypes = [];
			var serviceName = [];
			var serviceAmount = [];
			var description = [];
			var image = [];
			var cart_ctg = [];
			$('input[name="services_id[]"]:checked').each(function() {
				id = $(this).attr('data-id');
				loader.on();

				if ($(this).attr('data-price') != 0) {
					var init_qty = parseInt($("#quantity-input"+id).val());
					init_qty = init_qty?parseInt(init_qty):1;
					totalPrice = parseFloat(totalPrice)+(parseFloat($(this).attr('data-price'))*init_qty);
				}else{
					totalPrice = $("#Totalprice_"+id).val().replace(/\D/g, '');
				}


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

				description.push($(this).attr('data-description').replace(/['"`]/g, '')); 
				cart_ctg.push($(this).attr('cart_category')); 
				serviceAmount.push($(this).attr('data-price')); 
				ids.push($(this).attr('data-id')); 
				qty.push(init_qty); 
			});

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

			$.ajax({
				type: "POST", 
				url: "<?= base_url('MakePayments/addCart'); ?>", 
				data: {ids: ids, totalPrice:totalPrice, qty: qty, ctg: ctg, serviceTypes: serviceTypes, serviceName: serviceName, serviceAmount: serviceAmount, cart_type: cart_type, image: image, description: description, cart_ctg: cart_ctg}, 
				success: function(result){
					console.log(result);
					loader.off();
				}});


		}



		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);
      // $("#Totalprice_"+id).text((parseFloat($("input[value='"+id+"']").attr('data-price'))*init_qty / 1).toFixed(2));
			}

			addTocart();
		}

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


        // check max quantity
			if($("input[data-id='"+id+"']").attr('data-service-type')=='VADAMALA')
			{
				if($('#quantity-input'+id).attr('max'))
				{
					var maxQty = $('#quantity-input'+id).attr('max');
					if(init_qty == maxQty)
					{
						return false;
					}
				}
			}


			init_qty = init_qty?parseInt(init_qty)+1:0;
			$('#quantity-input'+id).val(init_qty);
    // $("#Totalprice_"+id).text((parseFloat($("input[value='"+id+"']").attr('data-price'))*init_qty / 1).toFixed(2));
			addTocart();

		}


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

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


			}

		}

		function CartCheckLogin(page){

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

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

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

							}

						}

					}
				});

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


			}
		}

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


		function 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 BookingLimitPerDay           = $(serviceObject).attr('data-BookingLimitPerDay');


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

					if(data.statusCode)
					{
						$("#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);

		}

	</script>

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