<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, maximum-scale=1, initial-scale=1, user-scalable=0">
    <meta name="keywords" content="">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>myoptician</title>
    <!--Favicon -->
    <link rel="shortcut icon" type="image/png" href="images/favicon-icon.png" />
   
    <!--Main Stylesheet-->
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <link rel="stylesheet" type="text/css" href="css/responsive.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
</head>

<body>
<?php include_once(__DIR__ . '/header.php'); ?>
<form id="main-form" method="POST" action="user-details.php">
	<input type="hidden" id="hidden_optician_id" name="hidden_optician_id" value="<?= isset($optician_id) ? $optician_id : $_GET['OpticianId'] ?>"/>
	<input type="hidden" id="hidden_shop_name" name="hidden_shop_name" value="<?= isset($shops) && count($shops) == 0 ? $shops[0]->getName() :  $_GET['Shop'] ?>"/>
	<input type="hidden" id="hidden_practitioner_name" name="hidden_practitioner_name" value="<?= isset($practitioners) && count($practitioners) == 1 ? $practitioners[0]->getName() : '' ?>"/>
	<input type="hidden" id="hidden_preferred_staff" name="hidden_preferred_staff" value="<?= isset($practitioners) && count($practitioners) == 1 ? 'YES' : 'NO' ?>"/>
	<input type="hidden" id="hidden_appointment_slot" name="hidden_appointment_slot" value=""/>

	<div class="secondp">
		<?php if(isset($practitioners) && count($practitioners) == 1 ) : ?>
			<div class="sitecontainer">
				<!-- <div class="heading">
					<h5></h5>
				</div> -->
			</div>
		<?php else : ?>
			<div class="sitecontainer">
		 	<div class="heading">
		 	  <h5>Do you have a preferred member of staff?</h5>
		 	  <div class="listofmember">
		 	  		<div class="yesno">
			 	  		<div class="btnyes">
				 	  		<input type="radio" id="no" name="selectmember" value="1"  checked="checked">
							<label for="no">No</label>
						</div>
						<div class="btnyes">
							<input type="radio" id="yes" name="selectmember" value="2">
							<label for="yes">Yes</label>
						</div>
					</div>
		 	  </div>
		 	</div>
		 	<div class="heading" id="hideshow2" style="display:none;">
		 	  <h5>Show appointments with:</h5>
		 	  <div class="listofmember person">
		 	  		<div class="yesno grid-layout" id="practitioners_list">
			 	  		<div class="btnyes" style="display:none">
				 	  		<input type="radio" id="practitioner_name_1" name="practitioner_name" value="">
							<label for="practitioner_name_1">name1</label>
						</div>
					</div>
		 	  </div>
		 	</div>
		</div>
		<?php endif ?>
	</div>

	<div class="sedsection">
		<div class="sitecontainer">
		 	<div class="sedsectioninner">
			 	<div class="left">
			 		<div class="heading">
				 	  <h5>Choose a date and time to suit you</h5>
					   <div id="calendar"></div>
				 	</div>
			 	</div>
			 	<div class="right">
			 		<div class="heading">
				 	  <h5>Available times on <span>selected date</span> </h5>
				 	</div>
				 	<div class="timeslote">
				 		<div class="box">
					 		<div class="item" style="display:none">
					 			<a href="#"><p>8:50am</p></a>
					 		</div>
					 	</div>
				 	</div>
			 	</div>		 	  
		 	</div>
		</div>
	</div>
</form>

	<script src="js/jquery.min.js"></script>
	<script src="js/jquery-3.6.4.min.js"></script>
	<!-- JS for jQuery -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<!-- JS for full calender -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
	<script src='js/fullcalendar-6.1.11.global.min.js'></script>
	<script src="js/spin.min.js"></script>
	<script src="js/helper.js"></script>

	<script>
		// Initialize Spin.js with options
		var opts = {
			lines: 13, // The number of lines to draw
			length: 20, // The length of each line
			width: 10, // The line thickness
			radius: 30, // The radius of the inner circle
			scale: 1, // Scales overall size of the spinner
			corners: 1, // Corner roundness (0..1)
			color: '#000', // CSS color or array of colors
			fadeColor: 'transparent', // CSS color or array of colors
			speed: 1, // Rounds per second
			rotate: 0, // The rotation offset
			animation: 'spinner-line-fade-quick', // The CSS animation name for the lines
			direction: 1, // 1: clockwise, -1: counterclockwise
			zIndex: 2e9, // The z-index (defaults to 2000000000)
			className: 'spinner', // The CSS class to assign to the spinner
			top: '50%', // Top position relative to parent
			left: '50%', // Left position relative to parent
			shadow: '0 0 1px transparent', // Box-shadow for the lines
			position: 'absolute' // Element positioning
		};

		// Initialize the spinner
		var spinner;

		// Show the loader
		function showLoader() {
			spinner = new Spinner(opts).spin();
			document.body.appendChild(spinner.el);
		}

		// Hide the loader
		function hideLoader() {
			spinner.stop();
		}
	</script>

	<script>
		var calendar;
		var currentSlots = {};
		$(document).ready(function() {
		    $("input[name$='selectmember']").click(function() {
		        var val = $(this).val();
		        $("#hideshow2").hide();
		        $("#hideshow" + val).show();
				if(val == "2"){
					console.log("clicked on yes");
					$("#hidden_preferred_staff").val("YES");
					getPractitioners(populatePractitioners);
					renderAppointmentSlots(null);
				} else if(val =="1"){
					$("#hidden_preferred_staff").val("NO");
					console.log("clicked on no");
					getAppointmentSlots( null, populateAppointmentSlots);
				}
		    });
		});

		function getPractitioners(callbackFunc) {
			showLoader();
			$.ajax({
				url: 'api/getPractitioners.php', // Replace with your actual backend endpoint
				method: 'GET',
				dataType: 'json',
				data: { OpticianId: opticianId, shop_name: shop },
				
				success: function(data) {
					// Populate the <ul> element with the fetched data
					console.log('practitioner lists:');
					console.log(data);
					callbackFunc(data.data);
					hideLoader();
				},
				error: function(error) {
					console.error('Error fetching shop data:', error);
					hideLoader();
				}
			});
		}

		function getAppointmentSlots(selectedPractitionerName, callbackFunc) {
			renderAppointmentSlots(null);
			showLoader();
			$.ajax({
				url: 'api/getAppointments.php', // Replace with your actual backend endpoint
				method: 'GET',
				dataType: 'json',
				data: { OpticianId: opticianId, shop_name: shop, practitioner_name: selectedPractitionerName},
				
				success: function(data) {
					// Populate the <ul> element with the fetched data
					console.log('appointment slits lists:');
					console.log(data);
					callbackFunc(data.data);
					hideLoader();
				},
				error: function(error) {
					console.error('Error fetching shop data:', error);
					hideLoader();
				}
			});
		}

		function populatePractitioners(practitionerNames){
			const practitioners_list = $("#practitioners_list");
			firstDiv = $("#practitioners_list div:first").clone();
			practitioners_list.empty();
			var count = 0;
			practitionerNames.forEach(function(practitioner) {
				count++;
				var practitionerName = practitioner.name;
				var newDiv = firstDiv.clone();
				newDiv.find("input").attr("id", "practitioner_name_"+count); // Replace "new-link" with the actual link
				newDiv.find("input").attr("value", practitionerName); // Replace "new-link" with the actual link
				newDiv.find("label").attr("for", "practitioner_name_"+count); // Replace "new-link" with the actual link
				newDiv.find("label").text(practitionerName); // Replace "new-link" with the actual link
				practitioners_list.append(newDiv);
				newDiv.show();
				newDiv.find("input").click(function() {
                    // Handle click event for the cloned li
					practitionerName = $(this).val();
					$("#hidden_practitioner_name").val(practitionerName);
					getAppointmentSlots(practitionerName, populateAppointmentSlots);
                });
			});
		} 

		function populateAppointmentSlots(slots){
			slots.forEach(function(slot) {
				var date = slot.date;
				var startTime = slot.start_time;
				var endTime = slot.end_time;
				var slotStr = slot.slot_str;
			});
			currentSlots = {};
			slots.forEach(item => {
				// Split the original date into day, month, and year
				const [day, month, year] = item.date.split('/');
				// Create a new date string in YYYY-MM-DD format
				const dateKey = `${year}-${month}-${day}`;
				if(currentSlots[dateKey] == null || currentSlots[dateKey] == undefined){
					currentSlots[dateKey] = [];
				}
				currentSlots[dateKey].push( {
					date: dateKey,
					start_time: item.start_time,
					end_time: item.end_time,
					slot_str: item.slot_str
				});
			});
			renderCalenderWithEvents();
		}

		function renderCalenderWithEvents(){
			var calenderEvents = [];
			var dates = Object.keys(currentSlots);
			dates.forEach(function(date) {
				// Access each key and its corresponding value
				var slots = currentSlots[date];
				currentSlots[date].forEach(function(slot){
					calenderEvents.push(generateValenderEvent(slot));
				});
			});

			var calendarEl = document.getElementById('calendar');
			calendar = new FullCalendar.Calendar(calendarEl, {
				height:"auto",
				headerToolbar: {
					left: 'prev today',
					center: 'title',
					right: 'next'
				},
				initialView: 'dayGridMonth',
				selectable: true,
				events: calenderEvents,
				dateClick: function(info) {
					renderAppointmentSlots(currentSlots[info.dateStr]);
				},
				
			});
			calendar.render();
		}

		function renderAppointmentSlots(slots){
			const appointmentBox = $(".timeslote div.box");
			firstDiv = $(".timeslote div.box div.item:first").clone();
			appointmentBox.empty();
			if(slots == undefined || slots == null){
				var newDiv = firstDiv.clone();
				newDiv.find("p").text("Please Select Date"); // Replace "new-link" with the actual link
				appointmentBox.append(newDiv);
				newDiv.show();
				// newDiv.hide();
			} else {
				var count = 0;
				slots.forEach(function(slot) {
					count++;
					var slotTime = slot.start_time;
					var newDiv = firstDiv.clone();
					newDiv.find("p").text(slotTime); // Replace "new-link" with the actual link
					appointmentBox.append(newDiv);
					newDiv.find("a").attr("data-slot", slot.slot_str)
					newDiv.show();
					newDiv.find("a").on("click", function(){
						$(this).parent().parent().find("a").each(function(e){$(this).removeClass('active');});
						$(this).addClass("active");
						$("#hidden_appointment_slot").val($(this).attr("data-slot"));
						$("#main-form").submit();
					});
				});
			}
		}

		//creating full calendar
		$(document).ready(function() {
			if($("#hidden_practitioner_name").val() != undefined && $("#hidden_practitioner_name").val().trim().length > 0){
				getAppointmentSlots( $("#hidden_practitioner_name").val().trim(), populateAppointmentSlots);
			} else {
				getAppointmentSlots( null, populateAppointmentSlots);
			}
			
		});

		
	</script>
<?php include_once(__DIR__ . '/footer.php'); ?>
</body>
</html>



