/**
 * Class Register JavaScript
 *
 * Handles the class register interface interactions and AJAX requests
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/assets/js
 * @since      1.0.0
 */

(function($) {
	'use strict';

	/**
	 * Class Register Object
	 */
	var KCMClassRegister = {
		/**
		 * Initialize
		 */
		init: function() {
			this.bindEvents();
		},

		/**
		 * Bind event handlers
		 */
		bindEvents: function() {
			// Class selection change
			$('#kcm-class-select').on('change', this.onClassChange.bind(this));

			// Date selection change
			$('#kcm-attendance-date').on('change', this.onDateChange.bind(this));

			// Select all / Deselect all buttons
			$('#kcm-select-all').on('click', this.selectAll.bind(this));
			$('#kcm-deselect-all').on('click', this.deselectAll.bind(this));

			// Mark attendance button
			$('#kcm-mark-attendance').on('click', this.markAttendance.bind(this));
		},

		/**
		 * Handle class selection change
		 */
		onClassChange: function(e) {
			var classId = $(e.target).val();
			var date = $('#kcm-attendance-date').val();

			// Hide member list and reset
			$('#kcm-member-list-wrapper').hide();
			$('#kcm-notes-row').hide();
			$('#kcm-submit-row').hide();
			$('#kcm-member-list').empty();
			this.hideMessage();

			if (!classId || !date) {
				return;
			}

			// Load members for selected class
			this.loadClassMembers(classId, date);
		},

		/**
		 * Handle date selection change
		 */
		onDateChange: function(e) {
			var classId = $('#kcm-class-select').val();
			var date = $(e.target).val();

			// Hide member list and reset
			$('#kcm-member-list-wrapper').hide();
			$('#kcm-notes-row').hide();
			$('#kcm-submit-row').hide();
			$('#kcm-member-list').empty();
			this.hideMessage();

			if (!classId || !date) {
				return;
			}

			// Load members for selected class and date
			this.loadClassMembers(classId, date);
		},

		/**
		 * Load enrolled members for a class via AJAX
		 */
		loadClassMembers: function(classId, date) {
			var self = this;

			// Show loading
			this.showLoading();

			$.ajax({
				url: macmClassRegister.ajaxurl,
				type: 'POST',
				data: {
					action: 'macm_load_class_members',
					nonce: macmClassRegister.nonce,
					class_id: classId,
					date: date
				},
				success: function(response) {
					self.hideLoading();

					if (response.success) {
						if (response.data.members && response.data.members.length > 0) {
							self.renderMemberList(response.data.members, response.data.attendance);
							$('#kcm-member-list-wrapper').show();
							$('#kcm-notes-row').show();
							$('#kcm-submit-row').show();
						} else {
							self.showMessage(response.data.message || 'No members enrolled in this class.', 'warning');
						}
					} else {
						self.showMessage(response.data.message || 'Failed to load members.', 'error');
					}
				},
				error: function(xhr, status, error) {
					self.hideLoading();
					self.showMessage('An error occurred while loading members. Please try again.', 'error');
					console.error('AJAX Error:', status, error);
				}
			});
		},

		/**
		 * Render member checklist
		 */
		renderMemberList: function(members, attendance) {
			var $list = $('#kcm-member-list');
			$list.empty();

			// Create attendance lookup for quick checks
			var attendanceMap = {};
			if (attendance && attendance.length > 0) {
				attendance.forEach(function(record) {
					attendanceMap[record.member_id] = true;
				});
			}

			members.forEach(function(member) {
				var $item = $('<div>', { class: 'kcm-member-item' });

				var $checkbox = $('<input>', {
					type: 'checkbox',
					id: 'member-' + member.id,
					name: 'members[]',
					value: member.id
				});

				// Pre-check if member already has attendance record
				if (attendanceMap[member.id]) {
					$checkbox.prop('checked', true);
				}

				var $label = $('<label>', {
					for: 'member-' + member.id,
					text: member.full_name
				});

				// Add belt color if available
				if (member.belt_color) {
					var $belt = $('<span>', {
						class: 'kcm-member-belt',
						text: ' (' + member.belt_color + ')'
					});
					$label.append($belt);
				}

				$item.append($checkbox).append($label);
				$list.append($item);
			});
		},

		/**
		 * Select all members
		 */
		selectAll: function(e) {
			e.preventDefault();
			$('#kcm-member-list input[type="checkbox"]').prop('checked', true);
		},

		/**
		 * Deselect all members
		 */
		deselectAll: function(e) {
			e.preventDefault();
			$('#kcm-member-list input[type="checkbox"]').prop('checked', false);
		},

		/**
		 * Mark attendance
		 */
		markAttendance: function(e) {
			e.preventDefault();

			var self = this;
			var classId = $('#kcm-class-select').val();
			var date = $('#kcm-attendance-date').val();
			var notes = $('#kcm-attendance-notes').val();
			var members = [];

			// Get selected members
			$('#kcm-member-list input[type="checkbox"]:checked').each(function() {
				members.push($(this).val());
			});

			// Validate
			if (!classId) {
				this.showMessage('Please select a class.', 'error');
				return;
			}

			if (!date) {
				this.showMessage('Please select a date.', 'error');
				return;
			}

			// Confirm
			var confirmMsg = members.length === 0
				? 'Remove all attendance records for ' + date + '?'
				: 'Mark attendance for ' + members.length + ' member(s) on ' + date + '?';
			if (!confirm(confirmMsg)) {
				return;
			}

			// Show loading
			this.showLoading();

			// Disable button
			$('#kcm-mark-attendance').prop('disabled', true);

			// Send AJAX request
			$.ajax({
				url: macmClassRegister.ajaxurl,
				type: 'POST',
				data: {
					action: 'macm_mark_attendance',
					nonce: macmClassRegister.nonce,
					class_id: classId,
					date: date,
					members: members,
					notes: notes
				},
				success: function(response) {
					self.hideLoading();
					$('#kcm-mark-attendance').prop('disabled', false);

					if (response.success) {
						// Show success message
						self.showMessage(response.data.message, 'success');

						// Show errors if any
						if (response.data.errors && response.data.errors.length > 0) {
							var errorList = '<ul>';
							response.data.errors.forEach(function(error) {
								errorList += '<li>' + error + '</li>';
							});
							errorList += '</ul>';
							self.showMessage(errorList, 'warning', true);
						}

						// Reload the member list to show updated attendance
						self.loadClassMembers(classId, date);
					} else {
						self.showMessage(response.data.message || 'Failed to mark attendance.', 'error');
					}
				},
				error: function(xhr, status, error) {
					self.hideLoading();
					$('#kcm-mark-attendance').prop('disabled', false);
					self.showMessage('An error occurred while marking attendance. Please try again.', 'error');
					console.error('AJAX Error:', status, error);
				}
			});
		},

		/**
		 * Reset form after successful submission
		 */
		resetForm: function() {
			// Deselect all members
			$('#kcm-member-list input[type="checkbox"]').prop('checked', false);

			// Clear notes
			$('#kcm-attendance-notes').val('');

			// Optionally reset class selection
			// $('#kcm-class-select').val('').trigger('change');
		},

		/**
		 * Show message
		 */
		showMessage: function(message, type, append) {
			type = type || 'info';
			var $messageBox = $('#kcm-register-message');

			// Remove existing classes
			$messageBox.removeClass('kcm-success kcm-error kcm-warning kcm-info');

			// Add type class
			$messageBox.addClass('kcm-' + type);

			// Set message
			if (append) {
				$messageBox.append(message);
			} else {
				$messageBox.html(message);
			}

			// Show message
			$messageBox.slideDown();

			// Auto-hide success messages after 5 seconds
			if (type === 'success') {
				setTimeout(function() {
					$messageBox.slideUp();
				}, 5000);
			}

			// Scroll to message
			$('html, body').animate({
				scrollTop: $messageBox.offset().top - 100
			}, 300);
		},

		/**
		 * Hide message
		 */
		hideMessage: function() {
			$('#kcm-register-message').slideUp().empty();
		},

		/**
		 * Show loading indicator
		 */
		showLoading: function() {
			$('#kcm-loading').show();
		},

		/**
		 * Hide loading indicator
		 */
		hideLoading: function() {
			$('#kcm-loading').hide();
		}
	};

	/**
	 * Initialize on document ready
	 */
	$(document).ready(function() {
		if ($('.kcm-class-register-wrapper').length > 0) {
			KCMClassRegister.init();
		}
	});

})(jQuery);
