<?php
/**
 * Events Public Class
 *
 * Handles the frontend events display and member registration
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/includes/public
 * @since      1.0.73
 */

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

/**
 * Events Frontend Class
 *
 * @since 1.0.73
 */
class MACM_Events {

	/**
	 * Page ID for events page
	 *
	 * @var int
	 */
	private $page_id;

	/**
	 * Initialize the class
	 *
	 * @since 1.0.73
	 */
	public function __construct() {
		add_shortcode( 'macm_events', array( $this, 'render_events_list' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'wp_ajax_macm_register_to_event', array( $this, 'handle_event_registration' ) );
	}

	/**
	 * Enqueue scripts and styles
	 *
	 * @since 1.0.73
	 */
	public function enqueue_scripts() {
		if ( is_page( 'events-competitions' ) || has_shortcode( get_post()->post_content ?? '', 'macm_events' ) ) {
			wp_enqueue_style(
				'kcm-events',
				plugins_url( 'assets/css/events.css', dirname( __DIR__ ) ),
				array(),
				'1.0.73'
			);

			// Add dynamic button gradient CSS.
			$button_gradient_start_raw = get_option( 'macm_button_gradient_start', '#B11226' );
			$button_gradient_end_raw   = get_option( 'macm_button_gradient_end', '#8F0E1E' );

			// Sanitize hex colors - fall back to defaults if invalid.
			$button_gradient_start = sanitize_hex_color( $button_gradient_start_raw );
			$button_gradient_end   = sanitize_hex_color( $button_gradient_end_raw );

			if ( ! $button_gradient_start ) {
				$button_gradient_start = '#B11226';
			}
			if ( ! $button_gradient_end ) {
				$button_gradient_end = '#8F0E1E';
			}

			$custom_css = sprintf(
				'.kcm-btn-primary,
				.kcm-event-attend-btn {
					background: linear-gradient(135deg, %s 0%%, %s 100%%) !important;
				}',
				esc_attr( $button_gradient_start ),
				esc_attr( $button_gradient_end )
			);

			wp_add_inline_style( 'kcm-events', $custom_css );

			wp_enqueue_script(
				'kcm-events',
				plugins_url( 'assets/js/events.js', dirname( __DIR__ ) ),
				array( 'jquery' ),
				'1.0.73',
				true
			);

			// Build registrations map for JS (event_id => array of member_ids).
			$registrations_for_js = array();
			if ( is_user_logged_in() ) {
				$js_user_id   = get_current_user_id();
				$js_cache_key = 'macm_user_event_regs_' . $js_user_id;
				$js_regs      = wp_cache_get( $js_cache_key, 'macm' );

				if ( false === $js_regs ) {
					global $wpdb;
					$js_regs = $wpdb->get_results(
						$wpdb->prepare(
							'SELECT event_id, member_id FROM %i WHERE user_id = %d',
							$wpdb->prefix . 'macm_event_registrations',
							$js_user_id
						)
					);
					wp_cache_set( $js_cache_key, $js_regs, 'macm', 5 * MINUTE_IN_SECONDS );
				}

				if ( ! empty( $js_regs ) ) {
					foreach ( $js_regs as $js_reg ) {
						$ev_id = (string) $js_reg->event_id;
						if ( ! isset( $registrations_for_js[ $ev_id ] ) ) {
							$registrations_for_js[ $ev_id ] = array();
						}
						$registrations_for_js[ $ev_id ][] = (string) $js_reg->member_id;
					}
				}
			}

			wp_localize_script(
				'kcm-events',
				'macmEvents',
				array(
					'ajaxurl'       => admin_url( 'admin-ajax.php' ),
					'nonce'         => wp_create_nonce( 'macm_events_nonce' ),
					'registrations' => $registrations_for_js,
				)
			);
		}
	}

	/**
	 * Render events list
	 *
	 * @since 1.0.73
	 * @return string HTML output.
	 */
	public function render_events_list() {
		global $wpdb;

		// Get current user.
		$current_user = wp_get_current_user();
		$user_id      = $current_user->ID;

		// Get all active events that haven't ended yet (show even if registration closed).
		// Use today's date for cache key to invalidate daily.
		$today            = current_time( 'Y-m-d' );
		$events_cache_key = 'macm_active_events_' . $today;
		$events           = wp_cache_get( $events_cache_key, 'macm' );

		if ( false === $events ) {
			$events = $wpdb->get_results(
				$wpdb->prepare(
					'SELECT * FROM %i WHERE status = %s AND end_date >= CURDATE() ORDER BY start_date ASC, event_time ASC',
					$wpdb->prefix . 'macm_events',
					'active'
				)
			);
			wp_cache_set( $events_cache_key, $events, 'macm', HOUR_IN_SECONDS );
		}

		// Get user's members if logged in.
		$user_members = array();
		if ( $user_id ) {
			$members_cache_key = 'macm_user_members_' . $user_id;
			$user_members      = wp_cache_get( $members_cache_key, 'macm' );

			if ( false === $user_members ) {
				$user_members = $wpdb->get_results(
					$wpdb->prepare(
						'SELECT id, full_name, status FROM %i WHERE user_id = %d ORDER BY full_name ASC',
						$wpdb->prefix . 'macm_members',
						$user_id
					)
				);
				wp_cache_set( $members_cache_key, $user_members, 'macm', HOUR_IN_SECONDS );
			}
		}

		// Get registrations for this user.
		$user_registrations = array();
		if ( $user_id ) {
			$reg_cache_key = 'macm_user_event_regs_' . $user_id;
			$registrations = wp_cache_get( $reg_cache_key, 'macm' );

			if ( false === $registrations ) {
				$registrations = $wpdb->get_results(
					$wpdb->prepare(
						'SELECT event_id, member_id FROM %i WHERE user_id = %d',
						$wpdb->prefix . 'macm_event_registrations',
						$user_id
					)
				);
				wp_cache_set( $reg_cache_key, $registrations, 'macm', 5 * MINUTE_IN_SECONDS );
			}

			foreach ( $registrations as $reg ) {
				if ( ! isset( $user_registrations[ $reg->event_id ] ) ) {
					$user_registrations[ $reg->event_id ] = array();
				}
				$user_registrations[ $reg->event_id ][] = $reg->member_id;
			}
		}

		ob_start();
		include MACM_PLUGIN_DIR . 'templates/public/events-list.php';
		return ob_get_clean();
	}

	/**
	 * Handle event registration submission
	 *
	 * @since 1.0.73
	 */
	public function handle_event_registration() {
		// Verify nonce.
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'macm_events_nonce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'martial-arts-club-manager' ) ) );
		}

		// Check if user is logged in.
		if ( ! is_user_logged_in() ) {
			wp_send_json_error( array( 'message' => __( 'You must be logged in to register for events.', 'martial-arts-club-manager' ) ) );
		}

		$user_id = get_current_user_id();

		// Sanitize and validate input.
		$event_id   = isset( $_POST['event_id'] ) ? absint( wp_unslash( $_POST['event_id'] ) ) : 0;
		$member_ids = isset( $_POST['member_ids'] ) && is_array( $_POST['member_ids'] ) ? array_map( 'absint', wp_unslash( $_POST['member_ids'] ) ) : array();

		// Validation.
		$errors = array();

		if ( empty( $event_id ) ) {
			$errors[] = __( 'Event ID is required.', 'martial-arts-club-manager' );
		}

		if ( empty( $member_ids ) ) {
			$errors[] = __( 'Please select at least one member.', 'martial-arts-club-manager' );
		}

		if ( ! empty( $errors ) ) {
			wp_send_json_error( array( 'message' => implode( '<br>', $errors ) ) );
		}

		global $wpdb;

		// Verify event exists and is active.
		$event = $wpdb->get_row(
			$wpdb->prepare(
				'SELECT * FROM %i WHERE id = %d AND status = %s',
				$wpdb->prefix . 'macm_events',
				$event_id,
				'active'
			)
		);

		if ( ! $event ) {
			wp_send_json_error( array( 'message' => __( 'Event not found or is no longer active.', 'martial-arts-club-manager' ) ) );
		}

		// Check if event has passed closing date.
		if ( ! empty( $event->closing_date ) ) {
			$today = current_time( 'Y-m-d' );
			if ( $today > $event->closing_date ) {
				wp_send_json_error( array( 'message' => __( 'Registration for this event has closed.', 'martial-arts-club-manager' ) ) );
			}
		}

		// Process each member registration.
		$registered_count   = 0;
		$already_registered = array();
		$registered_members = array();

		foreach ( $member_ids as $member_id ) {
			// Verify member belongs to this user.
			$member = $wpdb->get_row(
				$wpdb->prepare(
					'SELECT * FROM %i WHERE id = %d AND user_id = %d',
					$wpdb->prefix . 'macm_members',
					$member_id,
					$user_id
				)
			);

			if ( ! $member ) {
				continue; // Skip invalid member.
			}

			// Skip archived (inactive) members.
			if ( isset( $member->status ) && 'active' !== $member->status ) {
				continue;
			}

			// Check if already registered.
			$existing = $wpdb->get_var(
				$wpdb->prepare(
					'SELECT id FROM %i WHERE event_id = %d AND member_id = %d',
					$wpdb->prefix . 'macm_event_registrations',
					$event_id,
					$member_id
				)
			);

			if ( $existing ) {
				$already_registered[] = $member->full_name;
				continue; // Skip already registered member.
			}

			// Insert registration.
			$inserted = $wpdb->insert(
				$wpdb->prefix . 'macm_event_registrations',
				array(
					'event_id'          => $event_id,
					'user_id'           => $user_id,
					'member_id'         => $member_id,
					'registration_date' => current_time( 'mysql' ),
					'status'            => 'confirmed',
				),
				array( '%d', '%d', '%d', '%s', '%s' )
			);

			if ( $inserted ) {
				++$registered_count;
				$registered_members[] = $member;
			}
		}

		// Build response message.
		$messages = array();

		if ( $registered_count > 0 ) {
			if ( 1 === $registered_count ) {
				$messages[] = __( '1 member registered successfully!', 'martial-arts-club-manager' );
			} else {
				/* translators: %d: number of members */
				$messages[] = sprintf( __( '%d members registered successfully!', 'martial-arts-club-manager' ), $registered_count );
			}

			// Clear user registration cache.
			wp_cache_delete( 'macm_user_event_regs_' . $user_id, 'macm' );

			// Send notification emails.
			$this->send_admin_notification_email( $event, $registered_members, $user_id );
			$this->send_user_confirmation_email( $event, $registered_members, $user_id );
		}

		if ( ! empty( $already_registered ) ) {
			if ( 1 === count( $already_registered ) ) {
				/* translators: %s: member name */
				$messages[] = sprintf( __( '%s is already registered for this event.', 'martial-arts-club-manager' ), $already_registered[0] );
			} else {
				$messages[] = sprintf(
					/* translators: %s: comma-separated list of member names */
					__( 'These members are already registered: %s', 'martial-arts-club-manager' ),
					implode( ', ', $already_registered )
				);
			}
		}

		if ( $registered_count > 0 ) {
			wp_send_json_success( array( 'message' => implode( '<br>', $messages ) ) );
		} elseif ( ! empty( $already_registered ) ) {
				wp_send_json_error( array( 'message' => implode( '<br>', $messages ) ) );
		} else {
			wp_send_json_error( array( 'message' => __( 'Failed to register for event. Please try again.', 'martial-arts-club-manager' ) ) );
		}
	}

	/**
	 * Send admin notification email
	 *
	 * @since 1.0.73
	 * @param object       $event    Event object.
	 * @param array|object $members  Member object(s) - single object or array of objects.
	 * @param int          $user_id  User ID.
	 */
	private function send_admin_notification_email( $event, $members, $user_id ) {
		// Ensure $members is an array.
		if ( ! is_array( $members ) ) {
			$members = array( $members );
		}
		// Get notification email(s) from event, falling back to global events setting.
		$event_notification = isset( $event->notification_email ) ? trim( $event->notification_email ) : '';
		$event_email        = ! empty( $event_notification ) ? $event_notification : get_option( 'macm_events_notification_email', '' );
		$to                 = macm_parse_notification_emails( $event_email );

		// Get gradient colors from settings.
		$gradient_start = get_option( 'macm_email_gradient_start', '#B11226' );
		$gradient_end   = get_option( 'macm_email_gradient_end', '#8F0E1E' );
		$gradient_style = sprintf( 'background: linear-gradient(135deg, %s 0%%, %s 100%%)', esc_attr( $gradient_start ), esc_attr( $gradient_end ) );

		$site_name      = get_bloginfo( 'name' );
		$site_logo_html = $this->get_site_logo_html();

		// Get user info.
		$user = get_userdata( $user_id );
		// Get full name from multiple sources with fallbacks.
		$first_name = $user ? get_user_meta( $user_id, 'first_name', true ) : '';
		$last_name  = $user ? get_user_meta( $user_id, 'last_name', true ) : '';

		// If empty, try billing fields (WooCommerce).
		if ( empty( $first_name ) ) {
			$first_name = get_user_meta( $user_id, 'billing_first_name', true );
		}
		if ( empty( $last_name ) ) {
			$last_name = get_user_meta( $user_id, 'billing_last_name', true );
		}

		$user_name = trim( $first_name . ' ' . $last_name );

		// If still empty, use display_name as final fallback.
		if ( empty( $user_name ) && $user ) {
			$user_name = $user->display_name;
		}

		$user_email = $user ? $user->user_email : '';

		// Prepare email subject.
		/* translators: %s: event title */
		$subject = sprintf( __( 'New Event Registration - %s', 'martial-arts-club-manager' ), $event->title );

		// Build admin panel link.
		$admin_link = admin_url( 'admin.php?page=kcm-events&action=view_registrations&event_id=' . $event->id );

		// Build email body.
		$body  = '<h2 style="color: #111827; font-size: 20px; margin-bottom: 20px;">' . __( 'New Event Registration', 'martial-arts-club-manager' ) . '</h2>';
		$body .= '<table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">';

		// Event details.
		$body                .= '<tr><td colspan="2" style="padding: 15px 10px 5px 10px; font-weight: 600; font-size: 14px; color: #6B7280;">' . __( 'Event Information', 'martial-arts-club-manager' ) . '</td></tr>';
		$body                .= '<tr><td style="padding: 10px; padding-left: 20px; border-bottom: 1px solid #D1D5DB; font-weight: 600; width: 35%;">' . __( 'Event:', 'martial-arts-club-manager' ) . '</td>';
		$body                .= '<td style="padding: 10px; border-bottom: 1px solid #D1D5DB;">' . esc_html( $event->title ) . '</td></tr>';
		$body                .= '<tr><td style="padding: 10px; padding-left: 20px; border-bottom: 1px solid #D1D5DB; font-weight: 600;">' . __( 'Date:', 'martial-arts-club-manager' ) . '</td>';
		$start_date_formatted = date_i18n( get_option( 'date_format' ), strtotime( $event->start_date ) );
		$end_date_formatted   = date_i18n( get_option( 'date_format' ), strtotime( $event->end_date ) );
		if ( $event->start_date === $event->end_date ) {
			$body .= '<td style="padding: 10px; border-bottom: 1px solid #D1D5DB;">' . esc_html( $start_date_formatted ) . '</td></tr>';
		} else {
			$body .= '<td style="padding: 10px; border-bottom: 1px solid #D1D5DB;">' . esc_html( $start_date_formatted . ' - ' . $end_date_formatted ) . '</td></tr>';
		}

		if ( ! empty( $event->event_time ) ) {
			$body .= '<tr><td style="padding: 10px; padding-left: 20px; border-bottom: 1px solid #D1D5DB; font-weight: 600;">' . __( 'Time:', 'martial-arts-club-manager' ) . '</td>';
			$body .= '<td style="padding: 10px; border-bottom: 1px solid #D1D5DB;">' . esc_html( date_i18n( get_option( 'time_format' ), strtotime( $event->event_time ) ) ) . '</td></tr>';
		}

		if ( ! empty( $event->location ) ) {
			$body .= '<tr><td style="padding: 10px; padding-left: 20px; border-bottom: 1px solid #D1D5DB; font-weight: 600;">' . __( 'Location:', 'martial-arts-club-manager' ) . '</td>';
			$body .= '<td style="padding: 10px; border-bottom: 1px solid #D1D5DB;">' . esc_html( $event->location ) . '</td></tr>';
		}

		// Member details.
		$member_label = 1 === count( $members ) ? __( 'Member Information', 'martial-arts-club-manager' ) : __( 'Members Information', 'martial-arts-club-manager' );
		$body        .= '<tr><td colspan="2" style="padding: 15px 10px 5px 10px; font-weight: 600; font-size: 14px; color: #6B7280;">' . $member_label . '</td></tr>';

		if ( 1 === count( $members ) ) {
			$body .= '<tr><td style="padding: 10px; padding-left: 20px; border-bottom: 1px solid #D1D5DB; font-weight: 600;">' . __( 'Member Name:', 'martial-arts-club-manager' ) . '</td>';
			$body .= '<td style="padding: 10px; border-bottom: 1px solid #D1D5DB;">' . esc_html( $members[0]->full_name ) . '</td></tr>';
		} else {
			$body .= '<tr><td style="padding: 10px; padding-left: 20px; border-bottom: 1px solid #D1D5DB; font-weight: 600;">' . __( 'Registered Members:', 'martial-arts-club-manager' ) . '</td>';
			$body .= '<td style="padding: 10px; border-bottom: 1px solid #D1D5DB;"><ul style="margin: 0; padding-left: 20px;">';
			foreach ( $members as $member ) {
				$body .= '<li>' . esc_html( $member->full_name ) . '</li>';
			}
			$body .= '</ul></td></tr>';
		}

		// User details.
		$body .= '<tr><td colspan="2" style="padding: 15px 10px 5px 10px; font-weight: 600; font-size: 14px; color: #6B7280;">' . __( 'Registered By', 'martial-arts-club-manager' ) . '</td></tr>';
		$body .= '<tr><td style="padding: 10px; padding-left: 20px; border-bottom: 1px solid #D1D5DB; font-weight: 600;">' . __( 'Full Name:', 'martial-arts-club-manager' ) . '</td>';
		$body .= '<td style="padding: 10px; border-bottom: 1px solid #D1D5DB;">' . esc_html( $user_name ) . '</td></tr>';
		$body .= '<tr><td style="padding: 10px; padding-left: 20px; border-bottom: 1px solid #D1D5DB; font-weight: 600;">' . __( 'User Email:', 'martial-arts-club-manager' ) . '</td>';
		$body .= '<td style="padding: 10px; border-bottom: 1px solid #D1D5DB;"><a href="mailto:' . esc_attr( $user_email ) . '" style="color: #B11226; text-decoration: none;">' . esc_html( $user_email ) . '</a></td></tr>';

		$body .= '</table>';

		$body .= '<p style="margin: 20px 0;"><a href="' . esc_url( $admin_link ) . '" style="display: inline-block; background: linear-gradient(135deg, ' . esc_attr( $gradient_start ) . ' 0%, ' . esc_attr( $gradient_end ) . ' 100%); color: #ffffff; text-decoration: none; padding: 12px 30px; border-radius: 4px; font-weight: 600;">' . __( 'View All Registrations', 'martial-arts-club-manager' ) . '</a></p>';

		// Format email with template.
		$email_content = $this->format_email_template( $body, $gradient_style, $site_name, $site_logo_html );

		// Send email.
		$headers = array( 'Content-Type: text/html; charset=UTF-8' );
		$sent    = wp_mail( $to, $subject, $email_content, $headers );
	}

	/**
	 * Send user confirmation email
	 *
	 * @since 1.0.73
	 * @param object       $event    Event object.
	 * @param array|object $members  Member object(s) - single object or array of objects.
	 * @param int          $user_id  User ID.
	 */
	private function send_user_confirmation_email( $event, $members, $user_id ) {
		// Ensure $members is an array.
		if ( ! is_array( $members ) ) {
			$members = array( $members );
		}
		$user = get_userdata( $user_id );
		if ( ! $user || empty( $user->user_email ) || ! is_email( $user->user_email ) ) {
			return;
		}

		$to = $user->user_email;

		// Get gradient colors from settings.
		$gradient_start = get_option( 'macm_email_gradient_start', '#B11226' );
		$gradient_end   = get_option( 'macm_email_gradient_end', '#8F0E1E' );
		$gradient_style = sprintf( 'background: linear-gradient(135deg, %s 0%%, %s 100%%)', esc_attr( $gradient_start ), esc_attr( $gradient_end ) );

		$site_name      = get_bloginfo( 'name' );
		$site_logo_html = $this->get_site_logo_html();

		// Prepare email subject.
		/* translators: %s: event title */
		$subject = sprintf( __( 'Event Registration Confirmation - %s', 'martial-arts-club-manager' ), $event->title );

		// Build email body.
		$body  = '<h2 style="color: #111827; font-size: 20px; margin-bottom: 10px;">' . __( 'Registration Confirmed!', 'martial-arts-club-manager' ) . '</h2>';
		$body .= '<p style="color: #6B7280; font-size: 16px; line-height: 1.6; margin-bottom: 20px;">' . __( 'Your registration for the following event has been confirmed:', 'martial-arts-club-manager' ) . '</p>';

		$body .= '<h3 style="color: #111827; font-size: 18px; margin-top: 30px; margin-bottom: 15px;">' . __( 'Event Details:', 'martial-arts-club-manager' ) . '</h3>';
		$body .= '<table style="width: 100%; border-collapse: collapse; margin-bottom: 20px; background-color: #F4F4F2; border-radius: 4px;">';

		$body .= '<tr><td style="padding: 12px 15px; border-bottom: 1px solid #D1D5DB; font-weight: 600; width: 35%; color: #6B7280;">' . __( 'Event:', 'martial-arts-club-manager' ) . '</td>';
		$body .= '<td style="padding: 12px 15px; border-bottom: 1px solid #D1D5DB; color: #111827;">' . esc_html( $event->title ) . '</td></tr>';

		$body                .= '<tr><td style="padding: 12px 15px; border-bottom: 1px solid #D1D5DB; font-weight: 600; color: #6B7280;">' . __( 'Date:', 'martial-arts-club-manager' ) . '</td>';
		$start_date_formatted = date_i18n( get_option( 'date_format' ), strtotime( $event->start_date ) );
		$end_date_formatted   = date_i18n( get_option( 'date_format' ), strtotime( $event->end_date ) );
		if ( $event->start_date === $event->end_date ) {
			$body .= '<td style="padding: 12px 15px; border-bottom: 1px solid #D1D5DB; color: #111827;">' . esc_html( $start_date_formatted ) . '</td></tr>';
		} else {
			$body .= '<td style="padding: 12px 15px; border-bottom: 1px solid #D1D5DB; color: #111827;">' . esc_html( $start_date_formatted . ' - ' . $end_date_formatted ) . '</td></tr>';
		}

		if ( ! empty( $event->event_time ) ) {
			$body .= '<tr><td style="padding: 12px 15px; border-bottom: 1px solid #D1D5DB; font-weight: 600; color: #6B7280;">' . __( 'Time:', 'martial-arts-club-manager' ) . '</td>';
			$body .= '<td style="padding: 12px 15px; border-bottom: 1px solid #D1D5DB; color: #111827;">' . esc_html( date_i18n( get_option( 'time_format' ), strtotime( $event->event_time ) ) ) . '</td></tr>';
		}

		if ( ! empty( $event->location ) ) {
			$body .= '<tr><td style="padding: 12px 15px; border-bottom: 1px solid #D1D5DB; font-weight: 600; color: #6B7280;">' . __( 'Location:', 'martial-arts-club-manager' ) . '</td>';
			$body .= '<td style="padding: 12px 15px; border-bottom: 1px solid #D1D5DB; color: #111827;">' . esc_html( $event->location ) . '</td></tr>';
		}

		if ( ! empty( $event->cost_info ) ) {
			$body .= '<tr><td style="padding: 12px 15px; border-bottom: 1px solid #D1D5DB; font-weight: 600; color: #6B7280;">' . __( 'Cost:', 'martial-arts-club-manager' ) . '</td>';
			$body .= '<td style="padding: 12px 15px; border-bottom: 1px solid #D1D5DB; color: #111827;">' . esc_html( $event->cost_info ) . '</td></tr>';
		}

		if ( 1 === count( $members ) ) {
			$body .= '<tr><td style="padding: 12px 15px; font-weight: 600; color: #6B7280;">' . __( 'Registered Member:', 'martial-arts-club-manager' ) . '</td>';
			$body .= '<td style="padding: 12px 15px; color: #111827;">' . esc_html( $members[0]->full_name ) . '</td></tr>';
		} else {
			$body .= '<tr><td style="padding: 12px 15px; font-weight: 600; color: #6B7280; vertical-align: top;">' . __( 'Registered Members:', 'martial-arts-club-manager' ) . '</td>';
			$body .= '<td style="padding: 12px 15px; color: #111827;"><ul style="margin: 0; padding-left: 20px;">';
			foreach ( $members as $member ) {
				$body .= '<li>' . esc_html( $member->full_name ) . '</li>';
			}
			$body .= '</ul></td></tr>';
		}

		$body .= '</table>';

		if ( ! empty( $event->description ) ) {
			$body .= '<h3 style="color: #111827; font-size: 18px; margin-top: 30px; margin-bottom: 15px;">' . __( 'Event Description:', 'martial-arts-club-manager' ) . '</h3>';
			$body .= '<div style="color: #6B7280; font-size: 15px; line-height: 1.6;">' . wp_kses_post( $event->description ) . '</div>';
		}

		$body .= '<p style="color: #6B7280; font-size: 15px; line-height: 1.6; margin-top: 30px;">' . __( 'If you have any questions, please contact us.', 'martial-arts-club-manager' ) . '</p>';

		// Format email with template.
		$email_content = $this->format_email_template( $body, $gradient_style, $site_name, $site_logo_html );

		// Send email.
		$headers = array( 'Content-Type: text/html; charset=UTF-8' );
		$sent    = wp_mail( $to, $subject, $email_content, $headers );
	}

	/**
	 * Format email with template
	 *
	 * @since 1.0.73
	 * @param string $body          Email body.
	 * @param string $gradient_style Gradient style.
	 * @param string $site_name     Site name.
	 * @param string $site_logo_html Site logo HTML.
	 * @return string Formatted email HTML.
	 */
	private function format_email_template( $body, $gradient_style, $site_name, $site_logo_html ) {
		$html = '<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #F4F4F2;">
	<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background-color: #F4F4F2; padding: 20px 0;">
		<tr>
			<td align="center">
				<table role="presentation" cellpadding="0" cellspacing="0" width="600" style="background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
					<tr>
						<td style="' . $gradient_style . '; padding: 40px 30px; text-align: center; border-radius: 8px 8px 0 0;">
							' . $site_logo_html . '
							<h1 style="color: #ffffff; margin: 20px 0 0 0; font-size: 24px; font-weight: 600;">' . esc_html( $site_name ) . '</h1>
						</td>
					</tr>
					<tr>
						<td style="padding: 40px 30px;">
							<div style="font-size: 16px; color: #111827; line-height: 1.6;">
								' . $body . '
							</div>
						</td>
					</tr>
					<tr>
						<td style="background-color: #F4F4F2; padding: 20px 30px; text-align: center; border-radius: 0 0 8px 8px; border-top: 1px solid #D1D5DB;">
							<p style="margin: 0; font-size: 13px; color: #6B7280;">
								' . esc_html__( 'This is an automated notification from your website.', 'martial-arts-club-manager' ) . '
							</p>
						</td>
					</tr>
				</table>
			</td>
		</tr>
	</table>
</body>
</html>';

		return $html;
	}

	/**
	 * Get site logo HTML
	 *
	 * @since 1.0.73
	 * @return string Logo HTML.
	 */
	private function get_site_logo_html() {
		$custom_logo_id = get_theme_mod( 'custom_logo' );

		if ( $custom_logo_id ) {
			$logo_url = wp_get_attachment_image_url( $custom_logo_id, 'medium' );
			if ( $logo_url ) {
				return '<img src="' . esc_url( $logo_url ) . '" alt="' . esc_attr( get_bloginfo( 'name' ) ) . '" style="max-width: 200px; height: auto; display: block; margin: 0 auto;" />';
			}
		}

		return '';
	}
}
