<?php $this->load->view('includes/head') ?>
<?php $this->load->view('includes/topbar') ?>
<?php $this->load->view('includes/header') ?>
<!-- light box -->
<link href="<?=base_url('assets/css/lightbox.min.css');?>" rel="stylesheet" />
<script src="<?=base_url('assets/js/lightbox-plus-jquery.min.js');?>"></script> 
<script type="text/javascript" src="<?=base_url('admin_assets/js/sweetalert2.all.min.js')?>"></script>
<link href="<?=base_url('admin_assets/css/sweetalert2.min.css')?>" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="<?=base_url('assets/css/services-cart.css')?>">
<main id="main">
	<!-- ======= Coming Soon ======= -->

	<section class="temple-services" style="background-image: url(<?=base_url('assets/img/elegant-background-with-mandala.png');?>);background-size: auto;">

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

		<div class="row mb-0 pb-0" style="padding: 0px 50px;">
			
			<center class="mb-3">
				<h2 class="text-center mb-0" style="font-weight:bold!important;font-size: 30px!important;text-shadow: 1px 1px 5px #FA9D1E;"><?=camelCase($sponsorType_details[0]['displayName']);?></h2>
				<img src="<?=base_url('assets/img/border.png')?>" width="20%" alt="<?=$sponsorType_details[0]['displayName']?>">
			</center>
			
			<div class="col-md-6 mb-0 pb-0 aos-init aos-animate" data-aos="fade-right">
				<div style="height:422px;width: 100%;display: flex; justify-content: center; align-items: center;">
					<img src="<?=ApiBaseUrl()['url'].$sponsorType_details[0]['image']?>" class="img-fluid rounded shadow" style="width: 100%; height:auto;max-width: 100%;max-height: 100%;">
				</div>
			</div>

			<div class="text-center mb-0 pb-0 col-md-6 aos-init aos-animate" data-aos="fade-left">

				<p class="text-start">
					<?=$sponsorType_details[0]['description']?>
				</p>

			</div>
		</div>

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


		<?php 
		$cartList = $this->session->userdata('sponsorship_cart');
		// echo '<pre>'; print_r($cartList);

		$cart_count = isset($cartList['ids']) && $cartList['ids'] ? count($cartList['ids']) : 0;
		$cart_count = $cart_count != '' ? $cart_count : 0;
		if(empty($cartList['ids'])) {
			$cartList = array('totalPrice' => 0.00, 'ids' => array());
		}
		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;
			}
		}

		$currencySymbol = getCurrencySymbol();
		$GeneralSettings = GeneralSettings();

		?>

		<div class="bg-image shadow-1-strong mt-5" >
			<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;">SPONSOR NOW </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('sponsorships')">

																<?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('sponsorships')">

																<?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('sponsorships')">
																<?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 px-2" style="overflow:hidden">

									<div id="Abc">

										<div  class="tab-content mt-4 table-responsive" id="myTabContent">
											<?php
											echo getSponsorTypesServicesByServiceType($serviceType,$cartList);
											?>
											<div id="emptyServices" style="padding: 4px 66px; font-size: 21px; font-weight: 700;">

											</div>
										</div>

									</div>


								</div> 

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

			</section>



		</main>

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

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

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

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

			$(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("Sponsorship 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('SponsorNow/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('SponsorNow/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="sponsorships_id[]"]:checked').each(function() {
					$("input[name='sponsorships_id[]']").prop('checked', false);
				});

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

			}

			function addTocart()
			{

				var totalPrice = 0;
				var cart_type = 'SPONSORSHIP';
				var ids = [];
				var qty = [];
				var ctg = [];
				var serviceTypes = [];
				var serviceName = [];
				var startDate = [];
				var startTime = [];
				var serviceAmount = [];
				var description = [];
				var image = [];
				var cart_ctg = [];
				var is_date_required = [];


				var noDateSelected = 0;
				var addtoCartStatus = true;
				var service_desc = [];


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

					loader.on();





					// else 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());


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


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

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

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


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

						$("#Totalprice_"+$(this).attr('data-id')).html("<?= $currencySymbol; ?>&nbsp;"+((parseFloat($(this).attr('data-price'))*init_qty)*nDateSelectCount)+".00");
					}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)+".00");
						startDate.push('');

					}
					




					startTime.push($("#timepicker_"+id).val()); 




					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')); 
					cart_ctg.push($(this).attr('cart_category')); 
					serviceAmount.push($(this).attr('data-price')); 
					ids.push($(this).attr('data-id')); 
					qty.push(init_qty); 
					service_desc.push($(this).attr('data-servicedesc'));
					is_date_required.push($(this).attr('is_date_required')); 

				});


				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('SponsorNow/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, is_date_required: is_date_required,service_desc : service_desc}, 
					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);
				}

				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('SponsorNow/ViewCart')?>";

				}else{
					swal({
						title: "Your cart is empty!",
						text: "Please add some items to your cart.",
						icon: "warning",
						confirmButtonText: 'OK',
						confirmButtonColor: '#005D4B',
					});


				}

			}

			function CartCheckLogin(page){

				if ($(".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{

								window.location.href = "<?=base_url('checkout/sponsorship')?>";

							}

						}
					});

				}else{
					swal({
						title: "Your cart is empty!",
						text: "Please add some items to your cart.",
						icon: "warning",
						confirmButtonText: 'OK',
						confirmButtonColor: '#005D4B',
					});


				}
			}



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


		</script>


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