<?php
include_once __DIR__. '/helpers/admin-common.php';
require_once __DIR__. '/helpers/SessionManagementService.php';
require_once __DIR__. '/helpers/UserService.php';
require_once __DIR__. '/models/UserModel.php';
require_once __DIR__. '/../common.php';
require_once __DIR__. '/../my-optician-wsdl-service/MyOpticianWsdlService.php';
require_once __DIR__. '/../my-optician-wsdl-service/GlobalLoader.php';
global $service_url, $optician_id, $shops, $opticianService, $siteInfo, $siteId, $current_step, $isstepped_process;
$current_step = 1;
$isstepped_process = false;
$session_management_service = new SessionManagementService();
if(!isset($_SESSION['usermodel'])){
	include_once( __DIR__. '/../error.php');
	die;
}

$userModel = $session_management_service->getUserModel();
$siteInfo = $userModel->getSiteInfo();
$opticianService = new MyOpticianWsdlService($service_url, null);

$siteId = $siteInfo->getSite();
$password = $siteInfo->getPassword();

$shopName  = null;
if(isset($_GET['Shop'])){
	$shopName = $_GET['Shop'];
} else if(count($shops) == 1){
	$shopName = $shops[0]->getName();
} else {
	require_once 'error.php';
	exit(0);
}

$_POST['hidden_shop_name'] = $shopName;
$globalLoader = new GlobalLoader($optician_id);
$globalLoader->loadGlobalSelectedShop($siteInfo->getSite(), $siteInfo->getPassword(), $siteInfo);

if($shopName != null){
	$practitioners = $opticianService->getPractitioners($siteId, $password, $shopName, $siteInfo);
}


?>
<!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="#">
		<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">
				<div class="sitecontainer">
					<div class="heading" id="hideshow2" >
					<h5>Select 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>
					</div>
				</div>
		</div>
	</form>

	<div class="sedsection">
		<div class="sitecontainer">
		 	<div class="sedsectioninner">
			 	<div class="left">
			 		<div class="heading">
				 	  <h5>Choose a date to see booked appointments</h5>
					   <div id="calendar"></div>
				 	</div>
			 	</div>
			 	<div class="right">
			 		<div class="heading">
				 	  <h5>Appointments <span id='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 class="heading"> </div>
					<label >click the appointment to book the available slot.</label>
			 	</div>	 	  
		 	</div>
		</div>
	</div>

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

		function getRelativeBasePath() {
            // Get the current URL
            const currentUrl = window.location.href;

            // Parse the current URL to get the pathname
            const url = new URL(currentUrl);
            const pathname = url.pathname;

            const index = pathname.indexOf('optician-panel');

            // Remove the path including and after "optician-panel"
            let basePath;
            if (index !== -1) {
                basePath = pathname.substring(0, index);
            } else {
                basePath = pathname;
            }

            // Construct the new URL based on the base path
            const newUrl = `${url.origin}${basePath}`;

            return newUrl;
        }

        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);
					renderAppointmentSlots([]);
                });
				if(practitionerNames.length ==1)
					newDiv.find("input").click();
			});
		}

        function getPractitioners(callbackFunc) {
			showLoader();
            var opticianId = 123;
			$.ajax({
                
				url: getRelativeBasePath()+'/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.log('Error fetching shop data:');
                    console.log(error);
					hideLoader();
				}
			});
		}
        
		$(document).ready(function() {
		    // $("input[name$='selectmember']").click(function() {
		    //     var test = $(this).val();
		    //     $("#hideshow2").hide();
		    //     $("#hideshow" + test).show();
		    // });
			$("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);
				}
		    });
            getPractitioners(populatePractitioners);
		});

		// $(document).ready(function(){
		//   $(".sedsection .sedsectioninner .right .timeslote .box .item a").click(function(){
		//     $(this).addClass("active");
		//   });
		// });

		$(document).ready(function() {
			var calendarEl = document.getElementById('calendar');
			initialiseCalendar();
			renderAppointmentSlots(null);
		});

		function initialiseCalendar(){
			var currentSlots = {};
			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,
				unselectAuto: false,
				events: calenderEvents,
				dateClick: function(info) {
					console.log(info);
					console.log(info.dateStr);

					var practitioner_name = $("#hidden_practitioner_name").val() != undefined ? $("#hidden_practitioner_name").val().trim() : '';
					if(practitioner_name == ''){
						showError("Please select practitioner first.");
						$('#span-selected-date').text('');
					} else {
						getAppointmentSlots(practitioner_name, info.dateStr);
					}
					if(isMobileView()){
						calendar.select( info.dateStr );
					}
				},
				
			});
			calendar.render();
		}

		function isMobileView() {
			return getComputedStyle(document.body).getPropertyValue('--is-mobile') === '1';
		}

		function getAppointmentSlots(selectedPractitionerName, calendar_date_ymd) {
			var calendar_date;
			if(calendar_date_ymd == null)
				calendar_date = moment().format('DD/MM/YYYY');
			else 
			{
				calendar_date = moment(calendar_date_ymd).format('DD/MM/YYYY');
			}
			// renderAppointmentSlots(null);
			showLoader();
			$.ajax({
				url: getRelativeBasePath()+'api/getDiarySlots.php', // Replace with your actual backend endpoint
				method: 'GET',
				dataType: 'json',
				data: { OpticianId: opticianId, 
					shop_name: shop, 
					practitioner_name: selectedPractitionerName,
					calendar_date: calendar_date},
				
				success: function(data) {
					// Populate the <ul> element with the fetched data
					console.log('appointment slots lists:');
					console.log(data);
					var appointmentSlotsMap = parseAppointmentSlots(data.data);
					// if(appointmentSlotsMap != null 
					// 	&& appointmentSlotsMap != undefined 
					// 	&& Object.values(appointmentSlotsMap) != null 
					// 	&& Object.values(appointmentSlotsMap) != undefined 
					// 	&& Object.values(appointmentSlotsMap).length > 0)
					// var appointmentSlots = Object.values(appointmentSlotsMap)[0];
					var appointmentSlots = appointmentSlotsMap[calendar_date_ymd] != null 
						&& appointmentSlotsMap[calendar_date_ymd] != undefined 
						? appointmentSlotsMap[calendar_date_ymd] : [];
					$('#span-selected-date').text("for "+calendar_date);
					renderAppointmentSlots(appointmentSlots);
					
					hideLoader();
				},
				error: function(error) {
					console.error('Error fetching shop data:', error);
					hideLoader();
					$('#span-selected-date').text('');
				}
			});
		}

		function parseAppointmentSlots(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;
			// });
			var 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
				});
			});
			return currentSlots;
		}

		function renderAppointmentSlots(slots){
			const appointmentBox = $(".timeslote div.box");
			firstDiv = $(".timeslote div.box div.item:first").clone();
			appointmentBox.empty();
			console.log(slots);
			if(slots == undefined || slots == null || slots.length == 0){
				var newDiv = firstDiv.clone();
				newDiv.find("p").text("Please Select Date"); // Replace "new-link" with the actual link
				appointmentBox.append(newDiv);
				newDiv.show();
				$('#span-selected-date').text('');
				// newDiv.hide();
			} else {
				var count = 0;
				slots.forEach(function(slot) {
					count++;
					var slotTime = slot.start_time;
					var isBooked = slot.name != null && slot.name != undefined && slot.name.trim() != '';
					var text = slotTime + ( isBooked ? ' ' + slot.name : '' ); 
					var newDiv = firstDiv.clone();
					const practitioner_name = slot.name;
					console.log("practitioner name: "+practitioner_name);
					newDiv.find("p").text(text); // Replace "new-link" with the actual link
					// if(isBooked){
					// 	newDiv.find("a").addClass('booked');
					// }
					appointmentBox.append(newDiv);
					newDiv.find("a").attr("data-slot", slot.slot_str)
					if(slot.name==''){
						newDiv.find("a").on("click", function(){
							var practitioner_name = $("#hidden_practitioner_name").val();
							if(practitioner_name != null || practitioner_name != undefined){
								$("#hidden_preferred_staff").val(true);
							}
							$(this).parent().parent().find("a").each(function(e){$(this).removeClass('active');});
							$(this).addClass("active");
							$("#hidden_appointment_slot").val($(this).attr("data-slot"));
							$("#main-form").attr('action', getRelativeBasePath()+"user-details.php");
							$("#main-form").submit();
						});
					}
					newDiv.show();
				});
			}
		}

		function showError(error){
			window.alert(error);
		}
	</script>
<?php include_once(__DIR__ . '/../footer.php'); ?>
</body>
</html>