<?php
/**
 * Admin Classes Management
 *
 * Handles the classes management admin page
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/includes/admin
 * @since      1.0.0
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class MACM_Admin_Classes
 *
 * Manages the classes admin interface
 *
 * @since 1.0.0
 */
class MACM_Admin_Classes {

	/**
	 * Constructor
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'add_menu_pages' ), 17 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'admin_post_macm_save_class', array( $this, 'save_class' ) );
		add_action( 'admin_post_macm_archive_class', array( $this, 'archive_class' ) );
		add_action( 'admin_post_macm_unarchive_class', array( $this, 'unarchive_class' ) );
		add_action( 'admin_post_macm_delete_class', array( $this, 'delete_class' ) );
		add_action( 'admin_post_macm_save_enrollments', array( $this, 'save_enrollments' ) );
		add_action( 'admin_post_macm_export_class_enrollments', array( $this, 'export_class_enrollments' ) );
	}

	/**
	 * Add submenu pages
	 *
	 * @since 1.0.0
	 */
	public function add_menu_pages() {
		// Classes list page.
		add_submenu_page(
			'martial-arts-club-manager',
			__( 'Classes', 'martial-arts-club-manager' ),
			__( 'Classes', 'martial-arts-club-manager' ),
			'manage_macm_classes',
			'kcm-classes',
			array( $this, 'render_classes_page' )
		);

		// Hidden add/edit page.
		add_submenu_page(
			null,
			__( 'Add Class', 'martial-arts-club-manager' ),
			__( 'Add Class', 'martial-arts-club-manager' ),
			'manage_macm_classes',
			'kcm-class-form',
			array( $this, 'render_class_form_page' )
		);

		// Hidden enrollments page.
		add_submenu_page(
			null,
			__( 'Class Enrollments', 'martial-arts-club-manager' ),
			__( 'Class Enrollments', 'martial-arts-club-manager' ),
			'manage_macm_classes',
			'kcm-class-enrollments',
			array( $this, 'render_enrollments_page' )
		);
	}

	/**
	 * Enqueue scripts for classes pages
	 *
	 * @since 1.0.174
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_scripts( $hook ) {
		// Only load on classes pages.
		$classes_pages = array(
			'karate-club-manager_page_kcm-classes',
			'admin_page_kcm-class-form',
			'admin_page_kcm-class-enrollments',
		);

		if ( in_array( $hook, $classes_pages, true ) ) {
			wp_enqueue_script(
				'kcm-admin-classes',
				MACM_PLUGIN_URL . 'assets/js/admin-classes.js',
				array( 'jquery' ),
				MACM_VERSION,
				true
			);
		}
	}

	/**
	 * Render the classes list page
	 *
	 * @since 1.0.0
	 */
	public function render_classes_page() {
		// Check permissions.
		if ( ! current_user_can( 'manage_macm_classes' ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'martial-arts-club-manager' ) );
		}

		// Default filter values.
		$filter_day      = -1;
		$filter_location = '';
		$show_archived   = false;

		// Get filters only if nonce is verified (form submission).
		if ( isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'macm_filter_classes' ) ) {
			$filter_day      = isset( $_GET['filter_day'] ) ? absint( wp_unslash( $_GET['filter_day'] ) ) : -1;
			$filter_location = isset( $_GET['filter_location'] ) ? absint( wp_unslash( $_GET['filter_location'] ) ) : '';
			$show_archived   = isset( $_GET['show_archived'] ) ? true : false;
		}

		// Build query args.
		$args = array();
		if ( $filter_day >= 0 ) {
			$args['day_of_week'] = $filter_day;
		}
		if ( $filter_location ) {
			$args['location_id'] = $filter_location;
		}
		if ( ! $show_archived ) {
			$args['is_archived'] = 0;
		} else {
			$args['is_archived'] = null;
		}

		// Get classes.
		$classes = MACM_Class::get_all( $args );

		// Get locations for filter.
		$locations = MACM_Location::get_all();

		// Get messages - only allowed values from our own redirects.
		$message          = '';
		$error            = '';
		$allowed_messages = array( 'saved', 'archived', 'unarchived', 'deleted', 'enrollments_saved' );
		if ( isset( $_GET['message'] ) ) {
			$raw_message = sanitize_text_field( wp_unslash( $_GET['message'] ) );
			if ( in_array( $raw_message, $allowed_messages, true ) ) {
				$message = $raw_message;
			}
		}
		if ( isset( $_GET['error'] ) ) {
			$error = sanitize_text_field( wp_unslash( $_GET['error'] ) );
		}

		?>
		<div class="wrap">
			<h1 class="wp-heading-inline"><?php esc_html_e( 'Classes', 'martial-arts-club-manager' ); ?></h1>
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=kcm-class-form' ) ); ?>" class="page-title-action"><?php esc_html_e( 'Add New', 'martial-arts-club-manager' ); ?></a>
			<hr class="wp-header-end">

			<?php if ( 'saved' === $message ) : ?>
				<div class="notice notice-success is-dismissible">
					<p><?php esc_html_e( 'Class saved successfully.', 'martial-arts-club-manager' ); ?></p>
				</div>
			<?php elseif ( 'archived' === $message ) : ?>
				<div class="notice notice-success is-dismissible">
					<p><?php esc_html_e( 'Class archived successfully.', 'martial-arts-club-manager' ); ?></p>
				</div>
			<?php elseif ( 'unarchived' === $message ) : ?>
				<div class="notice notice-success is-dismissible">
					<p><?php esc_html_e( 'Class unarchived successfully.', 'martial-arts-club-manager' ); ?></p>
				</div>
			<?php elseif ( 'deleted' === $message ) : ?>
				<div class="notice notice-success is-dismissible">
					<p><?php esc_html_e( 'Class deleted successfully.', 'martial-arts-club-manager' ); ?></p>
				</div>
			<?php elseif ( 'enrollments_saved' === $message ) : ?>
				<div class="notice notice-success is-dismissible">
					<p><?php esc_html_e( 'Enrollments saved successfully.', 'martial-arts-club-manager' ); ?></p>
				</div>
			<?php endif; ?>

			<?php if ( $error ) : ?>
				<div class="notice notice-error is-dismissible">
					<p><?php echo esc_html( urldecode( $error ) ); ?></p>
				</div>
			<?php endif; ?>

			<!-- Filters -->
			<div class="tablenav top">
				<div class="alignleft actions">
					<form method="get" action="">
						<input type="hidden" name="page" value="kcm-classes">
						<?php wp_nonce_field( 'macm_filter_classes', '_wpnonce', false ); ?>

						<select name="filter_day" id="filter-day">
							<option value="-1"><?php esc_html_e( 'All Days', 'martial-arts-club-manager' ); ?></option>
							<?php for ( $i = 0; $i <= 6; $i++ ) : ?>
								<option value="<?php echo esc_attr( $i ); ?>" <?php selected( $filter_day, $i ); ?>>
									<?php echo esc_html( MACM_Class::get_day_name( $i ) ); ?>
								</option>
							<?php endfor; ?>
						</select>

						<select name="filter_location" id="filter-location">
							<option value=""><?php esc_html_e( 'All Locations', 'martial-arts-club-manager' ); ?></option>
							<?php foreach ( $locations as $location ) : ?>
								<option value="<?php echo esc_attr( $location->id ); ?>" <?php selected( $filter_location, $location->id ); ?>>
									<?php echo esc_html( $location->location_name ); ?>
								</option>
							<?php endforeach; ?>
						</select>

						<label style="margin-left: 10px;">
							<input type="checkbox" name="show_archived" value="1" <?php checked( $show_archived ); ?>>
							<?php esc_html_e( 'Show Archived', 'martial-arts-club-manager' ); ?>
						</label>

						<input type="submit" class="button" value="<?php esc_attr_e( 'Filter', 'martial-arts-club-manager' ); ?>">

						<?php if ( $filter_day >= 0 || $filter_location || $show_archived ) : ?>
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=kcm-classes' ) ); ?>" class="button">
								<?php esc_html_e( 'Clear Filters', 'martial-arts-club-manager' ); ?>
							</a>
						<?php endif; ?>
					</form>
				</div>
			</div>

			<!-- Classes Table -->
			<table class="wp-list-table widefat fixed striped kcm-classes-table">
				<thead>
					<tr>
						<th scope="col"><?php esc_html_e( 'Class Name', 'martial-arts-club-manager' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Day', 'martial-arts-club-manager' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Time', 'martial-arts-club-manager' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Location', 'martial-arts-club-manager' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Instructors', 'martial-arts-club-manager' ); ?></th>
						<th scope="col" class="num"><?php esc_html_e( 'Enrolled', 'martial-arts-club-manager' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Status', 'martial-arts-club-manager' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Actions', 'martial-arts-club-manager' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php if ( ! empty( $classes ) ) : ?>
						<?php foreach ( $classes as $class ) : ?>
							<?php
							$location         = MACM_Location::get( $class->location_id );
							$enrollment_count = MACM_Class::get_enrollment_count( $class->id );
							$instructors      = MACM_Instructor::get_class_instructors( $class->id );
							$instructor_names = array();
							foreach ( $instructors as $instructor ) {
								$instructor_names[] = $instructor->full_name;
							}
							?>
							<tr <?php echo $class->is_archived ? 'style="opacity: 0.6;"' : ''; ?>>
								<td>
									<strong><?php echo esc_html( $class->class_name ); ?></strong>
									<?php if ( isset( $class->description ) && $class->description ) : ?>
										<br><span class="description"><?php echo esc_html( wp_trim_words( $class->description, 15 ) ); ?></span>
									<?php endif; ?>
								</td>
								<td>
									<?php echo esc_html( MACM_Class::get_day_name( $class->day_of_week ) ); ?>
								</td>
								<td>
									<?php echo esc_html( MACM_Class::format_time_range( $class->start_time, $class->end_time ) ); ?>
								</td>
								<td>
									<?php echo $location ? esc_html( $location->location_name ) : '<span class="description">' . esc_html__( 'Unknown', 'martial-arts-club-manager' ) . '</span>'; ?>
								</td>
								<td>
									<?php if ( ! empty( $instructor_names ) ) : ?>
										<?php echo esc_html( implode( ', ', $instructor_names ) ); ?>
									<?php else : ?>
										<span class="description"><?php esc_html_e( 'None', 'martial-arts-club-manager' ); ?></span>
									<?php endif; ?>
								</td>
								<td class="num">
									<?php
									$is_oversubscribed = isset( $class->max_capacity ) && $class->max_capacity && $enrollment_count > $class->max_capacity;
									$enrollment_style  = $is_oversubscribed ? 'color: #d63638; font-weight: 600;' : '';
									?>
									<span style="<?php echo esc_attr( $enrollment_style ); ?>">
										<?php echo esc_html( $enrollment_count ); ?>
										<?php if ( isset( $class->max_capacity ) && $class->max_capacity ) : ?>
											/ <?php echo esc_html( $class->max_capacity ); ?>
										<?php endif; ?>
									</span>
								</td>
								<td>
									<?php if ( $class->is_archived ) : ?>
										<span class="kcm-badge kcm-badge-archived"><?php esc_html_e( 'Archived', 'martial-arts-club-manager' ); ?></span>
									<?php else : ?>
										<span class="kcm-badge kcm-badge-success"><?php esc_html_e( 'Active', 'martial-arts-club-manager' ); ?></span>
									<?php endif; ?>
								</td>
								<td>
									<div class="row-actions">
										<span class="edit">
											<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=kcm-class-form&class_id=' . $class->id ), 'macm_edit_class_' . $class->id ) ); ?>">
												<?php esc_html_e( 'Edit', 'martial-arts-club-manager' ); ?>
											</a> |
										</span>
										<span class="enrollments">
											<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=kcm-class-enrollments&class_id=' . $class->id ), 'macm_view_enrollments_' . $class->id ) ); ?>">
												<?php esc_html_e( 'Enrollments', 'martial-arts-club-manager' ); ?>
											</a> |
										</span>
										<?php if ( $class->is_archived ) : ?>
											<span class="unarchive">
												<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=macm_unarchive_class&class_id=' . $class->id ), 'macm_unarchive_class_' . $class->id ) ); ?>">
													<?php esc_html_e( 'Unarchive', 'martial-arts-club-manager' ); ?>
												</a> |
											</span>
										<?php else : ?>
											<span class="archive">
												<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=macm_archive_class&class_id=' . $class->id ), 'macm_archive_class_' . $class->id ) ); ?>">
													<?php esc_html_e( 'Archive', 'martial-arts-club-manager' ); ?>
												</a> |
											</span>
										<?php endif; ?>
										<span class="delete">
											<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=macm_delete_class&class_id=' . $class->id ), 'macm_delete_class_' . $class->id ) ); ?>"
												class="submitdelete"
												onclick="return confirm('<?php esc_attr_e( 'Are you sure? This will delete all enrollment and attendance records for this class.', 'martial-arts-club-manager' ); ?>');">
												<?php esc_html_e( 'Delete', 'martial-arts-club-manager' ); ?>
											</a>
										</span>
									</div>
								</td>
							</tr>
						<?php endforeach; ?>
					<?php else : ?>
						<tr>
							<td colspan="8" style="text-align: center; padding: 40px;">
								<p><?php esc_html_e( 'No classes found.', 'martial-arts-club-manager' ); ?></p>
								<p><a href="<?php echo esc_url( admin_url( 'admin.php?page=kcm-class-form' ) ); ?>" class="button button-primary"><?php esc_html_e( 'Add Your First Class', 'martial-arts-club-manager' ); ?></a></p>
							</td>
						</tr>
					<?php endif; ?>
				</tbody>
			</table>
		</div>
		<?php
	}

	/**
	 * Render the class form page (add/edit)
	 *
	 * @since 1.0.0
	 */
	public function render_class_form_page() {
		// Check permissions.
		if ( ! current_user_can( 'manage_macm_classes' ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'martial-arts-club-manager' ) );
		}

		// Get class to edit if any.
		$class    = null;
		$class_id = 0;
		if ( isset( $_GET['class_id'] ) ) {
			$class_id = absint( wp_unslash( $_GET['class_id'] ) );
			// Verify nonce for edit requests.
			if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'macm_edit_class_' . $class_id ) ) {
				wp_die( esc_html__( 'Security check failed. Please try again.', 'martial-arts-club-manager' ) );
			}
			$class = MACM_Class::get( $class_id );
			if ( ! $class ) {
				wp_die( esc_html__( 'Class not found.', 'martial-arts-club-manager' ) );
			}
		}

		// Get locations.
		$locations = MACM_Location::get_all();

		// Get all instructors.
		$all_instructors = MACM_Instructor::get_all( true );

		// Get assigned instructors for this class.
		$assigned_instructor_ids = array();
		if ( $class ) {
			$assigned_instructor_ids = MACM_Instructor::get_class_instructor_ids( $class_id );
		}

		?>
		<div class="wrap">
			<h1><?php echo $class ? esc_html__( 'Edit Class', 'martial-arts-club-manager' ) : esc_html__( 'Add New Class', 'martial-arts-club-manager' ); ?></h1>

			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
				<?php wp_nonce_field( 'macm_save_class', 'macm_class_nonce' ); ?>
				<input type="hidden" name="action" value="macm_save_class">
				<?php if ( $class ) : ?>
					<input type="hidden" name="class_id" value="<?php echo esc_attr( $class->id ); ?>">
				<?php endif; ?>

				<table class="form-table">
					<tr>
						<th scope="row">
							<label for="class_name"><?php esc_html_e( 'Class Name', 'martial-arts-club-manager' ); ?> <span class="description">(<?php esc_html_e( 'required', 'martial-arts-club-manager' ); ?>)</span></label>
						</th>
						<td>
							<input type="text"
									id="class_name"
									name="name"
									class="regular-text"
									value="<?php echo $class ? esc_attr( $class->class_name ) : ''; ?>"
									required>
							<p class="description"><?php esc_html_e( 'Enter a descriptive name for this class', 'martial-arts-club-manager' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="class_location"><?php esc_html_e( 'Location', 'martial-arts-club-manager' ); ?> <span class="description">(<?php esc_html_e( 'required', 'martial-arts-club-manager' ); ?>)</span></label>
						</th>
						<td>
							<select id="class_location" name="location_id" required>
								<option value=""><?php esc_html_e( '-- Select Location --', 'martial-arts-club-manager' ); ?></option>
								<?php foreach ( $locations as $location ) : ?>
									<option value="<?php echo esc_attr( $location->id ); ?>" <?php selected( $class ? $class->location_id : '', $location->id ); ?>>
										<?php echo esc_html( $location->location_name ); ?>
									</option>
								<?php endforeach; ?>
							</select>
							<?php if ( empty( $locations ) ) : ?>
								<p class="description" style="color: #d63638;">
									<?php esc_html_e( 'No locations available.', 'martial-arts-club-manager' ); ?>
									<a href="<?php echo esc_url( admin_url( 'admin.php?page=kcm-locations' ) ); ?>"><?php esc_html_e( 'Add a location first', 'martial-arts-club-manager' ); ?></a>
								</p>
							<?php endif; ?>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="class_day"><?php esc_html_e( 'Day of Week', 'martial-arts-club-manager' ); ?> <span class="description">(<?php esc_html_e( 'required', 'martial-arts-club-manager' ); ?>)</span></label>
						</th>
						<td>
							<select id="class_day" name="day_of_week" required>
								<?php for ( $i = 0; $i <= 6; $i++ ) : ?>
									<option value="<?php echo esc_attr( $i ); ?>" <?php selected( $class ? $class->day_of_week : '', $i ); ?>>
										<?php echo esc_html( MACM_Class::get_day_name( $i ) ); ?>
									</option>
								<?php endfor; ?>
							</select>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="class_start_time"><?php esc_html_e( 'Start Time', 'martial-arts-club-manager' ); ?> <span class="description">(<?php esc_html_e( 'required', 'martial-arts-club-manager' ); ?>)</span></label>
						</th>
						<td>
							<input type="time"
									id="class_start_time"
									name="start_time"
									value="<?php echo $class ? esc_attr( substr( $class->start_time, 0, 5 ) ) : ''; ?>"
									required>
							<p class="description"><?php esc_html_e( 'Class start time', 'martial-arts-club-manager' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="class_end_time"><?php esc_html_e( 'End Time', 'martial-arts-club-manager' ); ?> <span class="description">(<?php esc_html_e( 'required', 'martial-arts-club-manager' ); ?>)</span></label>
						</th>
						<td>
							<input type="time"
									id="class_end_time"
									name="end_time"
									value="<?php echo $class ? esc_attr( substr( $class->end_time, 0, 5 ) ) : ''; ?>"
									required>
							<p class="description"><?php esc_html_e( 'Class end time', 'martial-arts-club-manager' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="class_description"><?php esc_html_e( 'Description', 'martial-arts-club-manager' ); ?></label>
						</th>
						<td>
							<textarea id="class_description"
										name="description"
										class="large-text"
										rows="4"><?php echo ( $class && isset( $class->description ) ) ? esc_textarea( $class->description ?? '' ) : ''; ?></textarea>
							<p class="description"><?php esc_html_e( 'Optional description of this class', 'martial-arts-club-manager' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="class_max_capacity"><?php esc_html_e( 'Max Capacity', 'martial-arts-club-manager' ); ?></label>
						</th>
						<td>
							<input type="number"
									id="class_max_capacity"
									name="max_capacity"
									min="1"
									value="<?php echo ( $class && isset( $class->max_capacity ) ) ? esc_attr( $class->max_capacity ) : ''; ?>">
							<p class="description"><?php esc_html_e( 'Maximum number of members (leave blank for unlimited)', 'martial-arts-club-manager' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="class_sort_order"><?php esc_html_e( 'Sort Order', 'martial-arts-club-manager' ); ?></label>
						</th>
						<td>
							<input type="number"
									id="class_sort_order"
									name="sort_order"
									value="<?php echo $class ? esc_attr( $class->sort_order ) : '0'; ?>">
							<p class="description"><?php esc_html_e( 'Display order (lower numbers appear first)', 'martial-arts-club-manager' ); ?></p>
						</td>
					</tr>
				<tr>
					<th scope="row">
						<label for="class_instructors"><?php esc_html_e( 'Instructors', 'martial-arts-club-manager' ); ?></label>
					</th>
					<td>
						<select id="class_instructors" name="instructor_ids[]" multiple size="5" style="width: 100%; max-width: 400px;">
							<?php foreach ( $all_instructors as $instructor ) : ?>
								<option value="<?php echo esc_attr( $instructor->id ); ?>" <?php selected( in_array( $instructor->id, $assigned_instructor_ids, true ), true ); ?>>
									<?php echo esc_html( $instructor->full_name ); ?>
								</option>
							<?php endforeach; ?>
						</select>
						<?php if ( empty( $all_instructors ) ) : ?>
							<p class="description" style="color: #d63638;">
								<?php esc_html_e( 'No instructors available.', 'martial-arts-club-manager' ); ?>
								<a href="<?php echo esc_url( admin_url( 'admin.php?page=kcm-instructors' ) ); ?>"><?php esc_html_e( 'Add an instructor first', 'martial-arts-club-manager' ); ?></a>
							</p>
						<?php else : ?>
							<p class="description"><?php esc_html_e( 'Hold Ctrl (Cmd on Mac) to select multiple instructors', 'martial-arts-club-manager' ); ?></p>
						<?php endif; ?>
					</td>
				</tr>
				</table>

				<p class="submit">
					<input type="submit" class="button button-primary" value="<?php echo $class ? esc_attr__( 'Update Class', 'martial-arts-club-manager' ) : esc_attr__( 'Add Class', 'martial-arts-club-manager' ); ?>">
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=kcm-classes' ) ); ?>" class="button"><?php esc_html_e( 'Cancel', 'martial-arts-club-manager' ); ?></a>
				</p>
			</form>
		</div>
		<?php
	}

	/**
	 * Render the enrollments page
	 *
	 * @since 1.0.0
	 */
	public function render_enrollments_page() {
		// Check permissions.
		if ( ! current_user_can( 'manage_macm_classes' ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'martial-arts-club-manager' ) );
		}

		// Get and validate class_id.
		$class_id = isset( $_GET['class_id'] ) ? absint( wp_unslash( $_GET['class_id'] ) ) : 0;
		if ( ! $class_id ) {
			wp_die( esc_html__( 'Class ID is required.', 'martial-arts-club-manager' ) );
		}

		// Default filter status.
		$filter_status = 'active';

		// Check if this is a filter form submission (has filter nonce).
		if ( isset( $_GET['_wpnonce'] ) && isset( $_GET['filter_status'] ) ) {
			// Verify filter form nonce.
			if ( wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'macm_filter_enrollments_' . $class_id ) ) {
				$filter_status = sanitize_text_field( wp_unslash( $_GET['filter_status'] ) );
			}
		} elseif ( isset( $_GET['_wpnonce'] ) ) {
			// Initial page load from classes list - verify view enrollments nonce.
			if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'macm_view_enrollments_' . $class_id ) ) {
				wp_die( esc_html__( 'Security check failed. Please try again.', 'martial-arts-club-manager' ) );
			}
		} else {
			// No nonce at all - security check failed.
			wp_die( esc_html__( 'Security check failed. Please try again.', 'martial-arts-club-manager' ) );
		}

		$class = MACM_Class::get( $class_id );
		if ( ! $class ) {
			wp_die( esc_html__( 'Class not found.', 'martial-arts-club-manager' ) );
		}

		// Get location.
		$location = MACM_Location::get( $class->location_id );

		// Get all members with status filter.
		global $wpdb;
		$members_table = $wpdb->prefix . 'macm_members';

		// Build query with status filter.
		if ( 'all' !== $filter_status ) {
			$all_members = $wpdb->get_results(
				$wpdb->prepare(
					'SELECT * FROM %i WHERE status = %s ORDER BY full_name ASC',
					$members_table,
					$filter_status
				)
			);
		} else {
			$all_members = $wpdb->get_results(
				$wpdb->prepare(
					'SELECT * FROM %i ORDER BY full_name ASC',
					$members_table
				)
			);
		}

		// Get enrolled members.
		$enrolled_members = MACM_Class::get_enrolled_members( $class_id, true );
		$enrolled_ids     = array();
		foreach ( $enrolled_members as $enrollment ) {
			$enrolled_ids[] = $enrollment->member_id;
		}

		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Class Enrollments', 'martial-arts-club-manager' ); ?></h1>

			<div class="card" style="max-width: 800px; margin: 20px 0;">
				<h2><?php echo esc_html( $class->class_name ); ?></h2>
				<p>
					<strong><?php esc_html_e( 'Day:', 'martial-arts-club-manager' ); ?></strong>
					<?php echo esc_html( MACM_Class::get_day_name( $class->day_of_week ) ); ?>
					&nbsp;&nbsp;
					<strong><?php esc_html_e( 'Time:', 'martial-arts-club-manager' ); ?></strong>
					<?php echo esc_html( MACM_Class::format_time_range( $class->start_time, $class->end_time ) ); ?>
					&nbsp;&nbsp;
					<strong><?php esc_html_e( 'Location:', 'martial-arts-club-manager' ); ?></strong>
					<?php echo $location ? esc_html( $location->location_name ) : esc_html__( 'Unknown', 'martial-arts-club-manager' ); ?>
				</p>
				<p>
					<strong><?php esc_html_e( 'Currently Enrolled:', 'martial-arts-club-manager' ); ?></strong>
					<?php echo esc_html( count( $enrolled_ids ) ); ?>
					<?php if ( $class->max_capacity ) : ?>
						/ <?php echo esc_html( $class->max_capacity ); ?>
					<?php endif; ?>
				</p>
			</div>

			<!-- View Enrolled Members Button -->
			<div style="margin: 20px 0;">
				<button type="button" class="button button-secondary" id="view-enrolled-btn">
					<span class="dashicons dashicons-groups" style="vertical-align: middle; margin-top: 3px;"></span>
					<?php esc_html_e( 'View Enrolled Members', 'martial-arts-club-manager' ); ?>
				</button>
				<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=macm_export_class_enrollments&class_id=' . $class_id ), 'macm_export_class_enrollments_' . $class_id ) ); ?>"
					class="button button-secondary">
					<span class="dashicons dashicons-download" style="vertical-align: middle; margin-top: 3px;"></span>
					<?php esc_html_e( 'Export Enrolled Members CSV', 'martial-arts-club-manager' ); ?>
				</a>
			</div>

			<!-- Status Filter -->
			<div class="tablenav top" style="margin-bottom: 20px;">
				<div class="alignleft actions">
					<form method="get" action="">
						<input type="hidden" name="page" value="kcm-class-enrollments">
						<input type="hidden" name="class_id" value="<?php echo esc_attr( $class_id ); ?>">
						<?php wp_nonce_field( 'macm_filter_enrollments_' . $class_id, '_wpnonce', false ); ?>

						<select name="filter_status" id="filter-status">
							<option value="active" <?php selected( $filter_status, 'active' ); ?>><?php esc_html_e( 'Active Members', 'martial-arts-club-manager' ); ?></option>
							<option value="inactive" <?php selected( $filter_status, 'inactive' ); ?>><?php esc_html_e( 'Archived Members', 'martial-arts-club-manager' ); ?></option>
							<option value="all" <?php selected( $filter_status, 'all' ); ?>><?php esc_html_e( 'All Members', 'martial-arts-club-manager' ); ?></option>
						</select>

						<input type="submit" class="button" value="<?php esc_attr_e( 'Filter', 'martial-arts-club-manager' ); ?>">

						<?php if ( 'active' !== $filter_status ) : ?>
							<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=kcm-class-enrollments&class_id=' . $class_id ), 'macm_view_enrollments_' . $class_id ) ); ?>" class="button">
								<?php esc_html_e( 'Reset Filter', 'martial-arts-club-manager' ); ?>
							</a>
						<?php endif; ?>
					</form>
				</div>
			</div>

			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
				<?php wp_nonce_field( 'macm_save_enrollments', 'macm_enrollments_nonce' ); ?>
				<input type="hidden" name="action" value="macm_save_enrollments">
				<input type="hidden" name="class_id" value="<?php echo esc_attr( $class_id ); ?>">

				<h2><?php esc_html_e( 'Manage Enrollments', 'martial-arts-club-manager' ); ?></h2>
				<p class="description">
					<?php esc_html_e( 'Check the members you want enrolled in this class. Unchecked members will be removed.', 'martial-arts-club-manager' ); ?>
				</p>

				<div style="margin: 20px 0;">
					<button type="button" class="button" id="select-all-members"><?php esc_html_e( 'Select All', 'martial-arts-club-manager' ); ?></button>
					<button type="button" class="button" id="deselect-all-members"><?php esc_html_e( 'Deselect All', 'martial-arts-club-manager' ); ?></button>
				</div>

				<?php if ( ! empty( $all_members ) ) : ?>
					<table class="wp-list-table widefat fixed striped macm-enrollment-table">
						<thead>
							<tr>
								<th scope="col" class="check-column" style="width: 50px;">
									<input type="checkbox" id="member-select-all">
								</th>
								<th scope="col" style="width: 40%;"><?php esc_html_e( 'Member Name', 'martial-arts-club-manager' ); ?></th>
								<th scope="col" style="width: 20%;"><?php esc_html_e( 'Belt Color', 'martial-arts-club-manager' ); ?></th>
								<th scope="col" style="width: 20%;"><?php esc_html_e( 'Age', 'martial-arts-club-manager' ); ?></th>
								<th scope="col" style="width: 20%;"><?php esc_html_e( 'Status', 'martial-arts-club-manager' ); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ( $all_members as $member ) : ?>
								<?php
								$is_enrolled = in_array( $member->id, $enrolled_ids, true );
								$age         = MACM_Member::calculate_age( $member->date_of_birth );
								?>
								<tr>
									<td class="check-column">
										<input type="checkbox"
												name="member_ids[]"
												value="<?php echo esc_attr( $member->id ); ?>"
												class="member-checkbox"
												<?php checked( $is_enrolled ); ?>>
									</td>
									<td>
										<strong><?php echo esc_html( $member->full_name ); ?></strong>
									</td>
									<td>
										<?php echo esc_html( $member->belt_color ); ?>
									</td>
									<td>
										<?php echo esc_html( $age ); ?> <?php esc_html_e( 'years', 'martial-arts-club-manager' ); ?>
									</td>
									<td>
										<?php if ( $is_enrolled ) : ?>
											<span class="kcm-badge kcm-badge-success"><?php esc_html_e( 'Enrolled', 'martial-arts-club-manager' ); ?></span>
										<?php else : ?>
											<span class="kcm-badge kcm-badge-inactive"><?php esc_html_e( 'Not Enrolled', 'martial-arts-club-manager' ); ?></span>
										<?php endif; ?>
									</td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
				<?php else : ?>
					<div class="notice notice-warning">
						<p>
							<?php esc_html_e( 'No members available to enroll.', 'martial-arts-club-manager' ); ?>
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=martial-arts-club-manager' ) ); ?>"><?php esc_html_e( 'Add members first', 'martial-arts-club-manager' ); ?></a>
						</p>
					</div>
				<?php endif; ?>

				<p class="submit">
					<input type="submit" class="button button-primary" value="<?php esc_attr_e( 'Save Enrollments', 'martial-arts-club-manager' ); ?>">
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=kcm-classes' ) ); ?>" class="button"><?php esc_html_e( 'Cancel', 'martial-arts-club-manager' ); ?></a>
				</p>
			</form>
		</div>

		<!-- Enrolled Members Modal -->
		<div id="enrolled-members-modal" style="display: none;">
			<div class="kcm-modal-overlay">
				<div class="kcm-modal-content">
					<div class="kcm-modal-header">
						<h2><?php esc_html_e( 'Enrolled Members', 'martial-arts-club-manager' ); ?></h2>
						<button type="button" class="kcm-modal-close">&times;</button>
					</div>
					<div class="kcm-modal-body">
						<div class="class-info-summary" style="background: #F4F4F2; padding: 15px; border-radius: 4px; margin-bottom: 20px;">
							<h3 style="margin-top: 0;"><?php echo esc_html( $class->class_name ); ?></h3>
							<p style="margin: 5px 0;">
								<strong><?php esc_html_e( 'Day:', 'martial-arts-club-manager' ); ?></strong>
								<?php echo esc_html( MACM_Class::get_day_name( $class->day_of_week ) ); ?>
								&nbsp;&nbsp;
								<strong><?php esc_html_e( 'Time:', 'martial-arts-club-manager' ); ?></strong>
								<?php echo esc_html( MACM_Class::format_time_range( $class->start_time, $class->end_time ) ); ?>
								&nbsp;&nbsp;
								<strong><?php esc_html_e( 'Location:', 'martial-arts-club-manager' ); ?></strong>
								<?php echo $location ? esc_html( $location->location_name ) : esc_html__( 'Unknown', 'martial-arts-club-manager' ); ?>
							</p>
							<p style="margin: 5px 0;">
								<strong><?php esc_html_e( 'Total Enrolled:', 'martial-arts-club-manager' ); ?></strong>
								<?php echo esc_html( count( $enrolled_ids ) ); ?>
								<?php if ( $class->max_capacity ) : ?>
									/ <?php echo esc_html( $class->max_capacity ); ?>
								<?php endif; ?>
							</p>
						</div>

						<?php if ( ! empty( $enrolled_members ) ) : ?>
							<table class="wp-list-table widefat fixed striped">
								<thead>
									<tr>
										<th scope="col"><?php esc_html_e( 'Member Name', 'martial-arts-club-manager' ); ?></th>
										<th scope="col"><?php esc_html_e( 'Belt Color', 'martial-arts-club-manager' ); ?></th>
										<th scope="col"><?php esc_html_e( 'Age', 'martial-arts-club-manager' ); ?></th>
										<th scope="col"><?php esc_html_e( 'Enrolled Date', 'martial-arts-club-manager' ); ?></th>
									</tr>
								</thead>
								<tbody>
									<?php foreach ( $enrolled_members as $enrollment ) : ?>
										<?php
										$member = MACM_Member::get( $enrollment->member_id );
										if ( ! $member ) {
											continue;
										}
										$age           = MACM_Member::calculate_age( $member->date_of_birth );
										$enrolled_date = date_i18n( get_option( 'date_format' ), strtotime( $enrollment->enrolled_at ) );
										?>
										<tr>
											<td><strong><?php echo esc_html( $member->full_name ); ?></strong></td>
											<td><?php echo esc_html( $member->belt_color ); ?></td>
											<td><?php echo esc_html( $age ); ?> <?php esc_html_e( 'years', 'martial-arts-club-manager' ); ?></td>
											<td><?php echo esc_html( $enrolled_date ); ?></td>
										</tr>
									<?php endforeach; ?>
								</tbody>
							</table>
						<?php else : ?>
							<p><?php esc_html_e( 'No members currently enrolled in this class.', 'martial-arts-club-manager' ); ?></p>
						<?php endif; ?>
					</div>
					<div class="kcm-modal-footer">
						<button type="button" class="button button-secondary kcm-modal-close"><?php esc_html_e( 'Close', 'martial-arts-club-manager' ); ?></button>
						<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=macm_export_class_enrollments&class_id=' . $class_id ), 'macm_export_class_enrollments_' . $class_id ) ); ?>"
							class="button button-primary">
							<span class="dashicons dashicons-download" style="vertical-align: middle; margin-top: 3px;"></span>
							<?php esc_html_e( 'Export as CSV', 'martial-arts-club-manager' ); ?>
						</a>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Save class
	 *
	 * @since 1.0.0
	 */
	public function save_class() {
		// Verify nonce.
		check_admin_referer( 'macm_save_class', 'macm_class_nonce' );

		// Check permissions.
		if ( ! current_user_can( 'manage_macm_classes' ) ) {
			wp_die( esc_html__( 'Permission denied', 'martial-arts-club-manager' ) );
		}

		// Get and sanitize data.
		$class_id = isset( $_POST['class_id'] ) ? absint( wp_unslash( $_POST['class_id'] ) ) : 0;
		$data     = array(
			'name'         => isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '',
			'location_id'  => isset( $_POST['location_id'] ) ? absint( wp_unslash( $_POST['location_id'] ) ) : 0,
			'day_of_week'  => isset( $_POST['day_of_week'] ) ? absint( wp_unslash( $_POST['day_of_week'] ) ) : 0,
			'start_time'   => isset( $_POST['start_time'] ) ? sanitize_text_field( wp_unslash( $_POST['start_time'] ) ) . ':00' : '',
			'end_time'     => isset( $_POST['end_time'] ) ? sanitize_text_field( wp_unslash( $_POST['end_time'] ) ) . ':00' : '',
			'description'  => isset( $_POST['description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['description'] ) ) : '',
			'max_capacity' => isset( $_POST['max_capacity'] ) && '' !== $_POST['max_capacity'] ? absint( wp_unslash( $_POST['max_capacity'] ) ) : null,
			'sort_order'   => isset( $_POST['sort_order'] ) ? absint( wp_unslash( $_POST['sort_order'] ) ) : 0,
		);

		// Save or update.
		if ( $class_id ) {
			$result         = MACM_Class::update( $class_id, $data );
			$saved_class_id = $class_id;
		} else {
			$result         = MACM_Class::create( $data );
			$saved_class_id = $result;
		}

		// Update instructor assignments if class was saved successfully.
		if ( ! is_wp_error( $result ) ) {
			$instructor_ids = isset( $_POST['instructor_ids'] ) && is_array( $_POST['instructor_ids'] ) ? array_map( 'absint', wp_unslash( $_POST['instructor_ids'] ) ) : array();
			MACM_Instructor::update_class_instructors( $saved_class_id, $instructor_ids );
		}

		// Redirect with message.
		if ( is_wp_error( $result ) ) {
			$redirect = add_query_arg(
				array(
					'page'  => 'kcm-classes',
					'error' => urlencode( $result->get_error_message() ),
				),
				admin_url( 'admin.php' )
			);
		} else {
			$redirect = add_query_arg(
				array(
					'page'    => 'kcm-classes',
					'message' => 'saved',
				),
				admin_url( 'admin.php' )
			);
		}

		wp_safe_redirect( $redirect );
		exit;
	}

	/**
	 * Archive class
	 *
	 * @since 1.0.0
	 */
	public function archive_class() {
		$class_id = isset( $_GET['class_id'] ) ? absint( wp_unslash( $_GET['class_id'] ) ) : 0;
		check_admin_referer( 'macm_archive_class_' . $class_id );

		if ( ! current_user_can( 'manage_macm_classes' ) ) {
			wp_die( esc_html__( 'Permission denied', 'martial-arts-club-manager' ) );
		}

		$result = MACM_Class::archive( $class_id );

		if ( is_wp_error( $result ) ) {
			$redirect = add_query_arg(
				array(
					'page'  => 'kcm-classes',
					'error' => urlencode( $result->get_error_message() ),
				),
				admin_url( 'admin.php' )
			);
		} else {
			$redirect = add_query_arg(
				array(
					'page'    => 'kcm-classes',
					'message' => 'archived',
				),
				admin_url( 'admin.php' )
			);
		}

		wp_safe_redirect( $redirect );
		exit;
	}

	/**
	 * Unarchive class
	 *
	 * @since 1.0.0
	 */
	public function unarchive_class() {
		$class_id = isset( $_GET['class_id'] ) ? absint( wp_unslash( $_GET['class_id'] ) ) : 0;
		check_admin_referer( 'macm_unarchive_class_' . $class_id );

		if ( ! current_user_can( 'manage_macm_classes' ) ) {
			wp_die( esc_html__( 'Permission denied', 'martial-arts-club-manager' ) );
		}

		$result = MACM_Class::unarchive( $class_id );

		if ( is_wp_error( $result ) ) {
			$redirect = add_query_arg(
				array(
					'page'  => 'kcm-classes',
					'error' => urlencode( $result->get_error_message() ),
				),
				admin_url( 'admin.php' )
			);
		} else {
			$redirect = add_query_arg(
				array(
					'page'    => 'kcm-classes',
					'message' => 'unarchived',
				),
				admin_url( 'admin.php' )
			);
		}

		wp_safe_redirect( $redirect );
		exit;
	}

	/**
	 * Delete class
	 *
	 * @since 1.0.0
	 */
	public function delete_class() {
		$class_id = isset( $_GET['class_id'] ) ? absint( wp_unslash( $_GET['class_id'] ) ) : 0;
		check_admin_referer( 'macm_delete_class_' . $class_id );

		if ( ! current_user_can( 'manage_macm_classes' ) ) {
			wp_die( esc_html__( 'Permission denied', 'martial-arts-club-manager' ) );
		}

		$result = MACM_Class::delete( $class_id );

		if ( is_wp_error( $result ) ) {
			$redirect = add_query_arg(
				array(
					'page'  => 'kcm-classes',
					'error' => urlencode( $result->get_error_message() ),
				),
				admin_url( 'admin.php' )
			);
		} else {
			$redirect = add_query_arg(
				array(
					'page'    => 'kcm-classes',
					'message' => 'deleted',
				),
				admin_url( 'admin.php' )
			);
		}

		wp_safe_redirect( $redirect );
		exit;
	}

	/**
	 * Save enrollments
	 *
	 * @since 1.0.0
	 */
	public function save_enrollments() {
		// Verify nonce.
		check_admin_referer( 'macm_save_enrollments', 'macm_enrollments_nonce' );

		// Check permissions.
		if ( ! current_user_can( 'manage_macm_classes' ) ) {
			wp_die( esc_html__( 'Permission denied', 'martial-arts-club-manager' ) );
		}

		$class_id   = isset( $_POST['class_id'] ) ? absint( wp_unslash( $_POST['class_id'] ) ) : 0;
		$member_ids = isset( $_POST['member_ids'] ) && is_array( $_POST['member_ids'] ) ? array_map( 'absint', wp_unslash( $_POST['member_ids'] ) ) : array();

		// Get currently enrolled members.
		$currently_enrolled     = MACM_Class::get_enrolled_members( $class_id, true );
		$currently_enrolled_ids = array();
		foreach ( $currently_enrolled as $enrollment ) {
			$currently_enrolled_ids[] = $enrollment->member_id;
		}

		// Find members to add (in new list but not in current).
		$to_add = array_diff( $member_ids, $currently_enrolled_ids );

		// Find members to remove (in current but not in new list).
		$to_remove = array_diff( $currently_enrolled_ids, $member_ids );

		// Add new enrollments.
		if ( ! empty( $to_add ) ) {
			MACM_Class::enroll_members( $class_id, $to_add );
		}

		// Remove enrollments.
		foreach ( $to_remove as $member_id ) {
			MACM_Class::remove_member( $class_id, $member_id );
		}

		// Redirect with message.
		$redirect = add_query_arg(
			array(
				'page'    => 'kcm-classes',
				'message' => 'enrollments_saved',
			),
			admin_url( 'admin.php' )
		);

		wp_safe_redirect( $redirect );
		exit;
	}

	/**
	 * Export class enrollments as CSV
	 *
	 * @since 1.0.74
	 */
	public function export_class_enrollments() {
		// Check permissions.
		if ( ! current_user_can( 'manage_macm_classes' ) ) {
			wp_die( esc_html__( 'Permission denied', 'martial-arts-club-manager' ) );
		}

		// Get class ID.
		$class_id = isset( $_GET['class_id'] ) ? absint( wp_unslash( $_GET['class_id'] ) ) : 0;

		// Verify nonce.
		check_admin_referer( 'macm_export_class_enrollments_' . $class_id );

		// Get class.
		$class = MACM_Class::get( $class_id );
		if ( ! $class ) {
			wp_die( esc_html__( 'Class not found.', 'martial-arts-club-manager' ) );
		}

		// Get location.
		$location      = MACM_Location::get( $class->location_id );
		$location_name = $location ? $location->location_name : __( 'Unknown', 'martial-arts-club-manager' );

		// Get enrolled members.
		$enrolled_members = MACM_Class::get_enrolled_members( $class_id, true );

		// Clean any existing output.
		if ( ob_get_length() ) {
			ob_end_clean();
		}

		// Set headers for CSV download.
		$filename = sanitize_file_name( 'class-enrollments-' . $class->class_name . '-' . wp_date( 'Y-m-d' ) . '.csv' );
		header( 'Content-Type: text/csv; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
		header( 'Pragma: no-cache' );
		header( 'Expires: 0' );

		// Disable caching.
		nocache_headers();

		// Open output stream.
		$output = fopen( 'php://output', 'w' );

		// Add UTF-8 BOM for proper Excel encoding.
		fprintf( $output, chr( 0xEF ) . chr( 0xBB ) . chr( 0xBF ) );

		// Write class information header.
		fputcsv( $output, array( __( 'Class Information', 'martial-arts-club-manager' ) ) );
		fputcsv( $output, array( __( 'Class Name:', 'martial-arts-club-manager' ), $class->class_name ) );
		fputcsv( $output, array( __( 'Day:', 'martial-arts-club-manager' ), MACM_Class::get_day_name( $class->day_of_week ) ) );
		fputcsv( $output, array( __( 'Time:', 'martial-arts-club-manager' ), MACM_Class::format_time_range( $class->start_time, $class->end_time ) ) );
		fputcsv( $output, array( __( 'Location:', 'martial-arts-club-manager' ), $location_name ) );
		fputcsv( $output, array( __( 'Total Enrolled:', 'martial-arts-club-manager' ), count( $enrolled_members ) ) );
		if ( $class->max_capacity ) {
			fputcsv( $output, array( __( 'Max Capacity:', 'martial-arts-club-manager' ), $class->max_capacity ) );
		}
		fputcsv( $output, array( __( 'Export Date:', 'martial-arts-club-manager' ), date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) ) ) );
		fputcsv( $output, array() ); // Empty line.

		// Write column headers for members.
		fputcsv(
			$output,
			array(
				__( 'Member Name', 'martial-arts-club-manager' ),
				__( 'Date of Birth', 'martial-arts-club-manager' ),
				__( 'Age', 'martial-arts-club-manager' ),
				__( 'Belt Color', 'martial-arts-club-manager' ),
				__( 'Weight (kg)', 'martial-arts-club-manager' ),
				__( 'Height (cm)', 'martial-arts-club-manager' ),
				__( 'Group', 'martial-arts-club-manager' ),
				__( 'Membership Type', 'martial-arts-club-manager' ),
				__( 'Enrolled Date', 'martial-arts-club-manager' ),
				__( 'Member Status', 'martial-arts-club-manager' ),
			)
		);

		// Write member data.
		if ( ! empty( $enrolled_members ) ) {
			foreach ( $enrolled_members as $enrollment ) {
				$member = MACM_Member::get( $enrollment->member_id );
				if ( ! $member ) {
					continue;
				}

				$age           = MACM_Member::calculate_age( $member->date_of_birth );
				$dob_formatted = $member->date_of_birth ? date_i18n( get_option( 'date_format' ), strtotime( $member->date_of_birth ) ) : '';
				$enrolled_date = date_i18n( get_option( 'date_format' ), strtotime( $enrollment->enrolled_at ) );
				$member_status = 'active' === $member->status ? __( 'Active', 'martial-arts-club-manager' ) : __( 'Archived', 'martial-arts-club-manager' );

				fputcsv(
					$output,
					array(
						$member->full_name,
						$dob_formatted,
						$age,
						$member->belt_color,
						$member->weight,
						$member->height,
						$member->group_name,
						$member->membership_type_name,
						$enrolled_date,
						$member_status,
					)
				);
			}
		}

		// Stream closes automatically on exit - no explicit fclose needed for php://output.
		exit;
	}
}

// Initialize.
new MACM_Admin_Classes();
