<?php
/**
 * Admin-specific functionality
 *
 * @package KarateClubManager
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Admin class
 */
class MACM_Admin {
	/**
	 * Constructor
	 */
	public function __construct() {
		// Add AJAX handlers.
		add_action( 'wp_ajax_macm_admin_add_member', array( $this, 'ajax_admin_add_member' ) );
		add_action( 'wp_ajax_macm_admin_edit_member', array( $this, 'ajax_admin_edit_member' ) );
		add_action( 'wp_ajax_macm_get_user_phone', array( $this, 'ajax_get_user_phone' ) );
		add_action( 'wp_ajax_macm_admin_toggle_member_status', array( $this, 'ajax_toggle_member_status' ) );
		add_action( 'wp_ajax_macm_get_member_details', array( $this, 'ajax_get_member_details' ) );

		// Add export handler.
		add_action( 'admin_post_macm_export_members_csv', array( $this, 'export_members_csv' ) );
	}

	/**
	 * Enqueue admin styles
	 */
	public function enqueue_styles() {
		// Main admin styles.
		wp_enqueue_style(
			'kcm-admin-styles',
			MACM_PLUGIN_URL . 'assets/css/admin.css',
			array(),
			MACM_VERSION,
			'all'
		);

		// Admin components (shared UI components).
		wp_enqueue_style(
			'kcm-admin-components',
			MACM_PLUGIN_URL . 'assets/css/admin-components.css',
			array( 'kcm-admin-styles' ),
			MACM_VERSION,
			'all'
		);
	}

	/**
	 * Enqueue admin scripts
	 */
	public function enqueue_scripts() {
		// Enqueue WordPress media library.
		wp_enqueue_media();

		wp_enqueue_script(
			'kcm-admin-scripts',
			MACM_PLUGIN_URL . 'assets/js/admin.js',
			array( 'jquery' ),
			MACM_VERSION,
			true
		);

		// Localize script for AJAX.
		wp_localize_script(
			'kcm-admin-scripts',
			'macmAdmin',
			array(
				'ajaxurl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'kcm-admin-nonce' ),
				'i18n'    => array(
					'noMembersSelected'       => __( 'Please select at least one member.', 'martial-arts-club-manager' ),
					'confirmArchive'          => __( 'Confirm Archive', 'martial-arts-club-manager' ),
					'confirmActivate'         => __( 'Confirm Activate', 'martial-arts-club-manager' ),
					'archiveOneMember'        => __( 'Are you sure you want to archive this member?', 'martial-arts-club-manager' ),
					/* translators: %d: number of members */
					'archiveMultipleMembers'  => __( 'Are you sure you want to archive %d members?', 'martial-arts-club-manager' ),
					'activateOneMember'       => __( 'Are you sure you want to activate this member?', 'martial-arts-club-manager' ),
					/* translators: %d: number of members */
					'activateMultipleMembers' => __( 'Are you sure you want to activate %d members?', 'martial-arts-club-manager' ),
				),
			)
		);
	}

	/**
	 * AJAX handler for admin add member
	 */
	public function ajax_admin_add_member() {
		// Verify nonce.
		check_ajax_referer( 'kcm-admin-nonce', 'nonce' );

		// Check permissions.
		if ( ! current_user_can( 'manage_macm_members' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions', 'martial-arts-club-manager' ) ) );
		}

		// Get user ID.
		$user_id = isset( $_POST['user_id'] ) ? absint( wp_unslash( $_POST['user_id'] ) ) : 0;
		if ( ! $user_id ) {
			wp_send_json_error( array( 'message' => __( 'Please select a user', 'martial-arts-club-manager' ) ) );
		}

		// Verify user exists.
		$user = get_user_by( 'id', $user_id );
		if ( ! $user ) {
			wp_send_json_error( array( 'message' => __( 'Invalid user selected', 'martial-arts-club-manager' ) ) );
		}

		// Prepare member data.
		$data = array(
			'full_name'     => isset( $_POST['full_name'] ) ? sanitize_text_field( wp_unslash( $_POST['full_name'] ) ) : '',
			'date_of_birth' => isset( $_POST['date_of_birth'] ) ? sanitize_text_field( wp_unslash( $_POST['date_of_birth'] ) ) : '',
			'belt_color'    => isset( $_POST['belt_color'] ) ? sanitize_text_field( wp_unslash( $_POST['belt_color'] ) ) : '',
		);

		// Optional fields.
		if ( isset( $_POST['membership_type_id'] ) && ! empty( $_POST['membership_type_id'] ) ) {
			$data['membership_type_id'] = absint( wp_unslash( $_POST['membership_type_id'] ) );
		}

		if ( isset( $_POST['club_id'] ) && ! empty( $_POST['club_id'] ) ) {
			$data['club_id'] = absint( wp_unslash( $_POST['club_id'] ) );
		}

		if ( isset( $_POST['weight'] ) && ! empty( $_POST['weight'] ) ) {
			$data['weight'] = MACM_Member::weight_to_kg( floatval( wp_unslash( $_POST['weight'] ) ) );
		}

		if ( isset( $_POST['height'] ) && ! empty( $_POST['height'] ) ) {
			$data['height'] = MACM_Member::height_to_cm( floatval( wp_unslash( $_POST['height'] ) ) );
		}

		if ( isset( $_POST['license_number'] ) && ! empty( $_POST['license_number'] ) ) {
			$data['license_number'] = sanitize_text_field( wp_unslash( $_POST['license_number'] ) );
		}

		if ( isset( $_POST['license_expiration'] ) && ! empty( $_POST['license_expiration'] ) ) {
			// Validate: license_expiration requires license_number.
			if ( empty( $data['license_number'] ) ) {
				wp_send_json_error(
					array(
						'message' => __( 'License expiration date requires a license number. Please enter a license number first.', 'martial-arts-club-manager' ),
					)
				);
			}
			$data['license_expiration'] = sanitize_text_field( wp_unslash( $_POST['license_expiration'] ) );
		}

		if ( isset( $_POST['photo_id'] ) && ! empty( $_POST['photo_id'] ) ) {
			$data['photo_id'] = absint( wp_unslash( $_POST['photo_id'] ) );
		}

		// Create member.
		$member_id = MACM_Member::create( $user_id, $data );

		if ( is_wp_error( $member_id ) ) {
			wp_send_json_error( array( 'message' => $member_id->get_error_message() ) );
		}

		// Handle group assignments.
		$group_ids = array();
		if ( isset( $_POST['group_ids'] ) && is_array( $_POST['group_ids'] ) ) {
			$group_ids = array_map( 'absint', wp_unslash( $_POST['group_ids'] ) );
			$group_ids = array_filter( $group_ids ); // Remove zeros.
		}

		if ( ! empty( $group_ids ) ) {
			global $wpdb;
			$table_name = $wpdb->prefix . 'macm_member_groups';

			// Invalidate member groups cache before insertion.
			wp_cache_delete( 'macm_member_groups_' . $member_id, 'macm' );

			foreach ( $group_ids as $group_id ) {
				$wpdb->insert(
					$table_name,
					array(
						'member_id' => $member_id,
						'group_id'  => $group_id,
					),
					array( '%d', '%d' )
				);
			}
		}

		wp_send_json_success( array( 'message' => __( 'Member created successfully', 'martial-arts-club-manager' ) ) );
	}

	/**
	 * AJAX handler for admin edit member
	 */
	public function ajax_admin_edit_member() {
		// Verify nonce.
		check_ajax_referer( 'kcm-admin-nonce', 'nonce' );

		// Check permissions.
		if ( ! current_user_can( 'manage_macm_members' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions', 'martial-arts-club-manager' ) ) );
		}

		// Get member ID.
		$member_id = isset( $_POST['member_id'] ) ? absint( wp_unslash( $_POST['member_id'] ) ) : 0;
		if ( ! $member_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid member ID', 'martial-arts-club-manager' ) ) );
		}

		// Prepare data.
		$data = array(
			'full_name'     => isset( $_POST['full_name'] ) ? sanitize_text_field( wp_unslash( $_POST['full_name'] ) ) : '',
			'date_of_birth' => isset( $_POST['date_of_birth'] ) ? sanitize_text_field( wp_unslash( $_POST['date_of_birth'] ) ) : '',
			'belt_color'    => isset( $_POST['belt_color'] ) ? sanitize_text_field( wp_unslash( $_POST['belt_color'] ) ) : '',
		);

		// Optional fields.
		if ( isset( $_POST['membership_type_id'] ) && ! empty( $_POST['membership_type_id'] ) ) {
			$data['membership_type_id'] = absint( wp_unslash( $_POST['membership_type_id'] ) );
		} else {
			$data['membership_type_id'] = null;
		}

		if ( isset( $_POST['club_id'] ) && ! empty( $_POST['club_id'] ) ) {
			$data['club_id'] = absint( wp_unslash( $_POST['club_id'] ) );
		} else {
			$data['club_id'] = null;
		}

		// Handle multiple groups separately (not in $data).
		$group_ids = array();
		if ( isset( $_POST['group_ids'] ) && is_array( $_POST['group_ids'] ) ) {
			$group_ids = array_map( 'absint', wp_unslash( $_POST['group_ids'] ) );
			$group_ids = array_filter( $group_ids ); // Remove zeros.
		}

		if ( isset( $_POST['weight'] ) && ! empty( $_POST['weight'] ) ) {
			$data['weight'] = MACM_Member::weight_to_kg( floatval( wp_unslash( $_POST['weight'] ) ) );
		} else {
			$data['weight'] = null;
		}

		if ( isset( $_POST['height'] ) && ! empty( $_POST['height'] ) ) {
			$data['height'] = MACM_Member::height_to_cm( floatval( wp_unslash( $_POST['height'] ) ) );
		} else {
			$data['height'] = null;
		}

		if ( isset( $_POST['license_number'] ) && ! empty( $_POST['license_number'] ) ) {
			$data['license_number'] = sanitize_text_field( wp_unslash( $_POST['license_number'] ) );
		} else {
			$data['license_number'] = null;
		}

		if ( isset( $_POST['license_expiration'] ) && ! empty( $_POST['license_expiration'] ) ) {
			// Validate: license_expiration requires license_number.
			if ( empty( $data['license_number'] ) ) {
				wp_send_json_error(
					array(
						'message' => __( 'License expiration date requires a license number. Please enter a license number first.', 'martial-arts-club-manager' ),
					)
				);
			}
			$data['license_expiration'] = sanitize_text_field( wp_unslash( $_POST['license_expiration'] ) );
		} else {
			$data['license_expiration'] = null;
		}

		// Handle photo update.
		if ( isset( $_POST['photo_id'] ) ) {
			$new_photo_id   = ! empty( $_POST['photo_id'] ) ? absint( wp_unslash( $_POST['photo_id'] ) ) : null;
			$current_member = MACM_Member::get( $member_id );

			// Delete old photo if changed or removed.
			if ( $current_member && $current_member->photo_id && $current_member->photo_id !== $new_photo_id ) {
				wp_delete_attachment( $current_member->photo_id, true );
			}

			$data['photo_id'] = $new_photo_id;
		}

		// Update member.
		$updated = MACM_Member::update( $member_id, $data );

		if ( ! $updated ) {
			wp_send_json_error( array( 'message' => __( 'Error updating member', 'martial-arts-club-manager' ) ) );
		}

		// Update group assignments.
		global $wpdb;
		$table_name = $wpdb->prefix . 'macm_member_groups';

		// Invalidate member groups cache before modifications.
		wp_cache_delete( 'macm_member_groups_' . $member_id, 'macm' );

		// Delete existing group assignments.
		$wpdb->delete(
			$table_name,
			array( 'member_id' => $member_id ),
			array( '%d' )
		);

		// Insert new group assignments.
		if ( ! empty( $group_ids ) ) {
			foreach ( $group_ids as $group_id ) {
				$wpdb->insert(
					$table_name,
					array(
						'member_id' => $member_id,
						'group_id'  => $group_id,
					),
					array( '%d', '%d' )
				);
			}
		}

		wp_send_json_success( array( 'message' => __( 'Member updated successfully', 'martial-arts-club-manager' ) ) );
	}

	/**
	 * AJAX handler: Get user phone number
	 */
	public function ajax_get_user_phone() {
		// Verify nonce.
		check_ajax_referer( 'kcm-admin-nonce', 'nonce' );

		// Check permissions.
		if ( ! current_user_can( 'manage_macm_members' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions', 'martial-arts-club-manager' ) ) );
		}

		// Get user ID.
		$user_id = isset( $_POST['user_id'] ) ? absint( wp_unslash( $_POST['user_id'] ) ) : 0;
		if ( ! $user_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid user ID', 'martial-arts-club-manager' ) ) );
		}

		// Get phone number from user meta.
		$phone = get_user_meta( $user_id, 'macm_mobile_number', true );

		wp_send_json_success( array( 'phone' => $phone ) );
	}

	/**
	 * AJAX handler: Toggle member status (Archive/Activate)
	 */
	public function ajax_toggle_member_status() {
		// Verify nonce.
		check_ajax_referer( 'kcm-admin-nonce', 'nonce' );

		// Check permissions.
		if ( ! current_user_can( 'manage_macm_members' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions', 'martial-arts-club-manager' ) ) );
		}

		// Get member ID.
		$member_id = isset( $_POST['member_id'] ) ? absint( wp_unslash( $_POST['member_id'] ) ) : 0;
		if ( ! $member_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid member ID', 'martial-arts-club-manager' ) ) );
		}

		global $wpdb;

		// Get current member status with caching.
		$cache_key      = 'macm_member_status_' . $member_id;
		$current_status = wp_cache_get( $cache_key, 'macm' );

		if ( false === $current_status ) {
			$current_status = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT status FROM {$wpdb->prefix}macm_members WHERE id = %d",
					$member_id
				)
			);

			if ( null !== $current_status ) {
				wp_cache_set( $cache_key, $current_status, 'macm', 300 );
			}
		}

		if ( null === $current_status ) {
			wp_send_json_error( array( 'message' => __( 'Member not found', 'martial-arts-club-manager' ) ) );
		}

		// Toggle status.
		$new_status = ( 'active' === $current_status ) ? 'inactive' : 'active';

		// Invalidate status cache before update.
		wp_cache_delete( $cache_key, 'macm' );

		// Update member status.
		$updated = $wpdb->update(
			$wpdb->prefix . 'macm_members',
			array( 'status' => $new_status ),
			array( 'id' => $member_id ),
			array( '%s' ),
			array( '%d' )
		);

		if ( false === $updated ) {
			wp_send_json_error( array( 'message' => __( 'Error updating member status', 'martial-arts-club-manager' ) ) );
		}

		$message = ( 'active' === $new_status )
			? __( 'Member activated successfully', 'martial-arts-club-manager' )
			: __( 'Member archived successfully', 'martial-arts-club-manager' );

		wp_send_json_success( array( 'message' => $message ) );
	}

	/**
	 * Export members to CSV
	 *
	 * @since 1.0.20
	 */
	public function export_members_csv() {
		// Check nonce - verify before accessing any GET parameters.
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'macm_export_members' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'martial-arts-club-manager' ) );
		}

		// Check permissions.
		if ( ! current_user_can( 'manage_macm_members' ) ) {
			wp_die( esc_html__( 'You do not have permission to export members.', 'martial-arts-club-manager' ) );
		}

		// Clean all output buffers to prevent headers already sent.
		while ( ob_get_level() ) {
			ob_end_clean();
		}

		global $wpdb;

		// Determine filter values with flags for static WHERE pattern.
		// Status filter.
		$member_status = isset( $_GET['member_status'] ) && ! empty( $_GET['member_status'] ) ? sanitize_text_field( wp_unslash( $_GET['member_status'] ) ) : '';
		$apply_status  = ( ! empty( $member_status ) && 'all' !== $member_status ) ? 1 : 0;
		$status_value  = ( $apply_status ) ? $member_status : '';

		// Membership type filter (3 modes: 0=off, 1=filter by ID, 2=filter for NULL).
		$apply_membership_id   = 0;
		$membership_id_value   = 0;
		$apply_membership_null = 0;
		if ( ! empty( $_GET['membership_type'] ) ) {
			$membership_type = sanitize_text_field( wp_unslash( $_GET['membership_type'] ) );
			if ( 'none' === $membership_type ) {
				$apply_membership_null = 1;
			} elseif ( is_numeric( $membership_type ) ) {
				$apply_membership_id = 1;
				$membership_id_value = absint( $membership_type );
			}
		}

		// Club filter.
		$club_id_raw   = ! empty( $_GET['club_id'] ) ? absint( wp_unslash( $_GET['club_id'] ) ) : 0;
		$apply_club    = ( $club_id_raw > 0 ) ? 1 : 0;
		$club_id_value = $club_id_raw;

		// Belt color filter.
		$belt_color_raw   = ! empty( $_GET['belt_color'] ) ? sanitize_text_field( wp_unslash( $_GET['belt_color'] ) ) : '';
		$apply_belt       = ( ! empty( $belt_color_raw ) ) ? 1 : 0;
		$belt_color_value = $belt_color_raw;

		// Group filter.
		$group_id_raw   = ! empty( $_GET['group_id'] ) ? absint( wp_unslash( $_GET['group_id'] ) ) : 0;
		$apply_group    = ( $group_id_raw > 0 ) ? 1 : 0;
		$group_id_value = $group_id_raw;

		// Search filter.
		$search_term_raw   = ! empty( $_GET['macm_search'] ) ? sanitize_text_field( wp_unslash( $_GET['macm_search'] ) ) : '';
		$apply_search      = ( ! empty( $search_term_raw ) ) ? 1 : 0;
		$search_term_value = '%' . $wpdb->esc_like( $search_term_raw ) . '%';

		// Build cache key based on filters.
		$cache_key = 'macm_export_' . md5(
			$status_value . '_' . $apply_membership_id . '_' . $membership_id_value . '_' .
			$apply_membership_null . '_' . $club_id_value . '_' . $belt_color_value . '_' . $group_id_value . '_' . $search_term_raw
		);

		// Get all members matching filters with caching.
		$members = wp_cache_get( $cache_key, 'macm' );

		if ( false === $members ) {
			// Static query with conditional flags - no dynamic string building.
			// Each filter uses: (%d = 0 OR condition) pattern.
			// When flag=0, the OR short-circuits to TRUE, skipping the filter.
			// When flag=1, the condition is evaluated.
			$members = $wpdb->get_results(
				$wpdb->prepare(
					"SELECT DISTINCT m.*,
						u.display_name as user_name,
						u.user_email,
						c.club_name,
						mt.type_name as membership_type_name
					FROM {$wpdb->prefix}macm_members m
					LEFT JOIN {$wpdb->prefix}users u ON m.user_id = u.ID
					LEFT JOIN {$wpdb->prefix}macm_clubs c ON m.club_id = c.id
					LEFT JOIN {$wpdb->prefix}macm_membership_types mt ON m.membership_type_id = mt.id
					LEFT JOIN {$wpdb->prefix}macm_member_groups mg ON m.id = mg.member_id
					WHERE (%d = 0 OR m.status = %s)
					  AND (%d = 0 OR m.membership_type_id = %d)
					  AND (%d = 0 OR m.membership_type_id IS NULL)
					  AND (%d = 0 OR m.club_id = %d)
					  AND (%d = 0 OR m.belt_color = %s)
					  AND (%d = 0 OR mg.group_id = %d)
					  AND (%d = 0 OR (m.full_name LIKE %s OR u.display_name LIKE %s))
					ORDER BY m.full_name ASC",
					$apply_status,
					$status_value,
					$apply_membership_id,
					$membership_id_value,
					$apply_membership_null,
					$apply_club,
					$club_id_value,
					$apply_belt,
					$belt_color_value,
					$apply_group,
					$group_id_value,
					$apply_search,
					$search_term_value,
					$search_term_value
				)
			);

			if ( ! empty( $members ) ) {
				wp_cache_set( $cache_key, $members, 'macm', 60 );
			}
		}

		// Check if we have data to export.
		if ( empty( $members ) ) {
			wp_die( esc_html__( 'No data to export.', 'martial-arts-club-manager' ) );
		}

		// Get user meta for phone numbers.
		foreach ( $members as $member ) {
			$member->phone      = get_user_meta( $member->user_id, 'macm_mobile_number', true );
			$member->first_name = get_user_meta( $member->user_id, 'first_name', true );
			$member->last_name  = get_user_meta( $member->user_id, 'last_name', true );
		}

		// Set headers for CSV download.
		$filename = 'members-export-' . wp_date( 'Y-m-d-His' ) . '.csv';
		header( 'Content-Type: text/csv; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename=' . $filename );
		header( 'Pragma: no-cache' );
		header( 'Expires: 0' );

		// Create file pointer for output.
		$output = fopen( 'php://output', 'w' );

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

		// CSV headers.
		$headers = array(
			__( 'Full Name', 'martial-arts-club-manager' ),
			__( 'Date of Birth', 'martial-arts-club-manager' ),
			__( 'Belt Color', 'martial-arts-club-manager' ),
			__( 'Membership Type', 'martial-arts-club-manager' ),
			__( 'Club', 'martial-arts-club-manager' ),
			__( 'Status', 'martial-arts-club-manager' ),
			__( 'License Number', 'martial-arts-club-manager' ),
			__( 'License Expiration', 'martial-arts-club-manager' ),
			__( 'Weight (kg)', 'martial-arts-club-manager' ),
			__( 'Height (cm)', 'martial-arts-club-manager' ),
			__( 'User Name', 'martial-arts-club-manager' ),
			__( 'User First Name', 'martial-arts-club-manager' ),
			__( 'User Last Name', 'martial-arts-club-manager' ),
			__( 'User Email', 'martial-arts-club-manager' ),
			__( 'User Phone', 'martial-arts-club-manager' ),
			__( 'Created Date', 'martial-arts-club-manager' ),
		);

		fputcsv( $output, $headers );

		// Add member data.
		foreach ( $members as $member ) {
			// Format belt color.
			$belt_colors      = MACM_Member::get_belt_colors();
			$belt_color_label = isset( $belt_colors[ $member->belt_color ] ) ? $belt_colors[ $member->belt_color ] : $member->belt_color;

			// Format date of birth.
			$dob = '';
			if ( ! empty( $member->date_of_birth ) && '0000-00-00' !== $member->date_of_birth ) {
				$dob = date_i18n( get_option( 'date_format' ), strtotime( $member->date_of_birth ) );
			}

			// Format license expiration.
			$license_exp = '';
			if ( ! empty( $member->license_expiration ) && '0000-00-00' !== $member->license_expiration ) {
				$license_exp = date_i18n( get_option( 'date_format' ), strtotime( $member->license_expiration ) );
			}

			// Format created date.
			$created = '';
			if ( ! empty( $member->created_at ) ) {
				$created = date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $member->created_at ) );
			}

			$row = array(
				$member->full_name,
				$dob,
				$belt_color_label,
				$member->membership_type_name ? $member->membership_type_name : __( 'None', 'martial-arts-club-manager' ),
				$member->club_name ? $member->club_name : __( 'None', 'martial-arts-club-manager' ),
				ucfirst( $member->status ),
				$member->license_number ? $member->license_number : '',
				$license_exp,
				$member->weight ? $member->weight : '',
				$member->height ? $member->height : '',
				$member->user_name,
				$member->first_name,
				$member->last_name,
				$member->user_email,
				$member->phone ? $member->phone : '',
				$created,
			);

			fputcsv( $output, $row );
		}

		exit;
	}

	/**
	 * AJAX handler to get member details
	 */
	public function ajax_get_member_details() {
		// Verify nonce.
		check_ajax_referer( 'macm_get_member_details', 'nonce' );

		// Check permissions.
		if ( ! current_user_can( 'manage_macm_members' ) ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission to view member details.', 'martial-arts-club-manager' ) ) );
		}

		$member_id = isset( $_POST['member_id'] ) ? absint( wp_unslash( $_POST['member_id'] ) ) : 0;

		if ( ! $member_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid member ID.', 'martial-arts-club-manager' ) ) );
		}

		try {
			$this->get_member_details_response( $member_id );
		} catch ( \Throwable $e ) {
			wp_send_json_error(
				array(
					'message' => __( 'Error loading member details. Please try again or contact support.', 'martial-arts-club-manager' ),
					'debug'   => current_user_can( 'manage_options' ) ? $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine() : '',
				)
			);
		}
	}

	/**
	 * Build and send member details response.
	 *
	 * @param int $member_id Member ID.
	 */
	private function get_member_details_response( $member_id ) {
		global $wpdb;

		// Get member data with all related information.
		$cache_key = 'macm_member_details_' . $member_id;
		$member    = wp_cache_get( $cache_key, 'macm' );

		if ( false === $member ) {
			$member = $wpdb->get_row(
				$wpdb->prepare(
					'SELECT m.*,
						u.display_name as user_display_name,
						u.user_email as user_email,
						mt.type_name as membership_type_name,
						c.club_name as club_name,
						bc.color_name as belt_color_name
					FROM ' . $wpdb->prefix . 'macm_members m
					LEFT JOIN ' . $wpdb->prefix . 'users u ON m.user_id = u.ID
					LEFT JOIN ' . $wpdb->prefix . 'macm_membership_types mt ON m.membership_type_id = mt.id
					LEFT JOIN ' . $wpdb->prefix . 'macm_clubs c ON m.club_id = c.id
					LEFT JOIN ' . $wpdb->prefix . 'macm_belt_colors bc ON m.belt_color = bc.id
					WHERE m.id = %d',
					$member_id
				)
			);

			if ( $member ) {
				wp_cache_set( $cache_key, $member, 'macm', 300 );
			}
		}

		if ( ! $member ) {
			wp_send_json_error( array( 'message' => __( 'Member not found.', 'martial-arts-club-manager' ) ) );
		}

		// Get user's full name.
		$first_name = '';
		$last_name  = '';
		$phone      = '';
		if ( ! empty( $member->user_id ) ) {
			$first_name = get_user_meta( $member->user_id, 'first_name', true );
			$last_name  = get_user_meta( $member->user_id, 'last_name', true );
			$phone      = get_user_meta( $member->user_id, 'billing_phone', true );
		}

		if ( $first_name && $last_name ) {
			$user_full_name = $first_name . ' ' . $last_name;
		} elseif ( ! empty( $member->user_display_name ) ) {
			$user_full_name = $member->user_display_name;
		} else {
			$user_full_name = $member->full_name;
		}

		// Get member's groups.
		$groups_cache_key = 'macm_member_groups_' . $member_id;
		$groups           = wp_cache_get( $groups_cache_key, 'macm' );

		if ( false === $groups ) {
			$groups = $wpdb->get_results(
				$wpdb->prepare(
					'SELECT g.group_name
					FROM ' . $wpdb->prefix . 'macm_groups g
					INNER JOIN ' . $wpdb->prefix . 'macm_member_groups mg ON g.id = mg.group_id
					WHERE mg.member_id = %d AND g.is_active = 1',
					$member_id
				)
			);
			if ( ! is_array( $groups ) ) {
				$groups = array();
			}
			wp_cache_set( $groups_cache_key, $groups, 'macm', 300 );
		}

		$group_names = array();
		foreach ( $groups as $group ) {
			$group_names[] = $group->group_name;
		}

		// Premium-only data: class enrollments, attendance, events.
		$macm_premium_files_exist = file_exists( MACM_PLUGIN_DIR . 'includes/classes/class-macm-location.php' );
		$macm_is_premium          = function_exists( 'macm_fs' ) && macm_fs()->can_use_premium_code() && $macm_premium_files_exist;

		$class_enrollments   = array();
		$attendance_stats    = null;
		$event_registrations = array();

		if ( $macm_is_premium ) {
			// Get class enrollments.
			$enrollments_cache_key = 'macm_member_enrollments_' . $member_id;
			$class_enrollments     = wp_cache_get( $enrollments_cache_key, 'macm' );

			if ( false === $class_enrollments ) {
				$class_enrollments = $wpdb->get_results(
					$wpdb->prepare(
						'SELECT c.class_name, c.day_of_week, c.start_time, c.end_time, l.location_name
						FROM ' . $wpdb->prefix . 'macm_classes c
						INNER JOIN ' . $wpdb->prefix . 'macm_class_enrollments ce ON c.id = ce.class_id
						LEFT JOIN ' . $wpdb->prefix . 'macm_locations l ON c.location_id = l.id
						WHERE ce.member_id = %d AND c.is_archived = 0 AND ce.removed_at IS NULL
						ORDER BY c.day_of_week, c.start_time',
						$member_id
					)
				);
				if ( ! is_array( $class_enrollments ) ) {
					$class_enrollments = array();
				}
				wp_cache_set( $enrollments_cache_key, $class_enrollments, 'macm', 300 );
			}

			// Get attendance statistics.
			$attendance_cache_key = 'macm_member_attendance_stats_' . $member_id;
			$attendance_stats     = wp_cache_get( $attendance_cache_key, 'macm' );

			if ( false === $attendance_stats ) {
				$attendance_stats = $wpdb->get_row(
					$wpdb->prepare(
						'SELECT
							COUNT(*) as total_sessions,
							COUNT(*) as present_count,
							0 as absent_count,
							MAX(attendance_date) as last_attendance
						FROM ' . $wpdb->prefix . 'macm_attendance
						WHERE member_id = %d',
						$member_id
					)
				);
				wp_cache_set( $attendance_cache_key, $attendance_stats, 'macm', 300 );
			}

			// Get event registrations.
			$events_cache_key    = 'macm_member_events_' . $member_id;
			$event_registrations = wp_cache_get( $events_cache_key, 'macm' );

			if ( false === $event_registrations ) {
				$event_registrations = $wpdb->get_results(
					$wpdb->prepare(
						'SELECT e.title, e.start_date, e.end_date, er.registration_date
						FROM ' . $wpdb->prefix . 'macm_events e
						INNER JOIN ' . $wpdb->prefix . 'macm_event_registrations er ON e.id = er.event_id
						WHERE er.member_id = %d
						ORDER BY e.start_date DESC
						LIMIT 10',
						$member_id
					)
				);
				if ( ! is_array( $event_registrations ) ) {
					$event_registrations = array();
				}
				wp_cache_set( $events_cache_key, $event_registrations, 'macm', 300 );
			}
		}

		// Calculate age.
		$age = '';
		if ( ! empty( $member->date_of_birth ) ) {
			$dob = new DateTime( $member->date_of_birth );
			$now = new DateTime();
			$age = $now->diff( $dob )->y;
		}

		// Get photo URL.
		$photo_url = '';
		if ( ! empty( $member->photo_id ) ) {
			$photo_url = wp_get_attachment_url( $member->photo_id );
		}

		// Build HTML output.
		ob_start();
		?>
		<div class="kcm-member-details-container">
			<div class="kcm-member-details-header" style="display: flex; gap: 20px; margin-bottom: 30px; padding-bottom: 20px; border-bottom: 2px solid #D1D5DB;">
				<?php if ( $photo_url ) : ?>
					<div class="kcm-member-photo" style="flex-shrink: 0;">
						<img src="<?php echo esc_url( $photo_url ); ?>" alt="<?php echo esc_attr( $member->full_name ); ?>" style="width: 150px; height: 150px; object-fit: cover; border-radius: 8px; border: 3px solid #B11226;">
					</div>
				<?php endif; ?>
				<div class="kcm-member-basic-info" style="flex-grow: 1;">
					<h2 style="margin: 0 0 10px 0; font-size: 24px; color: #111827;"><?php echo esc_html( $member->full_name ); ?></h2>
					<div style="display: grid; grid-template-columns: auto 1fr; gap: 10px 20px; font-size: 14px;">
						<strong><?php esc_html_e( 'Status:', 'martial-arts-club-manager' ); ?></strong>
						<?php
						$member_status = isset( $member->status ) ? $member->status : 'active';
						?>
						<span style="<?php echo 'active' === $member_status ? 'color: #00a32a;' : 'color: #d63638;'; ?> font-weight: 600;">
							<?php echo esc_html( ucfirst( $member_status ) ); ?>
						</span>

						<?php if ( $age ) : ?>
							<strong><?php esc_html_e( 'Age:', 'martial-arts-club-manager' ); ?></strong>
							<span><?php echo esc_html( $age . ' years' ); ?></span>
						<?php endif; ?>

						<?php if ( ! empty( $member->belt_color_name ) ) : ?>
							<strong><?php esc_html_e( 'Belt Color:', 'martial-arts-club-manager' ); ?></strong>
							<span><?php echo esc_html( $member->belt_color_name ); ?></span>
						<?php endif; ?>

						<?php if ( ! empty( $member->membership_type_name ) ) : ?>
							<strong><?php esc_html_e( 'Membership Type:', 'martial-arts-club-manager' ); ?></strong>
							<span><?php echo esc_html( $member->membership_type_name ); ?></span>
						<?php endif; ?>

						<?php if ( ! empty( $group_names ) ) : ?>
							<strong><?php esc_html_e( 'Groups:', 'martial-arts-club-manager' ); ?></strong>
							<span><?php echo esc_html( implode( ', ', $group_names ) ); ?></span>
						<?php endif; ?>
					</div>
				</div>
			</div>

			<div class="kcm-member-details-sections" style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
				<!-- Personal Information -->
				<div class="kcm-details-section" style="background: #F4F4F2; padding: 20px; border-radius: 8px;">
					<h3 style="margin: 0 0 15px 0; color: #111827; font-size: 16px; border-bottom: 2px solid #B11226; padding-bottom: 8px;">
						<?php esc_html_e( 'Personal Information', 'martial-arts-club-manager' ); ?>
					</h3>
					<div style="display: grid; grid-template-columns: auto 1fr; gap: 10px; font-size: 14px;">
						<?php if ( ! empty( $member->date_of_birth ) ) : ?>
							<strong><?php esc_html_e( 'Date of Birth:', 'martial-arts-club-manager' ); ?></strong>
							<span><?php echo esc_html( date_i18n( 'F j, Y', strtotime( $member->date_of_birth ) ) ); ?></span>
						<?php endif; ?>

						<?php if ( ! empty( $member->weight ) && class_exists( 'MACM_Member' ) ) : ?>
							<strong><?php esc_html_e( 'Weight:', 'martial-arts-club-manager' ); ?></strong>
							<span><?php echo esc_html( MACM_Member::format_weight( $member->weight ) ); ?></span>
						<?php endif; ?>

						<?php if ( ! empty( $member->height ) && class_exists( 'MACM_Member' ) ) : ?>
							<strong><?php esc_html_e( 'Height:', 'martial-arts-club-manager' ); ?></strong>
							<span><?php echo esc_html( MACM_Member::format_height( $member->height ) ); ?></span>
						<?php endif; ?>

						<?php if ( ! empty( $member->license_number ) ) : ?>
							<strong><?php esc_html_e( 'License Number:', 'martial-arts-club-manager' ); ?></strong>
							<span><?php echo esc_html( $member->license_number ); ?></span>
						<?php endif; ?>

						<?php if ( ! empty( $member->license_expiration ) ) : ?>
							<strong><?php esc_html_e( 'License Expiry:', 'martial-arts-club-manager' ); ?></strong>
							<span><?php echo esc_html( date_i18n( 'F j, Y', strtotime( $member->license_expiration ) ) ); ?></span>
						<?php endif; ?>
					</div>
				</div>

				<!-- User Account Information -->
				<div class="kcm-details-section" style="background: #F4F4F2; padding: 20px; border-radius: 8px;">
					<h3 style="margin: 0 0 15px 0; color: #111827; font-size: 16px; border-bottom: 2px solid #B11226; padding-bottom: 8px;">
						<?php esc_html_e( 'Associated User Account', 'martial-arts-club-manager' ); ?>
					</h3>
					<div style="display: grid; grid-template-columns: auto 1fr; gap: 10px; font-size: 14px;">
						<strong><?php esc_html_e( 'Name:', 'martial-arts-club-manager' ); ?></strong>
						<span><?php echo esc_html( $user_full_name ); ?></span>

						<?php if ( ! empty( $member->user_email ) ) : ?>
							<strong><?php esc_html_e( 'Email:', 'martial-arts-club-manager' ); ?></strong>
							<span><a href="mailto:<?php echo esc_attr( $member->user_email ); ?>"><?php echo esc_html( $member->user_email ); ?></a></span>
						<?php endif; ?>

						<?php if ( $phone ) : ?>
							<strong><?php esc_html_e( 'Phone:', 'martial-arts-club-manager' ); ?></strong>
							<span><?php echo esc_html( $phone ); ?></span>
						<?php endif; ?>
					</div>
				</div>

				<?php if ( $macm_is_premium ) : ?>
					<!-- Class Enrollments -->
					<div class="kcm-details-section" style="background: #F4F4F2; padding: 20px; border-radius: 8px;">
						<h3 style="margin: 0 0 15px 0; color: #111827; font-size: 16px; border-bottom: 2px solid #B11226; padding-bottom: 8px;">
							<?php
							/* translators: %d: number of classes */
							printf( esc_html__( 'Class Enrollments (%d)', 'martial-arts-club-manager' ), count( $class_enrollments ) );
							?>
						</h3>
						<?php if ( ! empty( $class_enrollments ) ) : ?>
							<ul style="margin: 0; padding-left: 20px; font-size: 14px;">
								<?php foreach ( $class_enrollments as $class ) : ?>
									<li style="margin-bottom: 8px;">
										<strong><?php echo esc_html( $class->class_name ); ?></strong><br>
										<span style="color: #6B7280;">
											<?php
											if ( class_exists( 'MACM_Class' ) ) {
												echo esc_html( MACM_Class::get_day_name( $class->day_of_week ) );
											}
											echo ' ';
											echo esc_html( date_i18n( 'g:i A', strtotime( $class->start_time ) ) );
											echo ' - ';
											echo esc_html( date_i18n( 'g:i A', strtotime( $class->end_time ) ) );
											?>
											<?php if ( $class->location_name ) : ?>
												<br><?php echo esc_html( $class->location_name ); ?>
											<?php endif; ?>
										</span>
									</li>
								<?php endforeach; ?>
							</ul>
						<?php else : ?>
							<p style="margin: 0; color: #6B7280; font-style: italic;"><?php esc_html_e( 'Not enrolled in any classes', 'martial-arts-club-manager' ); ?></p>
						<?php endif; ?>
					</div>

					<!-- Attendance Statistics -->
					<div class="kcm-details-section" style="background: #F4F4F2; padding: 20px; border-radius: 8px;">
						<h3 style="margin: 0 0 15px 0; color: #111827; font-size: 16px; border-bottom: 2px solid #B11226; padding-bottom: 8px;">
							<?php esc_html_e( 'Attendance Statistics', 'martial-arts-club-manager' ); ?>
						</h3>
						<?php if ( $attendance_stats && $attendance_stats->total_sessions > 0 ) : ?>
							<div style="display: grid; grid-template-columns: auto 1fr; gap: 10px; font-size: 14px;">
								<strong><?php esc_html_e( 'Total Sessions Attended:', 'martial-arts-club-manager' ); ?></strong>
								<span style="color: #00a32a; font-weight: 600;"><?php echo esc_html( $attendance_stats->total_sessions ); ?></span>

								<?php if ( $attendance_stats->last_attendance ) : ?>
									<strong><?php esc_html_e( 'Last Attendance:', 'martial-arts-club-manager' ); ?></strong>
									<span><?php echo esc_html( date_i18n( 'F j, Y', strtotime( $attendance_stats->last_attendance ) ) ); ?></span>
								<?php endif; ?>
							</div>
						<?php else : ?>
							<p style="margin: 0; color: #6B7280; font-style: italic;"><?php esc_html_e( 'No attendance records yet', 'martial-arts-club-manager' ); ?></p>
						<?php endif; ?>
					</div>

					<!-- Event Registrations -->
					<?php if ( ! empty( $event_registrations ) ) : ?>
						<div class="kcm-details-section" style="background: #F4F4F2; padding: 20px; border-radius: 8px; grid-column: 1 / -1;">
							<h3 style="margin: 0 0 15px 0; color: #111827; font-size: 16px; border-bottom: 2px solid #B11226; padding-bottom: 8px;">
								<?php
								/* translators: %d: number of events */
								printf( esc_html__( 'Event Registration History (Last %d)', 'martial-arts-club-manager' ), count( $event_registrations ) );
								?>
							</h3>
							<ul style="margin: 0; padding-left: 20px; font-size: 14px;">
								<?php foreach ( $event_registrations as $event ) : ?>
									<li style="margin-bottom: 8px;">
										<strong><?php echo esc_html( $event->title ); ?></strong>
										<span style="color: #6B7280;">
											- <?php echo esc_html( date_i18n( 'M j, Y', strtotime( $event->start_date ) ) ); ?>
											<?php if ( $event->start_date !== $event->end_date ) : ?>
												to <?php echo esc_html( date_i18n( 'M j, Y', strtotime( $event->end_date ) ) ); ?>
											<?php endif; ?>
										</span>
									</li>
								<?php endforeach; ?>
							</ul>
						</div>
					<?php endif; ?>
				<?php endif; ?>
			</div>
		</div>
		<?php
		$html = ob_get_clean();

		wp_send_json_success( array( 'html' => $html ) );
	}
}
