/**
 * Admin Attendance JavaScript
 *
 * Handles admin attendance page interactions and AJAX requests
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/assets/js
 * @since      1.0.0
 */

(function($) {
	'use strict';

	/**
	 * Admin Attendance Object
	 */
	var KCMAdminAttendance = {

		/**
		 * Current report data for CSV export
		 */
		currentReportData: null,

		/**
		 * Chart instances
		 */
		trendChart: null,
		participationChart: null,

		/**
		 * Initialize
		 */
		init: function() {
			this.bindEvents();
		},

		/**
		 * Bind event handlers
		 */
		bindEvents: function() {
			// Report type change
			$('#report_type').on('change', this.onReportTypeChange.bind(this));

			// Generate report form
			$('#kcm-generate-report-form').on('submit', this.generateReport.bind(this));

			// Export CSV button
			$('#kcm-export-csv').on('click', this.exportCSV.bind(this));

			// Quick date filters
			$('.kcm-quick-date-filter').on('click', this.applyQuickDateFilter.bind(this));
			$('#kcm-clear-dates').on('click', this.clearDateFilters.bind(this));

			// Clear records forms
			$('#kcm-clear-by-date-form').on('submit', this.clearRecords.bind(this));
			$('#kcm-clear-by-member-form').on('submit', this.clearRecords.bind(this));
			$('#kcm-clear-all-form').on('submit', this.clearRecords.bind(this));

			// Permissions form
			$('#kcm-permissions-form').on('submit', this.savePermissions.bind(this));

			// Initialize report type visibility
			this.onReportTypeChange();
		},

		/**
		 * Handle report type change
		 */
		onReportTypeChange: function() {
			var reportType = $('#report_type').val();

			// Hide all conditional rows
			$('#report_class_row').hide();
			$('#report_member_row').hide();
			$('#report_instructor_row').hide();

			// Show relevant row based on type
			if (reportType === 'by_class') {
				$('#report_class_row').show();
				$('#report_class_id').prop('required', true);
				$('#report_member_id').prop('required', false);
				$('#report_instructor_id').prop('required', false);
			} else if (reportType === 'by_member') {
				$('#report_member_row').show();
				$('#report_member_id').prop('required', true);
				$('#report_class_id').prop('required', false);
				$('#report_instructor_id').prop('required', false);
			} else if (reportType === 'by_instructor') {
				$('#report_instructor_row').show();
				$('#report_instructor_id').prop('required', true);
				$('#report_class_id').prop('required', false);
				$('#report_member_id').prop('required', false);
			} else {
				// by_date - no additional fields required
				$('#report_class_id').prop('required', false);
				$('#report_member_id').prop('required', false);
				$('#report_instructor_id').prop('required', false);
			}
		},

		/**
		 * Apply quick date filter
		 */
		applyQuickDateFilter: function(e) {
			e.preventDefault();

			var filter = $(e.currentTarget).data('filter');
			var today = new Date();
			var dateFrom, dateTo;

			// Calculate date range based on filter
			switch(filter) {
				case 'today':
					dateFrom = today;
					dateTo = today;
					break;

				case 'this_week':
					// Get start of week (Sunday)
					var startOfWeek = new Date(today);
					startOfWeek.setDate(today.getDate() - today.getDay());
					dateFrom = startOfWeek;
					dateTo = today;
					break;

				case 'this_month':
					// Get first day of current month
					var startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
					dateFrom = startOfMonth;
					dateTo = today;
					break;

				case 'last_30_days':
					// Get date 30 days ago
					var thirtyDaysAgo = new Date(today);
					thirtyDaysAgo.setDate(today.getDate() - 30);
					dateFrom = thirtyDaysAgo;
					dateTo = today;
					break;

				default:
					return;
			}

			// Format dates as YYYY-MM-DD
			var formatDate = function(date) {
				var year = date.getFullYear();
				var month = String(date.getMonth() + 1).padStart(2, '0');
				var day = String(date.getDate()).padStart(2, '0');
				return year + '-' + month + '-' + day;
			};

			// Set the date input values
			$('#date_from').val(formatDate(dateFrom));
			$('#date_to').val(formatDate(dateTo));
		},

		/**
		 * Clear date filters
		 */
		clearDateFilters: function(e) {
			e.preventDefault();
			$('#date_from').val('');
			$('#date_to').val('');
		},

		/**
		 * Generate attendance report
		 */
		generateReport: function(e) {
			e.preventDefault();

			var self = this;
			var formData = $('#kcm-generate-report-form').serialize();

			// Hide previous results and messages
			$('#kcm-report-results').hide();
			$('#kcm-export-csv').hide();
			this.hideMessage('report');

			// Show loading
			this.showLoading('report');

			$.ajax({
				url: macmAdminAttendance.ajaxurl,
				type: 'POST',
				data: formData + '&action=macm_admin_generate_report&nonce=' + macmAdminAttendance.nonce,
				success: function(response) {
					self.hideLoading('report');

					if (response.success) {
						// Store data for CSV export
						self.currentReportData = {
							formData: formData,
							records: response.data.records,
							stats: response.data.stats
						};

						// Display results
						self.displayReportResults(response.data.records, response.data.stats);

						// Show export button
						$('#kcm-export-csv').show();

						// Show success message
						self.showMessage('report', 'Report generated successfully.', 'success');
					} else {
						self.showMessage('report', response.data.message || 'Failed to generate report.', 'error');
					}
				},
				error: function(xhr, status, error) {
					self.hideLoading('report');
					self.showMessage('report', 'An error occurred while generating the report.', 'error');
					console.error('AJAX Error:', status, error);
				}
			});
		},

		/**
		 * Display report results
		 */
		displayReportResults: function(records, stats) {
			// Destroy existing DataTable if it exists
			if ($.fn.DataTable && $.fn.DataTable.isDataTable('#kcm-attendance-report-table')) {
				$('#kcm-attendance-report-table').DataTable().destroy();
			}

			// Display statistics
			var statsHtml = '<div class="kcm-report-stats" style="display: flex; gap: 20px; margin-bottom: 20px; padding: 15px; background: #F4F4F2; border-left: 4px solid #B11226; border-radius: 3px;">';
			statsHtml += '<div style="flex: 1;"><strong>Total Records:</strong> <span style="font-size: 18px; color: #B11226;">' + (stats.total_records || 0) + '</span></div>';
			if (stats.unique_dates_count) {
				statsHtml += '<div style="flex: 1;"><strong>Unique Dates:</strong> <span style="font-size: 18px; color: #B11226;">' + stats.unique_dates_count + '</span></div>';
			}
			if (stats.unique_members_count) {
				statsHtml += '<div style="flex: 1;"><strong>Unique Members:</strong> <span style="font-size: 18px; color: #B11226;">' + stats.unique_members_count + '</span></div>';
			}
			if (stats.unique_classes_count) {
				statsHtml += '<div style="flex: 1;"><strong>Classes:</strong> <span style="font-size: 18px; color: #B11226;">' + stats.unique_classes_count + '</span></div>';
			}
			statsHtml += '</div>';

			$('#kcm-report-stats').html(statsHtml);

			// Display table
			var tableHtml = '<table id="kcm-attendance-report-table" class="display" style="width:100%">';
			tableHtml += '<thead><tr>';
			tableHtml += '<th>Date</th>';
			tableHtml += '<th>Member</th>';
			tableHtml += '<th>Class</th>';
			tableHtml += '<th>Instructors</th>';
			tableHtml += '<th>Notes</th>';
			tableHtml += '</tr></thead>';
			tableHtml += '<tbody>';

			if (records.length > 0) {
				records.forEach(function(record) {
					tableHtml += '<tr>';
					tableHtml += '<td>' + record.date + '</td>';
					tableHtml += '<td>' + record.member_name + '</td>';
					tableHtml += '<td>' + record.class_name + '</td>';
				tableHtml += '<td>' + (record.instructors || 'None') + '</td>';
					tableHtml += '<td>' + (record.notes || '—') + '</td>';
					tableHtml += '</tr>';
				});
			}

			tableHtml += '</tbody></table>';

			$('#kcm-report-table').html(tableHtml);

			// Initialize DataTable if available
			if (records.length > 0 && $.fn.DataTable) {
				$('#kcm-attendance-report-table').DataTable({
					order: [[0, 'desc']], // Sort by date descending by default
					pageLength: 25,
					lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, 'All']],
					language: {
						search: 'Search records:',
						lengthMenu: 'Show _MENU_ records per page',
						info: 'Showing _START_ to _END_ of _TOTAL_ records',
						infoEmpty: 'No records found',
						infoFiltered: '(filtered from _MAX_ total records)',
						paginate: {
							first: 'First',
							last: 'Last',
							next: 'Next',
							previous: 'Previous'
						}
					}
				});
			}

			// Render charts
			this.renderCharts(records);

			// Show results section
			$('#kcm-report-results').show();
		},

		/**
		 * Render attendance charts
		 */
		renderCharts: function(records) {
			if (!records || records.length === 0) {
				return;
			}

			// Destroy existing charts
			if (this.trendChart) {
				this.trendChart.destroy();
			}
			if (this.participationChart) {
				this.participationChart.destroy();
			}
			if (this.instructorChart) {
				this.instructorChart.destroy();
			}

			// Process data for charts
			var chartData = this.processChartData(records);

			// Render Attendance Trend Chart (Bar Chart)
			this.renderTrendChart(chartData);

			// Render Member Participation Chart (Doughnut Chart)
			this.renderParticipationChart(chartData);

			// Render Instructor Activity Chart (Doughnut Chart)
			this.renderInstructorChart(chartData);
		},

		/**
		 * Process data for charts
		 */
		processChartData: function(records) {
			var dateCount = {};
			var memberCount = {};
			var instructorCount = {};

			records.forEach(function(record) {
				// Count by date
				if (!dateCount[record.date]) {
					dateCount[record.date] = 0;
				}
				dateCount[record.date]++;

				// Count by member
				if (!memberCount[record.member_name]) {
					memberCount[record.member_name] = 0;
				}
				memberCount[record.member_name]++;

				// Count by instructor (handle multiple instructors)
				if (record.instructors && record.instructors !== 'None') {
					var instructorNames = record.instructors.split(', ');
					instructorNames.forEach(function(name) {
						name = name.trim();
						if (name && name !== 'None') {
							if (!instructorCount[name]) {
								instructorCount[name] = 0;
							}
							instructorCount[name]++;
						}
					});
				}
			});

			// Convert to arrays and sort by date
			var dates = Object.keys(dateCount).sort();
			var dateCounts = dates.map(function(date) {
				return dateCount[date];
			});

			// Sort members by count (top 10)
			var memberPairs = Object.keys(memberCount).map(function(name) {
				return { name: name, count: memberCount[name] };
			});
			memberPairs.sort(function(a, b) {
				return b.count - a.count;
			});
			memberPairs = memberPairs.slice(0, 10);

			// Sort instructors by count (top 10)
			var instructorPairs = Object.keys(instructorCount).map(function(name) {
				return { name: name, count: instructorCount[name] };
			});
			instructorPairs.sort(function(a, b) {
				return b.count - a.count;
			});
			instructorPairs = instructorPairs.slice(0, 10);

			return {
				dates: dates,
				dateCounts: dateCounts,
				members: memberPairs.map(function(p) { return p.name; }),
				memberCounts: memberPairs.map(function(p) { return p.count; }),
				instructors: instructorPairs.map(function(p) { return p.name; }),
				instructorCounts: instructorPairs.map(function(p) { return p.count; })
			};
		},

		/**
		 * Render attendance trend chart
		 */
		renderTrendChart: function(data) {
			var ctx = document.getElementById('kcm-attendance-trend-chart');
			if (!ctx) return;

			this.trendChart = new Chart(ctx, {
				type: 'bar',
				data: {
					labels: data.dates,
					datasets: [{
						label: 'Attendance Count',
						data: data.dateCounts,
						backgroundColor: 'rgba(177, 18, 38, 0.7)',
						borderColor: 'rgba(177, 18, 38, 1)',
						borderWidth: 1
					}]
				},
				options: {
					responsive: true,
					maintainAspectRatio: true,
					plugins: {
						legend: {
							display: false
						},
						tooltip: {
							callbacks: {
								label: function(context) {
									return 'Attendance: ' + context.parsed.y;
								}
							}
						}
					},
					scales: {
						y: {
							beginAtZero: true,
							ticks: {
								stepSize: 1
							},
							title: {
								display: true,
								text: 'Number of Attendances'
							}
						},
						x: {
							title: {
								display: true,
								text: 'Date'
							}
						}
					}
				}
			});
		},

		/**
		 * Render member participation chart
		 */
		renderParticipationChart: function(data) {
			var ctx = document.getElementById('kcm-member-participation-chart');
			if (!ctx) return;

			// Generate colors for members
			var colors = this.generateColors(data.members.length);

			this.participationChart = new Chart(ctx, {
				type: 'doughnut',
				data: {
					labels: data.members,
					datasets: [{
						data: data.memberCounts,
						backgroundColor: colors,
						borderWidth: 2,
						borderColor: '#fff'
					}]
				},
				options: {
					responsive: true,
					maintainAspectRatio: true,
					plugins: {
						legend: {
							position: 'bottom',
							labels: {
								boxWidth: 15,
								padding: 10,
								font: {
									size: 11
								}
							}
						},
						tooltip: {
							callbacks: {
								label: function(context) {
									var label = context.label || '';
									var value = context.parsed || 0;
									var total = context.dataset.data.reduce(function(a, b) { return a + b; }, 0);
									var percentage = ((value / total) * 100).toFixed(1);
									return label + ': ' + value + ' (' + percentage + '%)';
								}
							}
						}
					}
				}
			});
		},

		/**
		 * Render instructor activity chart
		 */
		renderInstructorChart: function(data) {
			var ctx = document.getElementById('kcm-instructor-activity-chart');
			if (!ctx) return;

			// Check if there are instructors
			if (!data.instructors || data.instructors.length === 0) {
				// Show message instead of chart
				ctx.parentElement.innerHTML = '<p style="text-align: center; color: #6B7280; padding: 40px 0;">No instructor data available</p>';
				return;
			}

			// Generate colors for instructors
			var colors = this.generateColors(data.instructors.length);

			this.instructorChart = new Chart(ctx, {
				type: 'doughnut',
				data: {
					labels: data.instructors,
					datasets: [{
						data: data.instructorCounts,
						backgroundColor: colors,
						borderWidth: 2,
						borderColor: '#fff'
					}]
				},
				options: {
					responsive: true,
					maintainAspectRatio: true,
					plugins: {
						legend: {
							position: 'bottom',
							labels: {
								boxWidth: 15,
								padding: 10,
								font: {
									size: 11
								}
							}
						},
						tooltip: {
							callbacks: {
								label: function(context) {
									var label = context.label || '';
									var value = context.parsed || 0;
									var total = context.dataset.data.reduce(function(a, b) { return a + b; }, 0);
									var percentage = ((value / total) * 100).toFixed(1);
									return label + ': ' + value + ' classes (' + percentage + '%)';
								}
							}
						}
					}
				}
			});
		},

		/**
		 * Generate colors for chart
		 */
		generateColors: function(count) {
			var colors = [
				'rgba(177, 18, 38, 0.8)',
				'rgba(46, 204, 113, 0.8)',
				'rgba(241, 196, 15, 0.8)',
				'rgba(231, 76, 60, 0.8)',
				'rgba(155, 89, 182, 0.8)',
				'rgba(52, 152, 219, 0.8)',
				'rgba(26, 188, 156, 0.8)',
				'rgba(230, 126, 34, 0.8)',
				'rgba(149, 165, 166, 0.8)',
				'rgba(17, 24, 39, 0.8)'
			];

			// If we need more colors, generate them
			while (colors.length < count) {
				var r = Math.floor(Math.random() * 200) + 55;
				var g = Math.floor(Math.random() * 200) + 55;
				var b = Math.floor(Math.random() * 200) + 55;
				colors.push('rgba(' + r + ', ' + g + ', ' + b + ', 0.8)');
			}

			return colors.slice(0, count);
		},

		/**
		 * Export report to CSV
		 */
		exportCSV: function(e) {
			e.preventDefault();

			if (!this.currentReportData) {
				alert('Please generate a report first.');
				return;
			}

			// Create form and submit
			var form = $('<form>', {
				method: 'POST',
				action: macmAdminAttendance.ajaxurl
			});

			form.append($('<input>', {
				type: 'hidden',
				name: 'action',
				value: 'kcm_admin_export_csv'
			}));

			form.append($('<input>', {
				type: 'hidden',
				name: 'nonce',
				value: macmAdminAttendance.nonce
			}));

			// Add form data
			var formData = this.currentReportData.formData.split('&');
			formData.forEach(function(pair) {
				var parts = pair.split('=');
				if (parts.length === 2) {
					form.append($('<input>', {
						type: 'hidden',
						name: decodeURIComponent(parts[0]),
						value: decodeURIComponent(parts[1])
					}));
				}
			});

			// Submit form
			$('body').append(form);
			form.submit();
			form.remove();
		},

		/**
		 * Clear attendance records
		 */
		clearRecords: function(e) {
			e.preventDefault();

			var self = this;
			var $form = $(e.target);
			var formData = $form.serialize();
			var clearType = $form.find('input[name="clear_type"]').val();

			// Confirmation
			var confirmMsg = 'Are you sure you want to clear these records? This action cannot be undone.';
			if (clearType === 'all') {
				confirmMsg = 'WARNING: This will delete ALL attendance records. Are you absolutely sure?';
			}

			if (!confirm(confirmMsg)) {
				return;
			}

			// Hide previous messages
			this.hideMessage('clear');

			// Show loading
			this.showLoading('clear');

			// Disable submit button
			$form.find('button[type="submit"]').prop('disabled', true);

			$.ajax({
				url: macmAdminAttendance.ajaxurl,
				type: 'POST',
				data: formData + '&action=macm_admin_clear_records&nonce=' + macmAdminAttendance.nonce,
				success: function(response) {
					self.hideLoading('clear');
					$form.find('button[type="submit"]').prop('disabled', false);

					if (response.success) {
						self.showMessage('clear', response.data.message, 'success');
						// Reset form
						$form[0].reset();
					} else {
						self.showMessage('clear', response.data.message || 'Failed to clear records.', 'error');
					}
				},
				error: function(xhr, status, error) {
					self.hideLoading('clear');
					$form.find('button[type="submit"]').prop('disabled', false);
					self.showMessage('clear', 'An error occurred while clearing records.', 'error');
					console.error('AJAX Error:', status, error);
				}
			});
		},

		/**
		 * Save permissions
		 */
		savePermissions: function(e) {
			e.preventDefault();

			var self = this;
			var formData = $('#kcm-permissions-form').serialize();

			// Hide previous messages
			this.hideMessage('permissions');

			// Show loading
			this.showLoading('permissions');

			// Disable submit button
			$('#kcm-permissions-form button[type="submit"]').prop('disabled', true);

			$.ajax({
				url: macmAdminAttendance.ajaxurl,
				type: 'POST',
				data: formData + '&action=macm_admin_save_permissions&nonce=' + macmAdminAttendance.nonce,
				success: function(response) {
					self.hideLoading('permissions');
					$('#kcm-permissions-form button[type="submit"]').prop('disabled', false);

					if (response.success) {
						self.showMessage('permissions', response.data.message, 'success');
					} else {
						self.showMessage('permissions', response.data.message || 'Failed to save permissions.', 'error');
					}
				},
				error: function(xhr, status, error) {
					self.hideLoading('permissions');
					$('#kcm-permissions-form button[type="submit"]').prop('disabled', false);
					self.showMessage('permissions', 'An error occurred while saving permissions.', 'error');
					console.error('AJAX Error:', status, error);
				}
			});
		},

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

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

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

			// Set message
			$messageBox.html('<p>' + message + '</p>');

			// Show message
			$messageBox.show();

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

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

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

		/**
		 * Show loading indicator
		 */
		showLoading: function(context) {
			var $messageBox = $('#kcm-' + context + '-message');
			$messageBox.removeClass('notice-success notice-error notice-warning notice-info');
			$messageBox.addClass('notice-info');
			$messageBox.html('<p><span class="spinner is-active" style="float: none; margin: 0 10px 0 0;"></span>Loading...</p>');
			$messageBox.show();
		},

		/**
		 * Hide loading indicator
		 */
		hideLoading: function(context) {
			// hideMessage will be called after AJAX completes
		}
	};

	/**
	 * Initialize on document ready
	 */
	$(document).ready(function() {
		KCMAdminAttendance.init();
	});

})(jQuery);
