// source --> https://enali.fr/wp-content/plugins/tutorlms-attendance/public/js/tutor-lms-attendance-public.js?ver=1.2.0 
(function ($) {
	'use strict';

	/**
	 * All of the code for your public-facing JavaScript source
	 * should reside in this file.
	 *
	 * Note: It has been assumed you will write jQuery code here, so the
	 * $ function reference has been prepared for usage within the scope
	 * of this function.
	 *
	 * This enables you to define handlers, for when the DOM is ready:
	 *
	 * $(function() {
	 *
	 * });
	 *
	 * When the window is loaded:
	 *
	 * $( window ).load(function() {
	 *
	 * });
	 *
	 * ...and/or other possibilities.
	 *
	 * Ideally, it is not considered best practise to attach more than a
	 * single DOM-ready or window-load handler for a particular page.
	 * Although scripts in the WordPress core, Plugins and Themes may be
	 * practising this, we should strive to set a better example in our own work.
	 */

	$(document).ready(function () {


		var mouseX = 0;
		var mouseY = 0;
		var current_user_id = tlms_ajax_url.sessionValue;
		document.addEventListener("mousemove", function (e) {
			mouseX = e.clientX;
			mouseY = e.clientY;
			// document.getElementById("coordinates").innerHTML = "<br />X: " + e.clientX + "px<br />Y: " + e.clientY + "px";
		});

		var ajaxRequestSent = false;
		var tracking_option = tlms_ajax_url.user_tr_option;
		if (tracking_option == 'on') {
			jQuery(document).mousemove(function (event) {

				var mouseY = event.pageY;
				var mouseX = event.pageX;
				var roles = tlms_ajax_url.user_role;
				var hasSubscriber = roles.includes('subscriber');
				var hasCustomer = roles.includes('customer');
				var value = tlms_ajax_url.sessionValue;

				if (!ajaxRequestSent && value !== 'true' && mouseY < 130 && mouseX > $(window).width() - 200 && (hasSubscriber || hasCustomer)) {
					ajaxRequestSent = true;
					$.post(tlms_ajax_url.ajax_url, { action: 'update_session', value: true }, function (response) {
						if (response.success) {
							console.log(response.success);
							if (value !== 'true') {
								value = true;
								$('#logout-popup').show();
							}
						} else {
							alert('Error: ' + response.data);
						}
					});
				}
			});


			$('.close-btn').click(function () {
				$('#logout-popup').hide();
			});

			$('.cancel-btn').click(function () {
				$('#logout-popup').hide();
			});

			$(window).click(function (event) {
				if ($(event.target).is('#logout-popup')) {
					$('#logout-popup').hide();
				}
			});
		}

		// Page Time Tracking Logic
		var track_pages = tlms_ajax_url.user_track_pages;
		var roles = tlms_ajax_url.user_role || [];
		var current_post_type = tlms_ajax_url.post_type;
		var current_post_id = tlms_ajax_url.post_id;
		var hasSubscriber = roles.indexOf('subscriber') !== -1;
		var hasCustomer = roles.indexOf('customer') !== -1;
		var hasAdmin = roles.indexOf('administrator') !== -1;
		var tracking_active = false;

		// Supported post types for duration tracking
		var supported_types = ['courses', 'lesson'];
		var is_enrolled = tlms_ajax_url.is_enrolled;
		var supports_tracking = supported_types.indexOf(current_post_type) !== -1;

		if (tracking_option === 'on' && (hasSubscriber || hasCustomer || hasAdmin) && supports_tracking && is_enrolled) {
			tracking_active = true;
			console.log('Tutor LMS Time Tracking Active for:', current_post_type, 'ID:', current_post_id);

			// Initial call to start tracking
			send_tracking_heartbeat();

			// Periodic heartbeat every 30 seconds
			var tracking_interval = setInterval(function () {
				send_tracking_heartbeat();
			}, 30000);

			// Track on page unload
			$(window).on('beforeunload', function () {
				send_tracking_heartbeat();
			});
		}

		function send_tracking_heartbeat() {
			if (!tracking_active) return;

			$.ajax({
				url: tlms_ajax_url.ajax_url,
				type: 'POST',
				data: {
					action: 'tlms_at_save_page_tracking',
					post_id: current_post_id,
					post_type: current_post_type
				},
				success: function (response) {
					console.log('Tracking heartbeat:', response.data);
				}
			});
		}

		$(".chosen-select").chosen({
			no_results_text: "Oops, nothing found!"
		})
		$(".search-choice-close").text("X");
		$('#tlms-mark-attendance-user').submit(function (e) {
			e.preventDefault();
			var attendance_button = $('#tlms-mark-attendance-user button');

			attendance_button.attr('disabled', true);

			const formData = new FormData(this);
			$.ajax({
				url: tlms_ajax_url.ajax_url,
				type: 'POST',
				data: formData,
				contentType: false, // prevent jQuery from using an incorrect Content-type header
				processData: false,
				success: function (response) {
					if (response['status'] == 'error') {
						alert(response['message']);
						attendance_button.attr('disabled', false);

					} else {
						attendance_button.hide();
						console.log(response);
					}
				}
			})
		})

		$('#tlmsat-mark-attendance-form').submit(function (e) {
			e.preventDefault();
			$('#tlms_at_failed').hide();
			$('#tlms_at_success').hide();

			const formData = new FormData(this);
			$.ajax({
				url: tlms_ajax_url.ajax_url,
				type: 'POST',
				data: formData,
				contentType: false, // prevent jQuery from using an incorrect Content-type header
				processData: false,
				success: function (response) {
					$('#tlmsat-mark-attendance-form').trigger("reset");
					$('#tlmsat_mark_attendance_users').val('').trigger('chosen:updated');
					$('.chosen-choices')
					if (response['status'] == 'error') {
						$('#tlms_at_failed').text(response['message']);
						$('#tlms-at_front_msg-box').show();
						$('#tlms_at_failed').show();
					}
					if (response['status'] == 'success') {
						$('#tlms-at_front_msg-box').show();
						$('#tlms_at_success').show();
					}
				}
			})
		})

		$(document).on("input", ".tlms_attendance_input", function () {
			let value = $(this).val();
			if (value === "" || value < 0) {
				$(this).val(0);
			}
		});

		if (window.location.href.indexOf('/dashboard/my-courses/') > -1) {
			$('body').addClass('tutor-course-page');
		}
		if ($('body').hasClass('tutor-course-page')) {
			$('.tutor-dropdown').each(function () {

				var parentId = $(this).closest('[id^="table-dashboard-course-list-"]').attr('id');


				var courseId = parentId.replace('table-dashboard-course-list-', '');


				var newItem = $('<a>', {
					class: 'tutor-dropdown-item tutor-minimum-attendance',
					href: 'javascript:void(0)',
					'data-course-id': courseId,
					html: '<i class="tutor-icon-gear tutor-mr-8" aria-hidden="true"></i><span>Minimum Attendance</span>'
				});


				$(this).append(newItem);
			});
		}


		$(".tutor-minimum-attendance").on("click", function (e) {
			e.preventDefault();

			var courseId = $(this).data("course-id");


			$.ajax({
				url: tlms_ajax_url.ajax_url,
				type: 'POST',
				data: {
					action: 'get_minimum_attendance',
					course_id: courseId,
				},
				success: function (response) {
					if (response.success) {
						var currentValue = response.data.minimum_attendance || '';


						Swal.fire({
							title: 'Minimum Attendance',
							html: `<input type="number" id="minimum-attendance-input" class="swal2-input tlms_attendance_input" placeholder="Enter minimum attendance" value="${currentValue}">`,
							showCancelButton: true,
							showCloseButton: true,
							confirmButtonText: 'Save',
							cancelButtonText: 'Cancel',
							customClass: {
								title: 'tlms_attendance_title',
								confirmButton: 'tlms_attendance_button',
							},
							preConfirm: () => {
								var value = $('#minimum-attendance-input').val();
								if (value < 0) {
									Swal.showValidationMessage('Please enter a correct value');
									return false;
								}
								return value;
							},
						}).then((result) => {
							if (result.isConfirmed) {
								var newValue = result.value;

								$.ajax({
									url: tlms_ajax_url.ajax_url,
									type: 'POST',
									data: {
										action: 'save_minimum_attendance',
										course_id: courseId,
										minimum_attendance: newValue,
									},
									success: function (response) {
										if (response.success) {

											tutor_toast("Success", response.data.message, "success");
										} else {

											tutor_toast("error", response.data.message, "error");
										}
									},
									error: function () {
										Swal.fire({
											icon: 'error',
											title: 'Error',
											text: 'An error occurred while saving.',
										});
									},
								});

							}
						});
					} else {
						Swal.fire({
							icon: 'error',
							title: 'Error',
							text: 'Failed to fetch current value.',
						});
					}
				},
				error: function () {
					Swal.fire({
						icon: 'error',
						title: 'Error',
						text: 'An error occurred while fetching data.',
					});
				},
			});

		});

	})


})(jQuery);