/**
 * Martial Arts Club Manager - Admin Scripts
 *
 * @package KarateClubManager
 */

(function($) {
	'use strict';

	/**
	 * Initialize when document is ready
	 */
	$(document).ready(function() {
		KCM_Admin.init();
	});

	/**
	 * Main admin object
	 */
	var KCM_Admin = {
		/**
		 * Initialize admin functionality
		 */
		init: function() {
			this.initArchiveButtons();
			this.initLicenseValidation();
			this.initLicenseExpirationClearButton();
			this.initBeltHistoryButtons();
		},

		/**
		 * Initialize Archive/Activate buttons
		 */
		initArchiveButtons: function() {
			var self = this;

			// Handle Archive button click
			$(document).on('click', '.kcm-admin-archive-member', function(e) {
				e.preventDefault();
				var button = $(this);
				var memberId = button.data('member-id');

				if (!confirm('Are you sure you want to archive this member?')) {
					return;
				}

				self.toggleMemberStatus(memberId, button);
			});

			// Handle Activate button click
			$(document).on('click', '.kcm-admin-activate-member', function(e) {
				e.preventDefault();
				var button = $(this);
				var memberId = button.data('member-id');

				if (!confirm('Are you sure you want to activate this member?')) {
					return;
				}

				self.toggleMemberStatus(memberId, button);
			});
		},

		/**
		 * Toggle member status (Archive/Activate)
		 */
		toggleMemberStatus: function(memberId, button) {
			var self = this;

			// Disable button and show loading
			button.prop('disabled', true);
			var originalText = button.text();
			button.text('Processing...');

			self.ajaxRequest(
				'kcm_admin_toggle_member_status',
				{ member_id: memberId },
				function(data) {
					// Success - reload page to show updated status
					location.reload();
				},
				function(data) {
					// Error
					button.prop('disabled', false);
					button.text(originalText);
					alert(data.message || 'Error updating member status');
				}
			);
		},

		/**
		 * Show loading state
		 */
		showLoading: function(element) {
			$(element).addClass('kcm-loading');
		},

		/**
		 * Hide loading state
		 */
		hideLoading: function(element) {
			$(element).removeClass('kcm-loading');
		},

		/**
		 * Show success notice
		 */
		showSuccess: function(message) {
			this.showNotice(message, 'success');
		},

		/**
		 * Show error notice
		 */
		showError: function(message) {
			this.showNotice(message, 'error');
		},

		/**
		 * Show notice
		 */
		showNotice: function(message, type) {
			var noticeClass = 'kcm-notice kcm-notice-' + type;
			var notice = $('<div class="' + noticeClass + '">' + message + '</div>');

			$('.kcm-admin-wrapper').prepend(notice);

			// Auto-hide after 5 seconds
			setTimeout(function() {
				notice.fadeOut(function() {
					$(this).remove();
				});
			}, 5000);
		},

		/**
		 * Make AJAX request
		 */
		ajaxRequest: function(action, data, successCallback, errorCallback) {
			data.action = action;
			data.nonce = macmAdmin.nonce;

			$.ajax({
				url: macmAdmin.ajaxurl,
				type: 'POST',
				data: data,
				success: function(response) {
					if (response.success) {
						if (typeof successCallback === 'function') {
							successCallback(response.data);
						}
					} else {
						if (typeof errorCallback === 'function') {
							errorCallback(response.data);
						}
					}
				},
				error: function(xhr, status, error) {
					if (typeof errorCallback === 'function') {
						errorCallback({message: 'AJAX request failed: ' + error});
					}
				}
			});
		},

		/**
		 * Initialize license number/expiration validation
		 * Requires license number before allowing expiration date
		 */
		initLicenseValidation: function() {
			var self = this;

			// Function to update expiration field state
			function updateExpirationField(licenseInput, expirationInput) {
				var hasLicenseNumber = licenseInput.val().trim().length > 0;

				if (hasLicenseNumber) {
					expirationInput.prop('disabled', false);
					expirationInput.closest('.kcm-form-row').find('.kcm-license-note').remove();
				} else {
					expirationInput.prop('disabled', true);
					expirationInput.val(''); // Clear any existing value

					// Add note if not already present
					if (expirationInput.closest('.kcm-form-row').find('.kcm-license-note').length === 0) {
						expirationInput.closest('.kcm-form-row').append(
							'<p class="kcm-license-note" style="color: #d63638; font-size: 12px; margin-top: 5px;">' +
							'Please enter a License Number first before setting the expiration date.' +
							'</p>'
						);
					}
				}
			}

			// Admin Add Member Modal
			$(document).on('input', '#kcm-admin-add-license-number', function() {
				var licenseInput = $(this);
				var expirationInput = $('#kcm-admin-add-license-expiration');
				updateExpirationField(licenseInput, expirationInput);
			});

			// Admin Edit Member Modal
			$(document).on('input', '#kcm-admin-license-number', function() {
				var licenseInput = $(this);
				var expirationInput = $('#kcm-admin-license-expiration');
				updateExpirationField(licenseInput, expirationInput);
			});

				// Function to check and update all license fields
			function checkAllLicenseFields() {
				// Check add form
				var addLicense = $('#kcm-admin-add-license-number');
				var addExpiration = $('#kcm-admin-add-license-expiration');
				if (addLicense.length && addExpiration.length) {
					updateExpirationField(addLicense, addExpiration);
				}

				// Check edit form
				var editLicense = $('#kcm-admin-license-number');
				var editExpiration = $('#kcm-admin-license-expiration');
				if (editLicense.length && editExpiration.length) {
					updateExpirationField(editLicense, editExpiration);
				}
			}

			// Initialize on modal open
			$(document).on('kcm-modal-opened', function() {
				checkAllLicenseFields();
			});

			// Check on page load (initial check)
			setTimeout(checkAllLicenseFields, 100);

			// Check again after a longer delay (for edit modals populated via AJAX)
			setTimeout(checkAllLicenseFields, 500);

			// Listen for changes to the license number field value (including programmatic changes)
			$(document).on('change', '#kcm-admin-license-number, #kcm-admin-add-license-number', function() {
				var licenseInput = $(this);
				var isEditForm = licenseInput.attr('id') === 'kcm-admin-license-number';
				var expirationInput = isEditForm ? $('#kcm-admin-license-expiration') : $('#kcm-admin-add-license-expiration');
				if (expirationInput.length) {
					updateExpirationField(licenseInput, expirationInput);
				}
			});

			// Watch for DOM mutations (when modal content is loaded dynamically)
			var observer = new MutationObserver(function(mutations) {
				mutations.forEach(function(mutation) {
					if (mutation.addedNodes.length) {
						// Check if license fields were added
						setTimeout(checkAllLicenseFields, 50);
					}
				});
			});

			// Observe the body for changes
			if (document.body) {
				observer.observe(document.body, {
					childList: true,
					subtree: true
				});
			}
		},

		/**
		 * Add clear button to license expiration field
		 */
		initLicenseExpirationClearButton: function() {
			// Wait for modals to be loaded
			setTimeout(function() {
				// Add clear button for both add and edit forms
				var editExpirationField = $('#kcm-admin-license-expiration');
				var addExpirationField = $('#kcm-admin-add-license-expiration');

				function addClearButton(field) {
					if (field.length && !field.next('.kcm-clear-date').length) {
						var wrapper = $('<div class="kcm-date-field-wrapper" style="position: relative; display: inline-block; width: 100%;"></div>');
						field.wrap(wrapper);

						var clearBtn = $('<button type="button" class="kcm-clear-date" style="position: absolute; right: 35px; top: 50%; transform: translateY(-50%); background: #dc3545; color: white; border: none; padding: 4px 8px; cursor: pointer; border-radius: 3px; font-size: 12px; z-index: 10;">Clear</button>');

						field.after(clearBtn);

						clearBtn.on('click', function(e) {
							e.preventDefault();
							field.val('').trigger('change');
						});
					}
				}

				addClearButton(editExpirationField);
				addClearButton(addExpirationField);

				// Re-add when modal is opened
				$(document).on('DOMNodeInserted', function() {
					var editField = $('#kcm-admin-license-expiration');
					var addField = $('#kcm-admin-add-license-expiration');
					if (editField.length && !editField.next('.kcm-clear-date').length) {
						addClearButton(editField);
					}
					if (addField.length && !addField.next('.kcm-clear-date').length) {
						addClearButton(addField);
					}
				});
			}, 500);
		},

		/**
		 * Initialize Belt History buttons
		 * NOTE: Belt history functionality is handled by inline JS in class-kcm-admin-menu.php
		 * This function is kept as a stub to prevent errors but doesn't add duplicate handlers
		 */
		initBeltHistoryButtons: function() {
			// Belt history event handlers are defined inline in class-kcm-admin-menu.php
			// to avoid duplicate event binding. This function is intentionally empty.
		},

		// Store current member data for grading
		currentGradingMemberId: null,
		currentGradingMemberName: null,
		gradingExportUrl: null,
		beltColors: [],
		instructors: [],
		gradingRecords: [],

		/**
		 * Show Belt History Modal
		 */
		showBeltHistoryModal: function(memberId, memberName) {
			var self = this;
			self.currentGradingMemberId = memberId;
			self.currentGradingMemberName = memberName;

			// Show modal with loading
			$('#kcm-grading-modal-title').text('Belt Grading History - ' + memberName);
			$('#kcm-grading-content').html('<div class="kcm-loading">Loading...</div>');
			$('#kcm-grading-export-btn, #kcm-add-grading-btn').hide();
			$('#kcm-grading-modal').show();

			// Check if macmGrading is available (premium feature)
			if (typeof macmGrading === 'undefined') {
				$('#kcm-grading-content').html('<div class="kcm-error">Belt history feature is not available. This is a premium feature.</div>');
				return;
			}

			// Fetch history via AJAX
			$.ajax({
				url: macmGrading.ajaxurl,
				type: 'POST',
				data: {
					action: 'macm_get_grading_history',
					member_id: memberId,
					nonce: macmGrading.nonce
				},
				success: function(response) {
					if (response.success) {
						self.beltColors = response.data.belt_colors;
						self.instructors = response.data.instructors;
						self.gradingRecords = response.data.records;
						self.gradingExportUrl = response.data.export_url;

						self.renderGradingHistory(response.data.records);
						$('#kcm-grading-export-btn, #kcm-add-grading-btn').show();
					} else {
						$('#kcm-grading-content').html('<div class="kcm-error">' + (response.data.message || 'Error loading history.') + '</div>');
					}
				},
				error: function() {
					$('#kcm-grading-content').html('<div class="kcm-error">Error loading history. Please try again.</div>');
				}
			});
		},

		/**
		 * Render grading history table
		 */
		renderGradingHistory: function(records) {
			var self = this;

			if (!records || records.length === 0) {
				$('#kcm-grading-content').html('<p class="kcm-no-records">No grading history found for this member.</p>');
				return;
			}

			var html = '<table class="wp-list-table widefat fixed striped">';
			html += '<thead><tr>';
			html += '<th>Date</th>';
			html += '<th>Belt Color</th>';
			html += '<th>Examiner</th>';
			html += '<th>Score</th>';
			html += '<th>Notes</th>';
			html += '<th>Actions</th>';
			html += '</tr></thead><tbody>';

			records.forEach(function(record) {
				html += '<tr>';
				html += '<td>' + self.escapeHtml(record.grading_date_formatted) + '</td>';
				html += '<td>' + self.escapeHtml(record.color_name || record.belt_color_key) + '</td>';
				html += '<td>' + self.escapeHtml(record.examiner_display || '-') + '</td>';
				html += '<td>' + self.escapeHtml(record.score || '-') + '</td>';
				html += '<td>' + self.escapeHtml(record.notes || '-') + '</td>';
				html += '<td>';
				html += '<a href="#" class="kcm-edit-grading" data-record-id="' + record.id + '">Edit</a> | ';
				html += '<a href="#" class="kcm-delete-grading" data-record-id="' + record.id + '" style="color: #dc3545;">Delete</a>';
				html += '</td>';
				html += '</tr>';
			});

			html += '</tbody></table>';
			$('#kcm-grading-content').html(html);
		},

		/**
		 * Show Add Grading Form
		 */
		showAddGradingForm: function() {
			var self = this;

			// Reset form
			$('#kcm-grading-form')[0].reset();
			$('#grading-record-id').val('');
			$('#grading-member-id').val(self.currentGradingMemberId);
			$('#kcm-grading-form-title').text('Add Grading Record');

			// Populate belt colors
			self.populateBeltColorSelect();

			// Populate instructors
			self.populateInstructorSelect();

			$('#kcm-grading-form-modal').show();
		},

		/**
		 * Show Edit Grading Form
		 */
		showEditGradingForm: function(recordId) {
			var self = this;

			// Find record
			var record = self.gradingRecords.find(function(r) {
				return r.id == recordId;
			});

			if (!record) {
				alert('Record not found');
				return;
			}

			// Reset form
			$('#kcm-grading-form')[0].reset();
			$('#grading-record-id').val(recordId);
			$('#grading-member-id').val(self.currentGradingMemberId);
			$('#kcm-grading-form-title').text('Edit Grading Record');

			// Populate belt colors
			self.populateBeltColorSelect(record.belt_color_key);

			// Populate instructors
			self.populateInstructorSelect(record.examiner_id);

			// Fill form values
			$('#grading-date').val(record.grading_date);
			$('#grading-examiner-name').val(record.examiner_name || '');
			$('#grading-score').val(record.score || '');
			$('#grading-notes').val(record.notes || '');

			$('#kcm-grading-form-modal').show();
		},

		/**
		 * Populate belt color select
		 */
		populateBeltColorSelect: function(selectedKey) {
			var select = $('#grading-belt-color');
			select.empty().append('<option value="">Select belt color...</option>');

			this.beltColors.forEach(function(belt) {
				var selected = belt.color_key === selectedKey ? ' selected' : '';
				select.append('<option value="' + belt.color_key + '"' + selected + '>' + belt.color_name + '</option>');
			});
		},

		/**
		 * Populate instructor select
		 */
		populateInstructorSelect: function(selectedId) {
			var select = $('#grading-examiner');
			select.empty().append('<option value="">Select instructor...</option>');

			this.instructors.forEach(function(instructor) {
				var selected = instructor.id == selectedId ? ' selected' : '';
				select.append('<option value="' + instructor.id + '"' + selected + '>' + instructor.full_name + '</option>');
			});
		},

		/**
		 * Save grading record
		 */
		saveGradingRecord: function() {
			var self = this;

			// Validate form
			var beltColor = $('#grading-belt-color').val();
			var gradingDate = $('#grading-date').val();

			if (!beltColor) {
				alert('Please select a belt color');
				return;
			}
			if (!gradingDate) {
				alert('Please select a grading date');
				return;
			}

			var data = {
				action: 'macm_save_grading',
				nonce: macmGrading.nonce,
				record_id: $('#grading-record-id').val(),
				member_id: $('#grading-member-id').val(),
				belt_color_key: beltColor,
				grading_date: gradingDate,
				examiner_id: $('#grading-examiner').val(),
				examiner_name: $('#grading-examiner-name').val(),
				score: $('#grading-score').val(),
				notes: $('#grading-notes').val()
			};

			$.ajax({
				url: macmGrading.ajaxurl,
				type: 'POST',
				data: data,
				success: function(response) {
					if (response.success) {
						$('#kcm-grading-form-modal').hide();
						// Reload history
						self.showBeltHistoryModal(self.currentGradingMemberId, self.currentGradingMemberName);
					} else {
						alert(response.data.message || 'Error saving grading record.');
					}
				},
				error: function() {
					alert('Error saving grading record. Please try again.');
				}
			});
		},

		/**
		 * Delete grading record
		 */
		deleteGradingRecord: function(recordId) {
			var self = this;

			if (!confirm('Are you sure you want to delete this grading record?')) {
				return;
			}

			$.ajax({
				url: macmGrading.ajaxurl,
				type: 'POST',
				data: {
					action: 'macm_delete_grading',
					nonce: macmGrading.nonce,
					record_id: recordId
				},
				success: function(response) {
					if (response.success) {
						// Reload history
						self.showBeltHistoryModal(self.currentGradingMemberId, self.currentGradingMemberName);
					} else {
						alert(response.data.message || 'Error deleting grading record.');
					}
				},
				error: function() {
					alert('Error deleting grading record. Please try again.');
				}
			});
		},

		/**
		 * Escape HTML for safe display
		 */
		escapeHtml: function(text) {
			if (!text) return '';
			var div = document.createElement('div');
			div.textContent = text;
			return div.innerHTML;
		}
	};

	// Make KCM_Admin available globally
	window.KCM_Admin = KCM_Admin;

})(jQuery);
