<?php

/**
 * Admin menu management
 *
 * @package KarateClubManager
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * Admin menu class
 */
class MACM_Admin_Menu {
    /**
     * Constructor
     */
    public function __construct() {
        add_action( 'admin_menu', array($this, 'add_menu_pages') );
        add_action( 'admin_menu', array($this, 'add_settings_page'), 22 );
        add_action( 'admin_enqueue_scripts', array($this, 'enqueue_dashboard_assets') );
    }

    /**
     * Enqueue dashboard-specific assets
     *
     * @param string $hook Current admin page hook.
     */
    public function enqueue_dashboard_assets( $hook ) {
        // Only load on dashboard page.
        if ( 'toplevel_page_martial-arts-club-manager' !== $hook ) {
            return;
        }
        // Enqueue dashboard CSS.
        wp_enqueue_style(
            'kcm-admin-dashboard',
            MACM_PLUGIN_URL . 'assets/css/admin-dashboard.css',
            array('kcm-admin-styles'),
            MACM_VERSION,
            'all'
        );
        // Enqueue Chart.js for dashboard charts (local copy for WordPress.org compliance).
        wp_enqueue_script(
            'chart-js',
            MACM_PLUGIN_URL . 'assets/js/vendor/chart.umd.min.js',
            array(),
            '4.5.1',
            true
        );
    }

    /**
     * Add menu pages
     */
    public function add_menu_pages() {
        // Main menu.
        add_menu_page(
            __( 'Martial Arts', 'martial-arts-club-manager' ),
            __( 'Martial Arts', 'martial-arts-club-manager' ),
            'manage_macm_members',
            'martial-arts-club-manager',
            array($this, 'dashboard_page'),
            'dashicons-groups',
            30
        );
        // Dashboard (same as parent).
        add_submenu_page(
            'martial-arts-club-manager',
            __( 'Dashboard', 'martial-arts-club-manager' ),
            __( 'Dashboard', 'martial-arts-club-manager' ),
            'manage_macm_members',
            'martial-arts-club-manager',
            array($this, 'dashboard_page')
        );
        // Members (position 15).
        add_submenu_page(
            'martial-arts-club-manager',
            __( 'Members', 'martial-arts-club-manager' ),
            __( 'Members', 'martial-arts-club-manager' ),
            'manage_macm_members',
            'kcm-members',
            array($this, 'members_page'),
            15
        );
        // Note: Other submenu pages are registered by their respective admin classes with specific priorities:
        // Belt Colors (11), Membership Types (12), Clubs (13), Groups (14), Members (15),
        // Locations (16), Classes (17), Attendance (18), License Reminders (19), Training Videos (19),
        // Page Access Control (20), Send Email (21), Settings (22).
    }

    /**
     * Add settings page (runs at priority 22 to appear last in menu)
     */
    public function add_settings_page() {
        // Settings (position 22).
        add_submenu_page(
            'martial-arts-club-manager',
            __( 'Settings', 'martial-arts-club-manager' ),
            __( 'Settings', 'martial-arts-club-manager' ),
            'manage_macm_settings',
            'kcm-settings',
            array($this, 'settings_page')
        );
    }

    /**
     * Dashboard page
     */
    public function dashboard_page() {
        if ( !current_user_can( 'manage_macm_members' ) ) {
            wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'martial-arts-club-manager' ) );
        }
        global $wpdb;
        // Get statistics with caching.
        $stats_cache_key = 'macm_dashboard_stats';
        $stats = wp_cache_get( $stats_cache_key, 'macm' );
        if ( false === $stats ) {
            $stats = array(
                'total_members'     => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}macm_members" ),
                'total_classes'     => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}macm_classes WHERE is_archived = 0" ),
                'total_locations'   => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}macm_locations" ),
                'total_groups'      => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}macm_groups" ),
                'total_attendance'  => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}macm_attendance WHERE MONTH(attendance_date) = MONTH(CURRENT_DATE()) AND YEAR(attendance_date) = YEAR(CURRENT_DATE())" ),
                'total_enrollments' => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}macm_class_enrollments" ),
            );
            wp_cache_set(
                $stats_cache_key,
                $stats,
                'macm',
                60
            );
        }
        $total_members = $stats['total_members'];
        $total_classes = $stats['total_classes'];
        $total_locations = $stats['total_locations'];
        $total_groups = $stats['total_groups'];
        $total_attendance = $stats['total_attendance'];
        $total_enrollments = $stats['total_enrollments'];
        // Get membership type counts with caching.
        $membership_cache_key = 'macm_dashboard_membership_counts';
        $membership_counts = wp_cache_get( $membership_cache_key, 'macm' );
        if ( false === $membership_counts ) {
            $membership_counts = $wpdb->get_results( "SELECT mt.type_name, COUNT(m.id) as count\n\t\t\t\tFROM {$wpdb->prefix}macm_membership_types mt\n\t\t\t\tLEFT JOIN {$wpdb->prefix}macm_members m ON m.membership_type_id = mt.id\n\t\t\t\tWHERE mt.is_active = 1\n\t\t\t\tGROUP BY mt.id, mt.type_name" );
            wp_cache_set(
                $membership_cache_key,
                $membership_counts,
                'macm',
                60
            );
        }
        $premium_members = 0;
        $basic_members = 0;
        foreach ( $membership_counts as $mc ) {
            if ( 'premium' === strtolower( $mc->type_name ) ) {
                $premium_members = $mc->count;
            } elseif ( 'basic' === strtolower( $mc->type_name ) ) {
                $basic_members = $mc->count;
            }
        }
        // Get recent members with caching.
        $recent_members_cache_key = 'macm_dashboard_recent_members';
        $recent_members = wp_cache_get( $recent_members_cache_key, 'macm' );
        if ( false === $recent_members ) {
            $recent_members = $wpdb->get_results( "SELECT m.*, u.display_name as user_display_name\n\t\t\t\tFROM {$wpdb->prefix}macm_members m\n\t\t\t\tLEFT JOIN {$wpdb->users} u ON m.user_id = u.ID\n\t\t\t\tORDER BY m.created_at DESC\n\t\t\t\tLIMIT 5" );
            wp_cache_set(
                $recent_members_cache_key,
                $recent_members,
                'macm',
                60
            );
        }
        // Get recent attendance with caching.
        $recent_attendance_cache_key = 'macm_dashboard_recent_attendance';
        $recent_attendance = wp_cache_get( $recent_attendance_cache_key, 'macm' );
        if ( false === $recent_attendance ) {
            $recent_attendance = $wpdb->get_results( "SELECT a.*, m.full_name as member_name, c.class_name\n\t\t\t\tFROM {$wpdb->prefix}macm_attendance a\n\t\t\t\tLEFT JOIN {$wpdb->prefix}macm_members m ON a.member_id = m.id\n\t\t\t\tLEFT JOIN {$wpdb->prefix}macm_classes c ON a.class_id = c.id\n\t\t\t\tORDER BY a.attendance_date DESC\n\t\t\t\tLIMIT 10" );
            wp_cache_set(
                $recent_attendance_cache_key,
                $recent_attendance,
                'macm',
                60
            );
        }
        // Get recent trial bookings with caching.
        $bookings_cache_key = 'macm_dashboard_recent_bookings';
        $recent_trial_bookings = wp_cache_get( $bookings_cache_key, 'macm' );
        if ( false === $recent_trial_bookings ) {
            $recent_trial_bookings = $wpdb->get_results( "SELECT *\n\t\t\t\tFROM {$wpdb->prefix}macm_trial_bookings\n\t\t\t\tORDER BY created_at DESC\n\t\t\t\tLIMIT 5" );
            wp_cache_set(
                $bookings_cache_key,
                $recent_trial_bookings,
                'macm',
                60
            );
        }
        // PREMIUM: Get upcoming events with caching.
        $upcoming_events = array();
        // PREMIUM: Get members with expiring licenses with caching.
        $expiring_licenses = array();
        // Chart Data: Belt Distribution with caching.
        $belt_cache_key = 'macm_dashboard_belt_distribution';
        $belt_distribution = wp_cache_get( $belt_cache_key, 'macm' );
        if ( false === $belt_distribution ) {
            $belt_distribution = $wpdb->get_results( "SELECT bc.color_name, bc.color_key, COUNT(m.id) as count\n\t\t\t\tFROM {$wpdb->prefix}macm_belt_colors bc\n\t\t\t\tLEFT JOIN {$wpdb->prefix}macm_members m ON m.belt_color = bc.color_key\n\t\t\t\tWHERE bc.is_active = 1\n\t\t\t\tGROUP BY bc.id, bc.color_name, bc.color_key\n\t\t\t\tORDER BY bc.sort_order ASC" );
            wp_cache_set(
                $belt_cache_key,
                $belt_distribution,
                'macm',
                60
            );
        }
        // Chart Data: Attendance Trends (last 6 months) with caching.
        $trends_cache_key = 'macm_dashboard_attendance_trends';
        $attendance_trends = wp_cache_get( $trends_cache_key, 'macm' );
        if ( false === $attendance_trends ) {
            $attendance_trends = $wpdb->get_results( "SELECT\n\t\t\t\t\tDATE_FORMAT(attendance_date, '%Y-%m') as month,\n\t\t\t\t\tDATE_FORMAT(attendance_date, '%b %Y') as month_label,\n\t\t\t\t\tCOUNT(*) as count\n\t\t\t\tFROM {$wpdb->prefix}macm_attendance\n\t\t\t\tWHERE attendance_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)\n\t\t\t\tGROUP BY DATE_FORMAT(attendance_date, '%Y-%m')\n\t\t\t\tORDER BY month ASC" );
            wp_cache_set(
                $trends_cache_key,
                $attendance_trends,
                'macm',
                60
            );
        }
        // Chart Data: Membership Type Distribution with caching.
        $dist_cache_key = 'macm_dashboard_membership_distribution';
        $membership_distribution = wp_cache_get( $dist_cache_key, 'macm' );
        if ( false === $membership_distribution ) {
            $membership_distribution = $wpdb->get_results( "SELECT mt.type_name, COUNT(m.id) as count\n\t\t\t\tFROM {$wpdb->prefix}macm_membership_types mt\n\t\t\t\tLEFT JOIN {$wpdb->prefix}macm_members m ON m.membership_type_id = mt.id\n\t\t\t\tWHERE mt.is_active = 1\n\t\t\t\tGROUP BY mt.id, mt.type_name\n\t\t\t\tORDER BY mt.type_name ASC" );
            wp_cache_set(
                $dist_cache_key,
                $membership_distribution,
                'macm',
                60
            );
        }
        include MACM_PLUGIN_DIR . 'templates/admin/dashboard.php';
    }

    /**
     * Members page
     */
    public function members_page() {
        if ( !current_user_can( 'manage_macm_members' ) ) {
            wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'martial-arts-club-manager' ) );
        }
        // Load the list table class.
        require_once MACM_PLUGIN_DIR . 'includes/admin/class-macm-admin-members-list-table.php';
        // Create list table instance.
        $list_table = new MACM_Admin_Members_List_Table();
        $list_table->prepare_items();
        // Get all members for the JavaScript data (for edit modal) with caching.
        global $wpdb;
        $members_cache_key = 'macm_admin_members_all';
        $members = wp_cache_get( $members_cache_key, 'macm' );
        if ( false === $members ) {
            $members = $wpdb->get_results( "SELECT m.*,\n\t\t\t\t\tu.display_name as user_name,\n\t\t\t\t\tu.user_email,\n\t\t\t\t\tc.club_name,\n\t\t\t\t\tmt.type_name as membership_type_name\n\t\t\t\tFROM {$wpdb->prefix}macm_members m\n\t\t\t\tLEFT JOIN {$wpdb->prefix}users u ON m.user_id = u.ID\n\t\t\t\tLEFT JOIN {$wpdb->prefix}macm_clubs c ON m.club_id = c.id\n\t\t\t\tLEFT JOIN {$wpdb->prefix}macm_membership_types mt ON m.membership_type_id = mt.id\n\t\t\t\tORDER BY m.created_at DESC" );
            wp_cache_set(
                $members_cache_key,
                $members,
                'macm',
                60
            );
        }
        // Add photo URLs for each member.
        foreach ( $members as $member ) {
            $member->photo_url = ( $member->photo_id ? wp_get_attachment_url( $member->photo_id ) : '' );
        }
        // Get groups for each member with caching.
        foreach ( $members as $member ) {
            $first_name = get_user_meta( $member->user_id, 'first_name', true );
            $last_name = get_user_meta( $member->user_id, 'last_name', true );
            if ( $first_name && $last_name ) {
                $member->user_full_name = $first_name . ' ' . $last_name;
            } elseif ( $first_name ) {
                $member->user_full_name = $first_name;
            } elseif ( $last_name ) {
                $member->user_full_name = $last_name;
            } else {
                $member->user_full_name = $member->user_name;
            }
            $group_cache_key = 'macm_member_groups_' . $member->id;
            $member->group_ids = wp_cache_get( $group_cache_key, 'macm' );
            if ( false === $member->group_ids ) {
                $member->group_ids = $wpdb->get_col( $wpdb->prepare( "SELECT group_id FROM {$wpdb->prefix}macm_member_groups WHERE member_id = %d", $member->id ) );
                wp_cache_set(
                    $group_cache_key,
                    $member->group_ids,
                    'macm',
                    300
                );
            }
        }
        $belt_colors = MACM_Member::get_belt_colors();
        // Unit system for weight/height labels.
        $macm_unit_system = get_option( 'macm_unit_system', 'metric' );
        $macm_weight_label = ( 'imperial' === $macm_unit_system ? __( 'Weight (lbs)', 'martial-arts-club-manager' ) : __( 'Weight (kg)', 'martial-arts-club-manager' ) );
        $macm_height_label = ( 'imperial' === $macm_unit_system ? __( 'Height (inches)', 'martial-arts-club-manager' ) : __( 'Height (cm)', 'martial-arts-club-manager' ) );
        $macm_weight_max = ( 'imperial' === $macm_unit_system ? 1100 : 500 );
        $macm_height_max = ( 'imperial' === $macm_unit_system ? 120 : 300 );
        // Get all users for user selection dropdown.
        $all_users = get_users( array(
            'orderby' => 'display_name',
            'order'   => 'ASC',
        ) );
        ?>
		<div class="wrap">
			<h1 class="wp-heading-inline"><?php 
        esc_html_e( 'Members', 'martial-arts-club-manager' );
        ?></h1>
			<a href="#" class="page-title-action" id="kcm-admin-add-member-btn"><?php 
        esc_html_e( 'Add New', 'martial-arts-club-manager' );
        ?></a>
			<hr class="wp-header-end">

			<form method="get" id="macm-members-bulk-form">
				<input type="hidden" name="page" value="kcm-members">
				<?php 
        wp_nonce_field( 'bulk-members', '_wpnonce', false );
        ?>
				<?php 
        $list_table->display();
        ?>
			</form>
		</div>

		<!-- Add Member Modal -->
		<div id="kcm-admin-add-member-modal" class="kcm-modal" style="display: none;">
			<div class="kcm-modal-content">
				<div class="kcm-modal-header">
					<h3><?php 
        esc_html_e( 'Add New Member', 'martial-arts-club-manager' );
        ?></h3>
					<button type="button" class="kcm-modal-close">&times;</button>
				</div>
				<div class="kcm-modal-body">
					<form id="kcm-admin-add-member-form">
						<div class="kcm-form-row">
							<label for="kcm-admin-add-user">
								<?php 
        esc_html_e( 'User Account', 'martial-arts-club-manager' );
        ?> <span class="required">*</span>
							</label>
							<select id="kcm-admin-add-user" name="user_id" required>
								<option value=""><?php 
        esc_html_e( 'Select User', 'martial-arts-club-manager' );
        ?></option>
								<?php 
        foreach ( $all_users as $user ) {
            ?>
									<?php 
            $user_display = $user->display_name;
            $first_name = get_user_meta( $user->ID, 'first_name', true );
            $last_name = get_user_meta( $user->ID, 'last_name', true );
            if ( $first_name && $last_name ) {
                $user_display = $first_name . ' ' . $last_name . ' (' . $user->user_email . ')';
            } else {
                $user_display .= ' (' . $user->user_email . ')';
            }
            ?>
									<option value="<?php 
            echo esc_attr( $user->ID );
            ?>">
										<?php 
            echo esc_html( $user_display );
            ?>
									</option>
								<?php 
        }
        ?>
							</select>
							<p class="description"><?php 
        esc_html_e( 'Select the WordPress user to associate this member with', 'martial-arts-club-manager' );
        ?></p>
						</div>

						<div class="kcm-form-row">
							<label for="kcm-admin-add-full-name">
								<?php 
        esc_html_e( 'Full Name', 'martial-arts-club-manager' );
        ?> <span class="required">*</span>
							</label>
							<input type="text" id="kcm-admin-add-full-name" name="full_name" required>
						</div>

						<div class="kcm-form-row">
							<label for="kcm-admin-add-date-of-birth">
								<?php 
        esc_html_e( 'Date of Birth', 'martial-arts-club-manager' );
        ?> <span class="required">*</span>
							</label>
							<input type="date" id="kcm-admin-add-date-of-birth" name="date_of_birth" required>
						</div>

						<div class="kcm-form-row">
							<label for="kcm-admin-add-belt-color">
								<?php 
        esc_html_e( 'Belt Color', 'martial-arts-club-manager' );
        ?> <span class="required">*</span>
							</label>
							<select id="kcm-admin-add-belt-color" name="belt_color" required>
								<option value=""><?php 
        esc_html_e( 'Select Belt Color', 'martial-arts-club-manager' );
        ?></option>
								<?php 
        foreach ( $belt_colors as $value => $label ) {
            ?>
									<option value="<?php 
            echo esc_attr( $value );
            ?>"><?php 
            echo esc_html( $label );
            ?></option>
								<?php 
        }
        ?>
							</select>
						</div>

						<div class="kcm-form-row">
							<label for="kcm-admin-add-membership-type">
								<?php 
        esc_html_e( 'Membership Type', 'martial-arts-club-manager' );
        ?>
							</label>
							<select id="kcm-admin-add-membership-type" name="membership_type_id">
								<option value=""><?php 
        esc_html_e( 'Not set', 'martial-arts-club-manager' );
        ?></option>
								<?php 
        $membership_types = MACM_Membership_Type::get_all();
        foreach ( $membership_types as $type ) {
            ?>
									<option value="<?php 
            echo esc_attr( $type->id );
            ?>"><?php 
            echo esc_html( $type->type_name );
            ?></option>
								<?php 
        }
        ?>
							</select>
						</div>

						<?php 
        if ( macm_fs()->can_use_premium_code() && class_exists( 'MACM_Club' ) ) {
            ?>
						<div class="kcm-form-row">
							<label for="kcm-admin-add-club"><?php 
            esc_html_e( 'Club', 'martial-arts-club-manager' );
            ?></label>
							<select id="kcm-admin-add-club" name="club_id">
								<option value=""><?php 
            esc_html_e( 'Not set', 'martial-arts-club-manager' );
            ?></option>
								<?php 
            $clubs = MACM_Club::get_all( true );
            foreach ( $clubs as $club ) {
                ?>
									<option value="<?php 
                echo esc_attr( $club->id );
                ?>">
										<?php 
                echo esc_html( $club->club_name );
                ?>
									</option>
								<?php 
            }
            ?>
							</select>
						</div>

						<div class="kcm-form-row">
							<label for="kcm-admin-add-groups"><?php 
            esc_html_e( 'Groups', 'martial-arts-club-manager' );
            ?></label>
							<select id="kcm-admin-add-groups" name="group_ids[]" multiple size="5" style="width: 100%; height: 120px;">
								<?php 
            $groups = MACM_Group::get_all( true );
            foreach ( $groups as $group ) {
                ?>
									<option value="<?php 
                echo esc_attr( $group->id );
                ?>">
										<?php 
                echo esc_html( $group->group_name );
                ?>
									</option>
								<?php 
            }
            ?>
							</select>
							<p class="description"><?php 
            esc_html_e( 'Hold Ctrl (Cmd on Mac) to select multiple groups', 'martial-arts-club-manager' );
            ?></p>
						</div>
						<?php 
        }
        ?>

						<div class="kcm-form-row">
							<label for="kcm-admin-add-weight"><?php 
        echo esc_html( $macm_weight_label );
        ?></label>
							<input type="number" id="kcm-admin-add-weight" name="weight" step="0.1" min="0" max="<?php 
        echo esc_attr( $macm_weight_max );
        ?>">
						</div>

						<div class="kcm-form-row">
							<label for="kcm-admin-add-height"><?php 
        echo esc_html( $macm_height_label );
        ?></label>
							<input type="number" id="kcm-admin-add-height" name="height" step="0.1" min="0" max="<?php 
        echo esc_attr( $macm_height_max );
        ?>">
						</div>

						<div class="kcm-form-row">
							<label for="kcm-admin-add-license-number"><?php 
        esc_html_e( 'License Number', 'martial-arts-club-manager' );
        ?></label>
							<input type="text" id="kcm-admin-add-license-number" name="license_number" maxlength="100">
						</div>

						<div class="kcm-form-row">
							<label for="kcm-admin-add-license-expiration"><?php 
        esc_html_e( 'License Expiration', 'martial-arts-club-manager' );
        ?></label>
							<input type="date" id="kcm-admin-add-license-expiration" name="license_expiration">
						</div>

						<div class="kcm-form-row">
							<label><?php 
        esc_html_e( 'Member Photo', 'martial-arts-club-manager' );
        ?></label>
							<div id="kcm-admin-add-photo-preview" style="margin-bottom: 10px;">
								<img id="kcm-admin-add-photo-image" src="" alt="<?php 
        esc_attr_e( 'Member Photo', 'martial-arts-club-manager' );
        ?>" style="max-width: 150px; max-height: 150px; display: none; border: 1px solid #D1D5DB; padding: 5px;">
							</div>
							<input type="hidden" id="kcm-admin-add-photo-id" name="photo_id" value="">
							<button type="button" class="button" id="kcm-admin-add-upload-photo-btn">
								<?php 
        esc_html_e( 'Upload Photo', 'martial-arts-club-manager' );
        ?>
							</button>
							<button type="button" class="button" id="kcm-admin-add-remove-photo-btn" style="display: none;">
								<?php 
        esc_html_e( 'Remove Photo', 'martial-arts-club-manager' );
        ?>
							</button>
							<p class="description"><?php 
        esc_html_e( 'Upload a photo for this member (optional)', 'martial-arts-club-manager' );
        ?></p>
						</div>

						<div class="kcm-modal-footer">
							<button type="button" class="button kcm-modal-close">
								<?php 
        esc_html_e( 'Cancel', 'martial-arts-club-manager' );
        ?>
							</button>
							<button type="submit" class="button button-primary">
								<?php 
        esc_html_e( 'Add Member', 'martial-arts-club-manager' );
        ?>
							</button>
						</div>
					</form>
				</div>
			</div>
		</div>

		<!-- Edit Member Modal -->
		<div id="kcm-admin-member-modal" class="kcm-modal" style="display: none;">
			<div class="kcm-modal-content">
				<div class="kcm-modal-header">
					<h3 id="kcm-admin-modal-title"><?php 
        esc_html_e( 'Edit Member', 'martial-arts-club-manager' );
        ?></h3>
					<button type="button" class="kcm-modal-close">&times;</button>
				</div>
				<div class="kcm-modal-body">
					<form id="kcm-admin-member-form">
						<input type="hidden" name="member_id" id="kcm-admin-member-id" value="">

						<div class="kcm-form-row">
							<label for="kcm-admin-full-name">
								<?php 
        esc_html_e( 'Full Name', 'martial-arts-club-manager' );
        ?> <span class="required">*</span>
							</label>
							<input type="text" id="kcm-admin-full-name" name="full_name" required>
						</div>

						<div class="kcm-form-row">
							<label for="kcm-admin-date-of-birth">
								<?php 
        esc_html_e( 'Date of Birth', 'martial-arts-club-manager' );
        ?> <span class="required">*</span>
							</label>
							<input type="date" id="kcm-admin-date-of-birth" name="date_of_birth" required>
						</div>

						<div class="kcm-form-row">
							<label for="kcm-admin-belt-color">
								<?php 
        esc_html_e( 'Belt Color', 'martial-arts-club-manager' );
        ?> <span class="required">*</span>
							</label>
							<select id="kcm-admin-belt-color" name="belt_color" required>
								<option value=""><?php 
        esc_html_e( 'Select Belt Color', 'martial-arts-club-manager' );
        ?></option>
								<?php 
        foreach ( $belt_colors as $value => $label ) {
            ?>
									<option value="<?php 
            echo esc_attr( $value );
            ?>"><?php 
            echo esc_html( $label );
            ?></option>
								<?php 
        }
        ?>
							</select>
						</div>

						<div class="kcm-form-row">
							<label for="kcm-admin-membership-type">
								<?php 
        esc_html_e( 'Membership Type', 'martial-arts-club-manager' );
        ?>
							</label>
							<select id="kcm-admin-membership-type" name="membership_type_id">
								<option value=""><?php 
        esc_html_e( 'Not set', 'martial-arts-club-manager' );
        ?></option>
								<?php 
        $membership_types = MACM_Membership_Type::get_all();
        foreach ( $membership_types as $type ) {
            ?>
									<option value="<?php 
            echo esc_attr( $type->id );
            ?>"><?php 
            echo esc_html( $type->type_name );
            ?></option>
								<?php 
        }
        ?>
							</select>
						</div>

						<?php 
        if ( macm_fs()->can_use_premium_code() && class_exists( 'MACM_Club' ) ) {
            ?>
						<div class="kcm-form-row">
							<label for="kcm-admin-club"><?php 
            esc_html_e( 'Club', 'martial-arts-club-manager' );
            ?></label>
							<select id="kcm-admin-club" name="club_id">
								<option value=""><?php 
            esc_html_e( 'Not set', 'martial-arts-club-manager' );
            ?></option>
								<?php 
            $clubs = MACM_Club::get_all( true );
            foreach ( $clubs as $club ) {
                ?>
									<option value="<?php 
                echo esc_attr( $club->id );
                ?>">
										<?php 
                echo esc_html( $club->club_name );
                ?>
									</option>
								<?php 
            }
            ?>
							</select>
						</div>

						<div class="kcm-form-row">
							<label for="kcm-admin-groups"><?php 
            esc_html_e( 'Groups', 'martial-arts-club-manager' );
            ?></label>
							<select id="kcm-admin-groups" name="group_ids[]" multiple size="5" style="width: 100%; height: 120px;">
								<?php 
            $groups = MACM_Group::get_all( true );
            foreach ( $groups as $group ) {
                ?>
									<option value="<?php 
                echo esc_attr( $group->id );
                ?>">
										<?php 
                echo esc_html( $group->group_name );
                ?>
									</option>
								<?php 
            }
            ?>
							</select>
							<p class="description"><?php 
            esc_html_e( 'Hold Ctrl (Cmd on Mac) to select multiple groups', 'martial-arts-club-manager' );
            ?></p>
						</div>
						<?php 
        }
        ?>

						<div class="kcm-form-row">
							<label for="kcm-admin-weight"><?php 
        echo esc_html( $macm_weight_label );
        ?></label>
							<input type="number" id="kcm-admin-weight" name="weight" step="0.1" min="0" max="<?php 
        echo esc_attr( $macm_weight_max );
        ?>">
						</div>

						<div class="kcm-form-row">
							<label for="kcm-admin-height"><?php 
        echo esc_html( $macm_height_label );
        ?></label>
							<input type="number" id="kcm-admin-height" name="height" step="0.1" min="0" max="<?php 
        echo esc_attr( $macm_height_max );
        ?>">
						</div>

						<div class="kcm-form-row">
							<label for="kcm-admin-license-number"><?php 
        esc_html_e( 'License Number', 'martial-arts-club-manager' );
        ?></label>
							<input type="text" id="kcm-admin-license-number" name="license_number" maxlength="100">
						</div>

						<div class="kcm-form-row">
							<label for="kcm-admin-license-expiration"><?php 
        esc_html_e( 'License Expiration', 'martial-arts-club-manager' );
        ?></label>
							<input type="date" id="kcm-admin-license-expiration" name="license_expiration">
						</div>

						<div class="kcm-form-row">
							<label><?php 
        esc_html_e( 'Member Photo', 'martial-arts-club-manager' );
        ?></label>
							<div id="kcm-admin-edit-photo-preview" style="margin-bottom: 10px;">
								<img id="kcm-admin-edit-photo-image" src="" alt="<?php 
        esc_attr_e( 'Member Photo', 'martial-arts-club-manager' );
        ?>" style="max-width: 150px; max-height: 150px; display: none; border: 1px solid #D1D5DB; padding: 5px;">
							</div>
							<input type="hidden" id="kcm-admin-edit-photo-id" name="photo_id" value="">
							<button type="button" class="button" id="kcm-admin-edit-upload-photo-btn">
								<?php 
        esc_html_e( 'Upload Photo', 'martial-arts-club-manager' );
        ?>
							</button>
							<button type="button" class="button" id="kcm-admin-edit-remove-photo-btn" style="display: none;">
								<?php 
        esc_html_e( 'Remove Photo', 'martial-arts-club-manager' );
        ?>
							</button>
							<p class="description"><?php 
        esc_html_e( 'Change or remove the member\'s photo (optional)', 'martial-arts-club-manager' );
        ?></p>
						</div>

						<div class="kcm-modal-footer">
							<button type="button" class="button kcm-modal-close">
								<?php 
        esc_html_e( 'Cancel', 'martial-arts-club-manager' );
        ?>
							</button>
							<button type="submit" class="button button-primary">
								<?php 
        esc_html_e( 'Save Member', 'martial-arts-club-manager' );
        ?>
							</button>
						</div>
					</form>
				</div>
			</div>
		</div>

		<!-- User Info Modal -->
		<div id="kcm-user-info-modal" class="kcm-modal" style="display: none;">
			<div class="kcm-modal-content" style="max-width: 500px;">
				<div class="kcm-modal-header">
					<h3><?php 
        esc_html_e( 'User Information', 'martial-arts-club-manager' );
        ?></h3>
					<button type="button" class="kcm-modal-close kcm-user-info-close">&times;</button>
				</div>
				<div class="kcm-modal-body">
					<div id="kcm-user-info-content">
						<div class="kcm-user-info-row">
							<strong><?php 
        esc_html_e( 'Full Name:', 'martial-arts-club-manager' );
        ?></strong>
							<span id="kcm-user-info-name"></span>
						</div>
						<div class="kcm-user-info-row">
							<strong><?php 
        esc_html_e( 'Email:', 'martial-arts-club-manager' );
        ?></strong>
							<span id="kcm-user-info-email"></span>
						</div>
						<div class="kcm-user-info-row">
							<strong><?php 
        esc_html_e( 'Telephone:', 'martial-arts-club-manager' );
        ?></strong>
							<span id="kcm-user-info-phone"></span>
						</div>
					</div>
				</div>
				<div class="kcm-modal-footer">
					<button type="button" class="button kcm-user-info-close">
						<?php 
        esc_html_e( 'Close', 'martial-arts-club-manager' );
        ?>
					</button>
				</div>
			</div>
		</div>

		<!-- View Member Details Modal -->
		<div id="kcm-view-member-details-modal" class="kcm-modal" style="display: none;">
			<div class="kcm-modal-content" style="max-width: 800px;">
				<div class="kcm-modal-header">
					<h3><?php 
        esc_html_e( 'Member Details', 'martial-arts-club-manager' );
        ?></h3>
					<button type="button" class="kcm-modal-close kcm-view-member-close">&times;</button>
				</div>
				<div class="kcm-modal-body">
					<div id="kcm-view-member-loading" style="text-align: center; padding: 40px;">
						<p><?php 
        esc_html_e( 'Loading member details...', 'martial-arts-club-manager' );
        ?></p>
					</div>
					<div id="kcm-view-member-content" style="display: none;">
						<!-- Content will be populated via AJAX -->
					</div>
				</div>
				<div class="kcm-modal-footer">
					<button type="button" class="button kcm-view-member-close">
						<?php 
        esc_html_e( 'Close', 'martial-arts-club-manager' );
        ?>
					</button>
				</div>
			</div>
		</div>

		<?php 
        // PREMIUM: Render grading history modals.
        if ( function_exists( 'macm_fs' ) && macm_fs()->can_use_premium_code() && class_exists( 'MACM_Admin_Grading_History' ) ) {
            MACM_Admin_Grading_History::render_modal();
        }
        // Build inline script using WordPress-compliant method.
        ob_start();
        ?>
		jQuery(document).ready(function($) {
			// Store member data.
			var membersData = <?php 
        echo wp_json_encode( $members );
        ?>;

			// WordPress Media Library for Add Member Photo.
			var kcmAddMemberMediaUploader;

			$('#kcm-admin-add-upload-photo-btn').on('click', function(e) {
				e.preventDefault();

				// If the uploader object has already been created, reopen the dialog.
				if (kcmAddMemberMediaUploader) {
					kcmAddMemberMediaUploader.open();
					return;
				}

				// Extend the wp.media object
				kcmAddMemberMediaUploader = wp.media.frames.file_frame = wp.media({
					title: '<?php 
        esc_html_e( 'Select Member Photo', 'martial-arts-club-manager' );
        ?>',
					button: {
						text: '<?php 
        esc_html_e( 'Use this photo', 'martial-arts-club-manager' );
        ?>'
					},
					multiple: false
				});

				// When an image is selected, run a callback.
				kcmAddMemberMediaUploader.on('select', function() {
					var attachment = kcmAddMemberMediaUploader.state().get('selection').first().toJSON();

					// Set the photo ID.
					$('#kcm-admin-add-photo-id').val(attachment.id);

					// Display the photo.
					$('#kcm-admin-add-photo-image').attr('src', attachment.url).show();

					// Show remove button.
					$('#kcm-admin-add-remove-photo-btn').show();
				});

				// Open the uploader dialog.
				kcmAddMemberMediaUploader.open();
			});

			// Remove photo button for Add Member.
			$('#kcm-admin-add-remove-photo-btn').on('click', function(e) {
				e.preventDefault();

				// Clear the photo ID.
				$('#kcm-admin-add-photo-id').val('');

				// Hide the photo.
				$('#kcm-admin-add-photo-image').attr('src', '').hide();

				// Hide remove button.
				$(this).hide();
			});

			// WordPress Media Library for Edit Member Photo.
			var kcmEditMemberMediaUploader;

			$('#kcm-admin-edit-upload-photo-btn').on('click', function(e) {
				e.preventDefault();

				if (kcmEditMemberMediaUploader) {
					kcmEditMemberMediaUploader.open();
					return;
				}

				kcmEditMemberMediaUploader = wp.media.frames.file_frame = wp.media({
					title: '<?php 
        esc_html_e( 'Select Member Photo', 'martial-arts-club-manager' );
        ?>',
					button: {
						text: '<?php 
        esc_html_e( 'Use this photo', 'martial-arts-club-manager' );
        ?>'
					},
					multiple: false
				});

				kcmEditMemberMediaUploader.on('select', function() {
					var attachment = kcmEditMemberMediaUploader.state().get('selection').first().toJSON();
					$('#kcm-admin-edit-photo-id').val(attachment.id);
					$('#kcm-admin-edit-photo-image').attr('src', attachment.url).show();
					$('#kcm-admin-edit-remove-photo-btn').show();
				});

				kcmEditMemberMediaUploader.open();
			});

			// Remove photo button for Edit Member.
			$('#kcm-admin-edit-remove-photo-btn').on('click', function(e) {
				e.preventDefault();
				$('#kcm-admin-edit-photo-id').val('');
				$('#kcm-admin-edit-photo-image').attr('src', '').hide();
				$(this).hide();
			});

			// Add member button.
			$('#kcm-admin-add-member-btn').on('click', function(e) {
				e.preventDefault();
				// Clear form.
				$('#kcm-admin-add-member-form')[0].reset();
				// Clear photo.
				$('#kcm-admin-add-photo-id').val('');
				$('#kcm-admin-add-photo-image').attr('src', '').hide();
				$('#kcm-admin-add-remove-photo-btn').hide();
				// Show modal.
				$('#kcm-admin-add-member-modal').fadeIn();
			});

			// Submit add member form.
			$('#kcm-admin-add-member-form').on('submit', function(e) {
				e.preventDefault();

				// Build form data with proper array handling.
				var formData = new FormData();
				formData.append('action', 'macm_admin_add_member');
				formData.append('nonce', macmAdmin.nonce);
				formData.append('user_id', $('#kcm-admin-add-user').val());
				formData.append('full_name', $('#kcm-admin-add-full-name').val());
				formData.append('date_of_birth', $('#kcm-admin-add-date-of-birth').val());
				formData.append('belt_color', $('#kcm-admin-add-belt-color').val());
				formData.append('membership_type_id', $('#kcm-admin-add-membership-type').val());

				// Premium fields - only if elements exist.
				if ($('#kcm-admin-add-club').length) {
					formData.append('club_id', $('#kcm-admin-add-club').val());
				}

				// Handle group_ids array - only if element exists.
				if ($('#kcm-admin-add-groups').length) {
					var groupIds = $('#kcm-admin-add-groups').val() || [];
					for (var i = 0; i < groupIds.length; i++) {
						formData.append('group_ids[]', groupIds[i]);
					}
				}

				formData.append('weight', $('#kcm-admin-add-weight').val());
				formData.append('height', $('#kcm-admin-add-height').val());
				formData.append('license_number', $('#kcm-admin-add-license-number').val());
				formData.append('license_expiration', $('#kcm-admin-add-license-expiration').val());
				formData.append('photo_id', $('#kcm-admin-add-photo-id').val());

				// Disable submit button.
				var $submitBtn = $('#kcm-admin-add-member-form button[type="submit"]');
				$submitBtn.prop('disabled', true).text('<?php 
        esc_html_e( 'Adding...', 'martial-arts-club-manager' );
        ?>');

				$.ajax({
					url: macmAdmin.ajaxurl,
					type: 'POST',
					data: formData,
					processData: false,
					contentType: false,
					success: function(response) {
						if (response.success) {
							// Reload page to show new member.
							location.reload();
						} else {
							alert(response.data.message || '<?php 
        esc_html_e( 'Error creating member', 'martial-arts-club-manager' );
        ?>');
							$submitBtn.prop('disabled', false).text('<?php 
        esc_html_e( 'Add Member', 'martial-arts-club-manager' );
        ?>');
						}
					},
					error: function(xhr, status, error) {
						alert('<?php 
        esc_html_e( 'AJAX error occurred: ', 'martial-arts-club-manager' );
        ?>' + error);
						$submitBtn.prop('disabled', false).text('<?php 
        esc_html_e( 'Add Member', 'martial-arts-club-manager' );
        ?>');
					}
				});
			});

			// View user info.
			$('.kcm-view-user-info').on('click', function(e) {
				e.preventDefault();
				var userId = $(this).data('user-id');
				var userFullName = $(this).data('user-full-name');
				var userEmail = $(this).data('user-email');

				// Show loading state.
				$('#kcm-user-info-name').text(userFullName);
				$('#kcm-user-info-email').html('<a href="mailto:' + userEmail + '">' + userEmail + '</a>');
				$('#kcm-user-info-phone').html('<span style="color: #6B7280;">Loading...</span>');

				// Show modal.
				$('#kcm-user-info-modal').fadeIn();

				// Fetch phone number via AJAX.
				$.ajax({
					url: macmAdmin.ajaxurl,
					type: 'POST',
					data: {
						action: 'macm_get_user_phone',
						nonce: macmAdmin.nonce,
						user_id: userId
					},
					success: function(response) {
						if (response.success && response.data.phone) {
							$('#kcm-user-info-phone').html('<a href="tel:' + response.data.phone + '">' + response.data.phone + '</a>');
						} else {
							$('#kcm-user-info-phone').html('<span style="color: #6B7280;">Not provided</span>');
						}
					},
					error: function() {
						$('#kcm-user-info-phone').html('<span style="color: #6B7280;">Error loading</span>');
					}
				});
			});

			// Edit member button.
			$('.kcm-admin-edit-member').on('click', function() {
				var memberId = $(this).data('member-id');
				var member = membersData.find(function(m) { return m.id == memberId; });

				if (member) {
					// Populate form.
					$('#kcm-admin-member-id').val(member.id);
					$('#kcm-admin-full-name').val(member.full_name);
					$('#kcm-admin-date-of-birth').val(member.date_of_birth);
					$('#kcm-admin-belt-color').val(member.belt_color);
					$('#kcm-admin-membership-type').val(member.membership_type_id || '');

					// Premium fields - only if elements exist.
					if ($('#kcm-admin-club').length) {
						$('#kcm-admin-club').val(member.club_id || '');
					}

					// Populate multi-select groups - only if element exists.
					if ($('#kcm-admin-groups').length) {
						$('#kcm-admin-groups').val(member.group_ids || []);
					}

					// Convert stored metric values to display units.
					var unitSystem = '<?php 
        echo esc_js( $macm_unit_system );
        ?>';
					if (member.weight && unitSystem === 'imperial') {
						$('#kcm-admin-weight').val(Math.round(member.weight * 2.20462 * 10) / 10);
					} else {
						$('#kcm-admin-weight').val(member.weight || '');
					}
					if (member.height && unitSystem === 'imperial') {
						$('#kcm-admin-height').val(Math.round(member.height * 0.393701 * 10) / 10);
					} else {
						$('#kcm-admin-height').val(member.height || '');
					}
					$('#kcm-admin-license-number').val(member.license_number || '');
					$('#kcm-admin-license-expiration').val(member.license_expiration || '');

					// Photo field.
					if (member.photo_id && member.photo_url) {
						$('#kcm-admin-edit-photo-id').val(member.photo_id);
						$('#kcm-admin-edit-photo-image').attr('src', member.photo_url).show();
						$('#kcm-admin-edit-remove-photo-btn').show();
					} else {
						$('#kcm-admin-edit-photo-id').val('');
						$('#kcm-admin-edit-photo-image').attr('src', '').hide();
						$('#kcm-admin-edit-remove-photo-btn').hide();
					}

					// Show modal.
					$('#kcm-admin-member-modal').fadeIn();
				}
			});

			// Close user info modal.
			$('.kcm-user-info-close').on('click', function() {
				$('#kcm-user-info-modal').fadeOut();
			});

			// Close modals.
			$('.kcm-modal-close').on('click', function() {
				$('#kcm-admin-add-member-modal').fadeOut();
				$('#kcm-admin-member-modal').fadeOut();
				$('#kcm-user-info-modal').fadeOut();
			});

			// Close modal on outside click.
			$(window).on('click', function(e) {
				if ($(e.target).is('#kcm-admin-add-member-modal')) {
					$('#kcm-admin-add-member-modal').fadeOut();
				}
				if ($(e.target).is('#kcm-admin-member-modal')) {
					$('#kcm-admin-member-modal').fadeOut();
				}
				if ($(e.target).is('#kcm-user-info-modal')) {
					$('#kcm-user-info-modal').fadeOut();
				}
			});

			// Submit form.
			$('#kcm-admin-member-form').on('submit', function(e) {
				e.preventDefault();

				// Build form data with proper array handling.
				var formData = new FormData();
				formData.append('action', 'macm_admin_edit_member');
				formData.append('nonce', macmAdmin.nonce);
				formData.append('member_id', $('#kcm-admin-member-id').val());
				formData.append('full_name', $('#kcm-admin-full-name').val());
				formData.append('date_of_birth', $('#kcm-admin-date-of-birth').val());
				formData.append('belt_color', $('#kcm-admin-belt-color').val());
				formData.append('membership_type_id', $('#kcm-admin-membership-type').val());

				// Premium fields - only if elements exist.
				if ($('#kcm-admin-club').length) {
					formData.append('club_id', $('#kcm-admin-club').val());
				}

				// Handle group_ids array - only if element exists.
				if ($('#kcm-admin-groups').length) {
					var groupIds = $('#kcm-admin-groups').val() || [];
					for (var i = 0; i < groupIds.length; i++) {
						formData.append('group_ids[]', groupIds[i]);
					}
				}

				formData.append('weight', $('#kcm-admin-weight').val());
				formData.append('height', $('#kcm-admin-height').val());
				formData.append('license_number', $('#kcm-admin-license-number').val());
				formData.append('license_expiration', $('#kcm-admin-license-expiration').val());
				formData.append('photo_id', $('#kcm-admin-edit-photo-id').val());

				$.ajax({
					url: macmAdmin.ajaxurl,
					type: 'POST',
					data: formData,
					processData: false,
					contentType: false,
					success: function(response) {
						if (response.success) {
							// Reload page to show updated data.
							location.reload();
						} else {
							alert(response.data.message || 'Error updating member');
						}
					},
					error: function(xhr, status, error) {
						alert('AJAX error occurred: ' + error);
					}
				});
			});

			// View Member Details.
			$(document).on('click', '.kcm-admin-view-member-details', function(e) {
				e.preventDefault();

				var memberId = $(this).data('member-id');

				// Show modal.
				$('#kcm-view-member-details-modal').fadeIn();
				$('#kcm-view-member-loading').show();
				$('#kcm-view-member-content').hide();

				// Fetch member details via AJAX.
				$.ajax({
					url: ajaxurl,
					type: 'POST',
					data: {
						action: 'macm_get_member_details',
						member_id: memberId,
						nonce: '<?php 
        echo esc_js( wp_create_nonce( 'macm_get_member_details' ) );
        ?>'
					},
					success: function(response) {
						$('#kcm-view-member-loading').hide();
						if (response.success) {
							$('#kcm-view-member-content').html(response.data.html).fadeIn();
						} else {
							var msg = (response.data && response.data.message) || '<?php 
        echo esc_js( __( 'Error loading member details', 'martial-arts-club-manager' ) );
        ?>';
							var debug = (response.data && response.data.debug) ? '<br><small style="color: #666;">' + response.data.debug + '</small>' : '';
							$('#kcm-view-member-content').html('<p style="color: #d63638;">' + msg + debug + '</p>').fadeIn();
						}
					},
					error: function(xhr, status, error) {
						$('#kcm-view-member-loading').hide();
						var detail = error || status || '<?php 
        echo esc_js( __( 'Unknown error', 'martial-arts-club-manager' ) );
        ?>';
						$('#kcm-view-member-content').html('<p style="color: #d63638;"><?php 
        echo esc_js( __( 'Server error:', 'martial-arts-club-manager' ) );
        ?> ' + detail + ' (HTTP ' + xhr.status + ')</p>').fadeIn();
					}
				});
			});

			// Close View Member Details Modal.
			$('.kcm-view-member-close').on('click', function() {
				$('#kcm-view-member-details-modal').fadeOut();
			});

			<?php 
        if ( function_exists( 'macm_fs' ) && macm_fs()->can_use_premium_code() ) {
            ?>
			// PREMIUM: Belt History Modal Handling.
			var currentGradingMemberId = 0;
			var currentGradingExportUrl = '';
			var gradingBeltColors = [];
			var gradingInstructors = [];
			var gradingRecords = [];

			// Open Belt History Modal.
			$(document).on('click', '.kcm-admin-belt-history', function(e) {
				e.preventDefault();
				currentGradingMemberId = $(this).data('member-id');
				var memberName = $(this).data('member-name');

				$('#kcm-grading-modal-title').text(memberName + ' - <?php 
            echo esc_js( __( 'Belt Grading History', 'martial-arts-club-manager' ) );
            ?>');
				$('#kcm-grading-content').html('<div class="kcm-loading"><?php 
            echo esc_js( __( 'Loading...', 'martial-arts-club-manager' ) );
            ?></div>');
				$('#kcm-add-grading-btn, #kcm-grading-export-btn').hide();
				$('#kcm-grading-modal').fadeIn();

				// Load grading history.
				$.ajax({
					url: ajaxurl,
					type: 'POST',
					data: {
						action: 'macm_get_grading_history',
						nonce: typeof macmGrading !== 'undefined' ? macmGrading.nonce : '',
						member_id: currentGradingMemberId
					},
					success: function(response) {
						if (response.success) {
							gradingBeltColors = response.data.belt_colors;
							gradingInstructors = response.data.instructors;
							gradingRecords = response.data.records;
							currentGradingExportUrl = response.data.export_url;

							renderGradingHistory(response.data.records);
							$('#kcm-add-grading-btn, #kcm-grading-export-btn').show();
						} else {
							$('#kcm-grading-content').html('<p class="kcm-error">' + (response.data.message || '<?php 
            echo esc_js( __( 'Error loading history.', 'martial-arts-club-manager' ) );
            ?>') + '</p>');
						}
					},
					error: function() {
						$('#kcm-grading-content').html('<p class="kcm-error"><?php 
            echo esc_js( __( 'Error loading history.', 'martial-arts-club-manager' ) );
            ?></p>');
					}
				});
			});

			// Render grading history table.
			function renderGradingHistory(records) {
				if (records.length === 0) {
					$('#kcm-grading-content').html('<p class="kcm-notice"><?php 
            echo esc_js( __( 'No grading history found for this member.', 'martial-arts-club-manager' ) );
            ?></p>');
					return;
				}

				var html = '<table class="wp-list-table widefat fixed striped">';
				html += '<thead><tr>';
				html += '<th><?php 
            echo esc_js( __( 'Date', 'martial-arts-club-manager' ) );
            ?></th>';
				html += '<th><?php 
            echo esc_js( __( 'Belt Color', 'martial-arts-club-manager' ) );
            ?></th>';
				html += '<th><?php 
            echo esc_js( __( 'Examiner', 'martial-arts-club-manager' ) );
            ?></th>';
				html += '<th><?php 
            echo esc_js( __( 'Score', 'martial-arts-club-manager' ) );
            ?></th>';
				html += '<th><?php 
            echo esc_js( __( 'Notes', 'martial-arts-club-manager' ) );
            ?></th>';
				html += '<th><?php 
            echo esc_js( __( 'Actions', 'martial-arts-club-manager' ) );
            ?></th>';
				html += '</tr></thead><tbody>';

				$.each(records, function(i, record) {
					html += '<tr>';
					html += '<td>' + record.grading_date_formatted + '</td>';
					html += '<td><span class="kcm-belt-badge kcm-belt-' + record.belt_color_key + '">' + record.color_name + '</span></td>';
					html += '<td>' + (record.examiner_display || '-') + '</td>';
					html += '<td>' + (record.score || '-') + '</td>';
					html += '<td>' + (record.notes || '-') + '</td>';
					html += '<td>';
					html += '<a href="#" class="kcm-edit-grading" data-record-id="' + record.id + '"><?php 
            echo esc_js( __( 'Edit', 'martial-arts-club-manager' ) );
            ?></a> | ';
					html += '<a href="#" class="kcm-delete-grading" data-record-id="' + record.id + '"><?php 
            echo esc_js( __( 'Delete', 'martial-arts-club-manager' ) );
            ?></a>';
					html += '</td>';
					html += '</tr>';
				});

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

			// Close grading modal.
			$('#kcm-grading-modal .kcm-modal-close').on('click', function() {
				$('#kcm-grading-modal').fadeOut();
			});

			// Export CSV.
			$('#kcm-grading-export-btn').on('click', function() {
				if (currentGradingExportUrl) {
					window.location.href = currentGradingExportUrl;
				}
			});

			// Open Add Grading Form.
			$('#kcm-add-grading-btn').on('click', function() {
				openGradingForm(0);
			});

			// Edit grading record.
			$(document).on('click', '.kcm-edit-grading', function(e) {
				e.preventDefault();
				var recordId = $(this).data('record-id');
				openGradingForm(recordId);
			});

			// Open grading form modal.
			function openGradingForm(recordId) {
				// Reset form.
				$('#kcm-grading-form')[0].reset();
				$('#grading-record-id').val(recordId || '');
				$('#grading-member-id').val(currentGradingMemberId);

				// Find record data if editing.
				var record = null;
				if (recordId) {
					for (var i = 0; i < gradingRecords.length; i++) {
						if (gradingRecords[i].id == recordId) {
							record = gradingRecords[i];
							break;
						}
					}
				}

				// Populate belt colors dropdown.
				var beltSelect = $('#grading-belt-color');
				beltSelect.find('option:not(:first)').remove();
				$.each(gradingBeltColors, function(i, belt) {
					var selected = (record && record.belt_color_key === belt.color_key) ? ' selected' : '';
					beltSelect.append('<option value="' + belt.color_key + '"' + selected + '>' + belt.color_name + '</option>');
				});

				// Populate instructors dropdown.
				var instructorSelect = $('#grading-examiner');
				instructorSelect.find('option:not(:first)').remove();
				$.each(gradingInstructors, function(i, instructor) {
					var selected = (record && record.examiner_id == instructor.id) ? ' selected' : '';
					instructorSelect.append('<option value="' + instructor.id + '"' + selected + '>' + instructor.full_name + '</option>');
				});

				// If editing, populate form fields.
				if (record) {
					$('#kcm-grading-form-title').text('<?php 
            echo esc_js( __( 'Edit Grading Record', 'martial-arts-club-manager' ) );
            ?>');
					$('#grading-date').val(record.grading_date);
					$('#grading-examiner-name').val(record.examiner_name || '');
					$('#grading-score').val(record.score || '');
					$('#grading-notes').val(record.notes || '');
				} else {
					$('#kcm-grading-form-title').text('<?php 
            echo esc_js( __( 'Add Grading Record', 'martial-arts-club-manager' ) );
            ?>');
				}

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

			// Close grading form modal.
			$('.kcm-grading-form-cancel, #kcm-grading-form-modal .kcm-modal-close').on('click', function() {
				$('#kcm-grading-form-modal').fadeOut();
			});

			// Save grading record.
			$('#kcm-save-grading-btn').on('click', function() {
				var formData = {
					action: 'macm_save_grading',
					nonce: typeof macmGrading !== 'undefined' ? macmGrading.nonce : '',
					record_id: $('#grading-record-id').val(),
					member_id: $('#grading-member-id').val(),
					belt_color_key: $('#grading-belt-color').val(),
					grading_date: $('#grading-date').val(),
					examiner_id: $('#grading-examiner').val(),
					examiner_name: $('#grading-examiner-name').val(),
					score: $('#grading-score').val(),
					notes: $('#grading-notes').val()
				};

				$.ajax({
					url: ajaxurl,
					type: 'POST',
					data: formData,
					success: function(response) {
						if (response.success) {
							$('#kcm-grading-form-modal').fadeOut();
							// Refresh the grading history.
							$('.kcm-admin-belt-history[data-member-id="' + currentGradingMemberId + '"]').trigger('click');
						} else {
							alert(response.data.message || '<?php 
            echo esc_js( __( 'Error saving record.', 'martial-arts-club-manager' ) );
            ?>');
						}
					},
					error: function() {
						alert('<?php 
            echo esc_js( __( 'Error saving record.', 'martial-arts-club-manager' ) );
            ?>');
					}
				});
			});

			// Delete grading record.
			$(document).on('click', '.kcm-delete-grading', function(e) {
				e.preventDefault();
				if (!confirm('<?php 
            echo esc_js( __( 'Are you sure you want to delete this grading record?', 'martial-arts-club-manager' ) );
            ?>')) {
					return;
				}

				var recordId = $(this).data('record-id');

				$.ajax({
					url: ajaxurl,
					type: 'POST',
					data: {
						action: 'macm_delete_grading',
						nonce: typeof macmGrading !== 'undefined' ? macmGrading.nonce : '',
						record_id: recordId
					},
					success: function(response) {
						if (response.success) {
							// Refresh the grading history.
							$('.kcm-admin-belt-history[data-member-id="' + currentGradingMemberId + '"]').trigger('click');
						} else {
							alert(response.data.message || '<?php 
            echo esc_js( __( 'Error deleting record.', 'martial-arts-club-manager' ) );
            ?>');
						}
					},
					error: function() {
						alert('<?php 
            echo esc_js( __( 'Error deleting record.', 'martial-arts-club-manager' ) );
            ?>');
					}
				});
			});
			<?php 
        }
        ?>
		});
		<?php 
        $members_page_script = ob_get_clean();
        wp_add_inline_script( 'kcm-admin-scripts', $members_page_script );
        // Build inline styles using WordPress-compliant method.
        $members_page_styles = '
			/* Make row actions always visible (consistent with classes page) */
			.row-actions {
				position: static !important;
				visibility: visible !important;
				opacity: 1 !important;
				white-space: nowrap;
			}
			.row-actions span {
				display: inline;
			}

			/* Actions column specific styling */
			.column-actions .row-actions {
				margin: 0;
				padding: 0;
			}
			.column-actions .row-actions span {
				margin: 0;
				padding: 0;
			}
			.column-actions .row-actions span:not(:last-child):after {
				content: " | ";
				color: #D1D5DB;
			}

			/* Mobile Responsive Styles */
			@media (max-width: 782px) {
				/* Make members table scrollable horizontally */
				.wrap {
					overflow-x: auto;
					-webkit-overflow-scrolling: touch;
				}

				.wp-list-table {
					table-layout: fixed;
					width: 1200px !important;
				}

				/* Ensure Actions column has adequate width on mobile */
				.wp-list-table .column-actions {
					min-width: 160px;
					width: 160px;
				}

				.wp-list-table thead th:nth-child(1),
				.wp-list-table tbody td:nth-child(1) {
					width: 80px;
				}

				.wp-list-table thead th:nth-child(2),
				.wp-list-table tbody td:nth-child(2) {
					width: 120px;
				}

				.wp-list-table thead th:nth-child(3),
				.wp-list-table tbody td:nth-child(3) {
					width: 110px;
				}

				.wp-list-table thead th:nth-child(4),
				.wp-list-table tbody td:nth-child(4) {
					width: 70px;
				}

				.wp-list-table thead th:nth-child(5),
				.wp-list-table tbody td:nth-child(5) {
					width: 100px;
				}

				.wp-list-table thead th:nth-child(6),
				.wp-list-table tbody td:nth-child(6) {
					width: 110px;
				}

				.wp-list-table thead th:nth-child(7),
				.wp-list-table tbody td:nth-child(7) {
					width: 100px;
				}

				.wp-list-table thead th:nth-child(8),
				.wp-list-table tbody td:nth-child(8) {
					width: 100px;
				}

				.wp-list-table thead th:nth-child(9),
				.wp-list-table tbody td:nth-child(9) {
					width: 90px;
				}

				.wp-list-table thead th:nth-child(10),
				.wp-list-table tbody td:nth-child(10) {
					width: 90px;
				}

				.wp-list-table thead th:nth-child(11),
				.wp-list-table tbody td:nth-child(11) {
					width: 90px;
				}

				.wp-list-table thead th:nth-child(12),
				.wp-list-table tbody td:nth-child(12) {
					width: 100px;
				}

				.wp-list-table thead th:nth-child(13),
				.wp-list-table tbody td:nth-child(13) {
					width: 90px;
				}

				.wp-list-table thead th:nth-child(14),
				.wp-list-table tbody td:nth-child(14) {
					width: 150px;
				}

				/* Adjust table font sizes */
				.wp-list-table td,
				.wp-list-table th {
					font-size: 13px;
					padding: 8px 6px;
				}

				.wp-list-table .row-actions {
					font-size: 12px;
				}
			}

			@media (max-width: 480px) {
				.wp-list-table {
					font-size: 12px;
					width: 1150px !important;
				}
			}
		';
        wp_add_inline_style( 'kcm-admin-styles', $members_page_styles );
        ?>
		<?php 
    }

    /**
     * Settings page
     */
    public function settings_page() {
        if ( !current_user_can( 'manage_macm_settings' ) ) {
            wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'martial-arts-club-manager' ) );
        }
        // Initialize settings class and display settings page.
        $settings = new MACM_Admin_Settings();
        $settings->display_settings_page();
    }

}
