<!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>Have you got a preferred Optician?</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>Preferred Optician/Optometrist:</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 id="practitioner_notes_div" style="display: none; font-size: small; padding-top: 10px; color: blue;">
						<p>Note: <span id="practitioner_notes"></span> </p>
					</div>
					<div id="practitioner_notes_html_div" style="display: none; font-size: small; padding-top: 10px; color: blue;">
						<span id="practitioner_notes_html"></span>
					</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>
		// let eventTriggered = false; // Flag to ensure the action is triggered only once

		function handleClickEvent(event) {
			// Perform your action here
			console.log(`Event triggered: ${event.type}`);
			$('#touch_div').remove();
		}

		// Attach both touchstart and click event listeners to the window
		// window.addEventListener('touchstart', handleClickEvent);
		window.addEventListener('click', handleClickEvent);
		// 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 slots 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 practitionerNotes = practitioner.notes;
				var practitionerNotesHtml = practitioner.base64_decoded_notes;
				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);
				newDiv.find("input").attr("data-notes", practitionerNotes); // Replace "new-link" with the actual link
				newDiv.find("input").attr("data-base64-notes", practitionerNotesHtml);
				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();
					var notes_to_display = $(this).attr('data-notes');
					var html_notes_to_display = $(this).attr('data-base64-notes');
					$("#hidden_practitioner_name").val(practitionerName);
					if(notes_to_display === null || notes_to_display === undefined || notes_to_display === ''){
						$("#practitioner_notes_div").hide();
					}else{
						$("#practitioner_notes_div").show();
						$("#practitioner_notes").html(notes_to_display);
					}

					if(html_notes_to_display === null || html_notes_to_display === undefined || html_notes_to_display === ''){
						$("#practitioner_notes_html_div").hide();
					}else{
						$("#practitioner_notes_html_div").show();
						$("#practitioner_notes_html").html(html_notes_to_display);
					}
					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;
				var name = slot.name;
			});
			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,
					name: item.name
				});
			});
			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]);
					addSelectedDiv(info.jsEvent);
				},
				
			});
			calendar.render();
		}

		function addSelectedDiv(event){
			// var touchdiv = '<div class="fc-daygrid-bg-harness" id="touch_div" style="left: 0px; right: 0px;"><div class="fc-highlight"></div></div>';
			// window.alert(event.srcElement.outerHTML);
			// window.alert(event.srcElement.parentElement.outerHTML);
			// window.alert(event.srcElement.parentElement.parentElement.outerHTML);
			// window.alert( ((event.srcElement.classList.contains('fc-daygrid-day-top') 
			// 			|| event.srcElement.classList.contains('fc-daygrid-day-events') ) && 
			// 		event.srcElement.parentElement.classList.contains('fc-daygrid-day-frame') && 
			// 		event.srcElement.parentElement.parentElement.classList.contains('fc-daygrid-day') &&
			// 		event.srcElement.parentElement.parentElement.tagName == 'TD'));
			// window.alert(event.srcElement.parentElement.parentElement.tagName);

			if( (!event.srcElement.classList.contains('fc-highlight')
				&& event.srcElement.parentElement.parentElement.classList.contains('fc-daygrid-day-bg'))
				){
				const newDiv = document.createElement('div');
				// Set attributes and inner HTML for the div
				newDiv.className = 'fc-daygrid-bg-harness';
				newDiv.id = 'touch_div';
				newDiv.style.cssText = 'left: 0px; right: 0px;';
	
				// Add child div with class 'fc-highlight'
				const highlightDiv = document.createElement('div');
				highlightDiv.className = 'fc-highlight';
				newDiv.appendChild(highlightDiv);
	
				event.srcElement.parentElement.parentElement.appendChild(newDiv);
			}

			if(( (event.srcElement.classList.contains('fc-daygrid-day-top') 
						|| event.srcElement.classList.contains('fc-daygrid-day-events') ) && 
					event.srcElement.parentElement.classList.contains('fc-daygrid-day-frame') && 
					event.srcElement.parentElement.parentElement.classList.contains('fc-daygrid-day') &&
					event.srcElement.parentElement.parentElement.tagName == 'TD')){
						
				const newDiv = document.createElement('div');
				// Set attributes and inner HTML for the div
				newDiv.className = 'fc-daygrid-bg-harness';
				newDiv.id = 'touch_div';
				newDiv.style.cssText = 'left: 0px; right: 0px;';
	
				// Add child div with class 'fc-highlight'
				const highlightDiv = document.createElement('div');
				highlightDiv.className = 'fc-highlight';
				newDiv.appendChild(highlightDiv);
	
				event.srcElement.parentElement.appendChild(newDiv);
			}
		}

		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();
					const practitioner_name = slot.name;
					console.log("practitioner name: "+practitioner_name);
					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(){
						if(practitioner_name != null || practitioner_name != undefined){
							$("#hidden_preferred_staff").val(true);
							$("#hidden_practitioner_name").val(practitioner_name);
						}
						$(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);
			}
			
		});

		document.addEventListener('DOMContentLoaded', () => {
			let startX = 0, startY = 0, isDragging = false;
			const movementThreshold = 5; // Allowable movement in pixels

			window.addEventListener('touchstart', (event) => {
				isDragging = false;
				startX = event.touches[0].clientX;
				startY = event.touches[0].clientY;
			});

			window.addEventListener('touchmove', (event) => {
				const deltaX = Math.abs(event.touches[0].clientX - startX);
				const deltaY = Math.abs(event.touches[0].clientY - startY);
				if (deltaX > movementThreshold || deltaY > movementThreshold) {
					isDragging = true;
				}
			});

			window.addEventListener('touchend', (event) => {
				if (!isDragging) {
					console.log("Stationary touch detected!");
					// alert("You performed a stationary touch!");
					handleClickEvent(event);
				}
			});
		});

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



