<?php
/**
 * License Reminders Admin Settings
 *
 * Handles the admin interface for license expiration reminder settings
 *
 * @package KarateClubManager
 * @since 1.0.18
 */

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

/**
 * License Reminders Admin Class
 */
class MACM_Admin_License_Reminders {

	/**
	 * Initialize the class
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'add_submenu_page' ), 19 );
		add_action( 'admin_init', array( $this, 'register_settings' ) );
		add_action( 'admin_post_macm_test_reminder', array( $this, 'handle_test_reminder' ) );
		add_action( 'admin_post_macm_run_license_check', array( $this, 'handle_run_license_check' ) );
		add_action( 'admin_post_macm_reset_email_template', array( $this, 'handle_reset_template' ) );
		add_action( 'admin_notices', array( $this, 'display_admin_notices' ) );
	}

	/**
	 * Add submenu page under KCM menu
	 *
	 * @since 1.0.18
	 */
	public function add_submenu_page() {
		add_submenu_page(
			'martial-arts-club-manager',
			__( 'License Reminders', 'martial-arts-club-manager' ),
			__( 'License Reminders', 'martial-arts-club-manager' ),
			'manage_options',
			'kcm-license-reminders',
			array( $this, 'render_settings_page' )
		);
	}

	/**
	 * Register settings
	 *
	 * @since 1.0.18
	 */
	public function register_settings() {
		register_setting(
			'macm_license_reminders',
			'macm_license_reminder_subject',
			array(
				'sanitize_callback' => array( $this, 'sanitize_subject' ),
			)
		);
		register_setting(
			'macm_license_reminders',
			'macm_license_reminder_body',
			array(
				'sanitize_callback' => array( $this, 'sanitize_body' ),
			)
		);
	}

	/**
	 * Sanitize subject field
	 *
	 * @since 1.0.23
	 * @param string $value The subject value.
	 * @return string Sanitized subject.
	 */
	public function sanitize_subject( $value ) {
		// Start output buffering to prevent warnings from breaking redirect.
		if ( ! ob_get_level() ) {
			ob_start();
		}

		$sanitized = sanitize_text_field( $value );

		// Clean output buffer.
		if ( ob_get_level() ) {
			ob_end_clean();
		}

		return $sanitized;
	}

	/**
	 * Sanitize body field
	 *
	 * @since 1.0.23
	 * @param string $value The body value.
	 * @return string Sanitized body.
	 */
	public function sanitize_body( $value ) {
		// Start output buffering to prevent warnings from breaking redirect.
		if ( ! ob_get_level() ) {
			ob_start();
		}

		$sanitized = wp_kses_post( $value );

		// Clean output buffer.
		if ( ob_get_level() ) {
			ob_end_clean();
		}

		return $sanitized;
	}

	/**
	 * Render settings page
	 *
	 * @since 1.0.18
	 */
	public function render_settings_page() {
		// Check permissions.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'martial-arts-club-manager' ) );
		}

		// Get current settings.
		$subject = get_option( 'macm_license_reminder_subject', '' );
		$body    = get_option( 'macm_license_reminder_body', '' );

		// Check if using default template (both subject and body are empty).
		$using_default_template = empty( $subject ) && empty( $body );

		// Get available placeholders.
		$placeholders = MACM_License_Reminders::get_available_placeholders();

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

			<div class="notice notice-info">
				<p>
					<strong><?php esc_html_e( 'How it works:', 'martial-arts-club-manager' ); ?></strong><br>
					<?php esc_html_e( 'The system automatically checks weekly for members whose licenses will expire within the next 30 days or have already expired within the last 60 days. A reminder email is sent once per week to the user who owns that member until the license is renewed.', 'martial-arts-club-manager' ); ?>
				</p>
			</div>

			<form method="post" action="options.php">
				<?php settings_fields( 'macm_license_reminders' ); ?>

				<h2><?php esc_html_e( 'Email Template', 'martial-arts-club-manager' ); ?></h2>

				<table class="form-table">
					<tr>
						<th scope="row">
							<label for="macm_license_reminder_subject">
								<?php esc_html_e( 'Email Subject', 'martial-arts-club-manager' ); ?>
							</label>
						</th>
						<td>
							<input
								type="text"
								id="macm_license_reminder_subject"
								name="macm_license_reminder_subject"
								value="<?php echo esc_attr( $subject ); ?>"
								class="large-text"
								placeholder="<?php esc_attr_e( 'License Expiration Reminder - {member_name}', 'martial-arts-club-manager' ); ?>"
							/>
							<p class="description">
								<?php esc_html_e( 'Leave blank to use default.', 'martial-arts-club-manager' ); ?>
							</p>
						</td>
					</tr>

					<tr>
						<th scope="row">
							<label for="macm_license_reminder_body">
								<?php esc_html_e( 'Email Body', 'martial-arts-club-manager' ); ?>
							</label>
						</th>
						<td>
							<?php
							wp_editor(
								$body,
								'macm_license_reminder_body',
								array(
									'textarea_name' => 'macm_license_reminder_body',
									'textarea_rows' => 15,
									'media_buttons' => false,
									'teeny'         => false,
									'tinymce'       => array(
										'toolbar1' => 'bold,italic,underline,separator,alignleft,aligncenter,alignright,separator,link,unlink,separator,undo,redo',
									),
								)
							);
							?>
							<p class="description">
								<?php esc_html_e( 'HTML is supported. Leave blank to use default template.', 'martial-arts-club-manager' ); ?>
							</p>
						</td>
					</tr>
				</table>

				<h3><?php esc_html_e( 'Available Placeholders', 'martial-arts-club-manager' ); ?></h3>
				<p><?php esc_html_e( 'You can use the following placeholders in your email template. They will be replaced with actual values when the email is sent.', 'martial-arts-club-manager' ); ?></p>

				<table class="widefat striped">
					<thead>
						<tr>
							<th><?php esc_html_e( 'Placeholder', 'martial-arts-club-manager' ); ?></th>
							<th><?php esc_html_e( 'Description', 'martial-arts-club-manager' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $placeholders as $placeholder => $description ) : ?>
							<tr>
								<td><code><?php echo esc_html( $placeholder ); ?></code></td>
								<td><?php echo esc_html( $description ); ?></td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>

				<p class="submit">
					<?php submit_button( __( 'Save Settings', 'martial-arts-club-manager' ), 'primary', 'submit', false ); ?>
				</p>
			</form>

			<?php if ( ! $using_default_template ) : ?>
				<!-- Reset to Default Template -->
				<div style="margin-top: 20px; padding: 15px; background: #fff3cd; border-left: 4px solid #ffc107; border-radius: 4px;">
					<h3 style="margin-top: 0;"><?php esc_html_e( 'Use New Professional Template (v1.0.41)', 'martial-arts-club-manager' ); ?></h3>
					<p><?php esc_html_e( 'Version 1.0.41 includes a beautiful new HTML email template with your site logo, professional styling, and better formatting.', 'martial-arts-club-manager' ); ?></p>
					<p><?php esc_html_e( 'If you previously customized the template, you can reset it to use the new default design.', 'martial-arts-club-manager' ); ?></p>
					<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin-top: 15px;">
						<input type="hidden" name="action" value="macm_reset_email_template">
						<?php wp_nonce_field( 'macm_reset_template', 'macm_reset_template_nonce' ); ?>
						<?php submit_button( __( 'Reset to New Default Template', 'martial-arts-club-manager' ), 'secondary', 'submit', false ); ?>
					</form>
				</div>
			<?php else : ?>
				<!-- Using Default Template - Show Preview -->
				<div style="margin-top: 20px; padding: 15px; background: #d1ecf1; border-left: 4px solid #0c5460; border-radius: 4px;">
					<h3 style="margin-top: 0; color: #0c5460;">
						<span class="dashicons dashicons-yes-alt" style="color: #0c5460;"></span>
						<?php esc_html_e( 'Using Professional HTML Template', 'martial-arts-club-manager' ); ?>
					</h3>
					<p style="margin: 0;"><?php esc_html_e( 'Your license reminder emails are using the new professional HTML template with logo support. See preview below.', 'martial-arts-club-manager' ); ?></p>
				</div>
			<?php endif; ?>

			<hr>

			<h2><?php esc_html_e( 'Test Email', 'martial-arts-club-manager' ); ?></h2>
			<p><?php esc_html_e( 'Send a test email to yourself to preview how the reminder will look.', 'martial-arts-club-manager' ); ?></p>

			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
				<input type="hidden" name="action" value="macm_test_reminder">
				<?php wp_nonce_field( 'macm_test_reminder', 'macm_test_reminder_nonce' ); ?>

				<table class="form-table">
					<tr>
						<th scope="row">
							<label for="test_email">
								<?php esc_html_e( 'Send Test To', 'martial-arts-club-manager' ); ?>
							</label>
						</th>
						<td>
							<input
								type="email"
								id="test_email"
								name="test_email"
								value="<?php echo esc_attr( wp_get_current_user()->user_email ); ?>"
								class="regular-text"
								required
							/>
							<p class="description">
								<?php esc_html_e( 'A sample reminder will be sent to this email address using the current template.', 'martial-arts-club-manager' ); ?>
							</p>
						</td>
					</tr>
				</table>

				<?php submit_button( __( 'Send Test Email', 'martial-arts-club-manager' ), 'secondary' ); ?>
			</form>

			<?php if ( $using_default_template ) : ?>
				<hr>

				<h2><?php esc_html_e( 'Email Template Preview', 'martial-arts-club-manager' ); ?></h2>
				<p><?php esc_html_e( 'This is what your license reminder emails will look like:', 'martial-arts-club-manager' ); ?></p>

				<?php
				// Get gradient colors from settings (same as actual emails).
				$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 ) );
				?>

				<div style="background: #F4F4F2; padding: 30px; border-radius: 8px; margin: 20px 0;">
					<div style="max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); overflow: hidden;">

						<!-- Header Preview -->
						<div style="<?php echo esc_attr( $gradient_style ); ?>; padding: 40px 30px; text-align: center;">
							<?php
							$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 ) {
									echo '<img src="' . esc_url( $logo_url ) . '" alt="' . esc_attr( get_bloginfo( 'name' ) ) . '" style="max-width: 200px; height: auto; display: block; margin: 0 auto;" />';
								}
							} else {
								echo '<div style="font-size: 32px; font-weight: 700; color: #ffffff;">' . esc_html( get_bloginfo( 'name' ) ) . '</div>';
							}
							?>
							<h1 style="color: #ffffff; margin: 20px 0 0 0; font-size: 24px; font-weight: 600;"><?php esc_html_e( 'License Expiration Reminder', 'martial-arts-club-manager' ); ?></h1>
						</div>

						<!-- Content Preview -->
						<div style="padding: 40px 30px;">
							<p style="font-size: 16px; color: #111827; margin: 0 0 20px 0;">
								<strong><?php esc_html_e( 'Dear John Smith,', 'martial-arts-club-manager' ); ?></strong>
							</p>
							<p style="font-size: 16px; color: #111827; margin: 0 0 25px 0;">
								<?php esc_html_e( 'This is a friendly reminder that the license for', 'martial-arts-club-manager' ); ?> <strong style="color: <?php echo esc_attr( $gradient_start ); ?>;"><?php esc_html_e( 'John Doe', 'martial-arts-club-manager' ); ?></strong> <?php esc_html_e( 'is due to expire soon.', 'martial-arts-club-manager' ); ?>
							</p>

							<!-- License Details Card -->
							<div style="background-color: #F4F4F2; border-radius: 6px; padding: 25px; margin: 0 0 25px 0;">
								<h2 style="color: <?php echo esc_attr( $gradient_start ); ?>; font-size: 18px; margin: 0 0 15px 0; font-weight: 600;"><?php esc_html_e( 'License Details', 'martial-arts-club-manager' ); ?></h2>
								<table style="width: 100%; border-collapse: collapse;">
									<tr>
										<td style="padding: 8px 0; font-size: 15px; color: #6B7280;">
											<strong style="color: #111827;"><?php esc_html_e( 'Member:', 'martial-arts-club-manager' ); ?></strong>
										</td>
										<td style="padding: 8px 0; font-size: 15px; color: #111827; text-align: right;">
											<?php esc_html_e( 'John Doe', 'martial-arts-club-manager' ); ?>
										</td>
									</tr>
									<tr>
										<td style="padding: 8px 0; font-size: 15px; color: #6B7280; border-top: 1px solid #D1D5DB;">
											<strong style="color: #111827;"><?php esc_html_e( 'License Number:', 'martial-arts-club-manager' ); ?></strong>
										</td>
										<td style="padding: 8px 0; font-size: 15px; color: #111827; text-align: right; border-top: 1px solid #D1D5DB;">
											ABC123456
										</td>
									</tr>
									<tr>
										<td style="padding: 8px 0; font-size: 15px; color: #6B7280; border-top: 1px solid #D1D5DB;">
											<strong style="color: #111827;"><?php esc_html_e( 'Expiration Date:', 'martial-arts-club-manager' ); ?></strong>
										</td>
										<td style="padding: 8px 0; font-size: 15px; color: #d32f2f; text-align: right; font-weight: 600; border-top: 1px solid #D1D5DB;">
											<?php echo esc_html( date_i18n( get_option( 'date_format' ), strtotime( '+14 days' ) ) ); ?>
										</td>
									</tr>
									<tr>
										<td style="padding: 8px 0; font-size: 15px; color: #6B7280; border-top: 1px solid #D1D5DB;">
											<strong style="color: #111827;"><?php esc_html_e( 'Days Until Expiration:', 'martial-arts-club-manager' ); ?></strong>
										</td>
										<td style="padding: 8px 0; font-size: 15px; color: #d32f2f; text-align: right; font-weight: 600; border-top: 1px solid #D1D5DB;">
											14
										</td>
									</tr>
								</table>
							</div>

							<!-- Warning Box -->
							<div style="background-color: #fff3cd; border-left: 4px solid #ffc107; padding: 15px 20px; border-radius: 4px; margin: 0 0 25px 0;">
								<p style="margin: 0; font-size: 15px; color: #856404;">
									<strong><?php esc_html_e( 'Action Required:', 'martial-arts-club-manager' ); ?></strong><br>
									<?php esc_html_e( 'Please renew this license before it expires to ensure uninterrupted access to club activities.', 'martial-arts-club-manager' ); ?>
								</p>
							</div>

							<p style="font-size: 15px; color: #111827; margin: 0;">
								<?php esc_html_e( 'Best regards,', 'martial-arts-club-manager' ); ?><br>
								<strong><?php echo esc_html( get_bloginfo( 'name' ) ); ?></strong>
							</p>
						</div>

						<!-- Footer Preview -->
						<div style="background-color: #F4F4F2; padding: 20px 30px; text-align: center; border-top: 1px solid #D1D5DB;">
							<p style="margin: 0; font-size: 13px; color: #6B7280;">
								<?php esc_html_e( 'This is an automated reminder. Please do not reply to this email.', 'martial-arts-club-manager' ); ?>
							</p>
						</div>
					</div>
				</div>
			<?php endif; ?>

			<hr>

			<h2><?php esc_html_e( 'Cron Status', 'martial-arts-club-manager' ); ?></h2>
			<?php $this->display_cron_status(); ?>

			<hr>

			<h2><?php esc_html_e( 'Manual Check', 'martial-arts-club-manager' ); ?></h2>
			<p><?php esc_html_e( 'Run the license expiration check immediately. This will find all members with licenses expiring within 30 days or expired within the last 60 days, and send reminder emails (skipping members who already received a reminder this week).', 'martial-arts-club-manager' ); ?></p>

			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin-top: 15px;">
				<input type="hidden" name="action" value="macm_run_license_check">
				<?php wp_nonce_field( 'macm_run_license_check', 'macm_run_license_check_nonce' ); ?>
				<?php submit_button( __( 'Run License Check Now', 'martial-arts-club-manager' ), 'secondary', 'submit', false ); ?>
			</form>
		</div>

		<?php
		// Enqueue inline styles using WordPress-compliant method.
		$license_reminders_styles = '
			.kcm-placeholder-list {
				background: #F4F4F2;
				border: 1px solid #D1D5DB;
				padding: 15px;
				margin: 15px 0;
			}
			.kcm-placeholder-list code {
				background: #fff;
				padding: 2px 6px;
				border: 1px solid #D1D5DB;
				border-radius: 3px;
			}
		';
		wp_add_inline_style( 'kcm-admin-styles', $license_reminders_styles );
		?>
		<?php
	}

	/**
	 * Display admin notices
	 *
	 * @since 1.0.38
	 */
	public function display_admin_notices() {
		$page_param = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( empty( $page_param ) || 'kcm-license-reminders' !== sanitize_key( $page_param ) ) {
			return;
		}

		$message_raw = filter_input( INPUT_GET, 'message', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( ! empty( $message_raw ) ) {
			$message = sanitize_text_field( $message_raw );

			switch ( $message ) {
				case 'cron_executed':
					$found_raw   = filter_input( INPUT_GET, 'found', FILTER_SANITIZE_NUMBER_INT );
					$found       = ! empty( $found_raw ) ? absint( $found_raw ) : 0;
					$sent_raw    = filter_input( INPUT_GET, 'sent', FILTER_SANITIZE_NUMBER_INT );
					$sent        = ! empty( $sent_raw ) ? absint( $sent_raw ) : 0;
					$skipped_raw = filter_input( INPUT_GET, 'skipped', FILTER_SANITIZE_NUMBER_INT );
					$skipped     = ! empty( $skipped_raw ) ? absint( $skipped_raw ) : 0;

					echo '<div class="notice notice-success is-dismissible"><p>';
					printf(
						/* translators: %1$d: members found, %2$d: emails sent, %3$d: emails skipped */
						esc_html__( 'License check completed! Found %1$d member(s) with expiring licenses. Sent %2$d email(s). Skipped %3$d (already sent this week).', 'martial-arts-club-manager' ),
						(int) $found,
						(int) $sent,
						(int) $skipped
					);
					echo '</p></div>';
					break;

				case 'no_members_found':
					echo '<div class="notice notice-warning is-dismissible"><p>';
					esc_html_e( 'No members found with licenses expiring within 30 days or expired within the last 60 days.', 'martial-arts-club-manager' );
					echo '</p></div>';
					break;

				case 'template_reset':
					echo '<div class="notice notice-success is-dismissible"><p>';
					esc_html_e( 'Email template has been reset to the new default HTML template. Send a test email to see the new professional design!', 'martial-arts-club-manager' );
					echo '</p></div>';
					break;
			}
		}
	}

	/**
	 * Display cron status information
	 *
	 * @since 1.0.18
	 */
	private function display_cron_status() {
		$next_run = wp_next_scheduled( MACM_License_Reminders::CRON_HOOK );

		if ( $next_run ) {
			$time_until = human_time_diff( time(), $next_run );
			echo '<p>';
			echo '<span class="dashicons dashicons-yes-alt" style="color: green;"></span> ';
			echo wp_kses_post(
				sprintf(
					/* translators: %s: time until next cron run */
					__( 'Cron is scheduled. Next check will run in <strong>%s</strong>.', 'martial-arts-club-manager' ),
					esc_html( $time_until )
				)
			);
			echo '</p>';
			echo '<p>';
			echo wp_kses_post(
				sprintf(
					/* translators: %s: formatted date and time */
					__( 'Next scheduled run: <code>%s</code>', 'martial-arts-club-manager' ),
					esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $next_run ) )
				)
			);
			echo '</p>';
		} else {
			echo '<p>';
			echo '<span class="dashicons dashicons-warning" style="color: orange;"></span> ';
			esc_html_e( 'Cron is not scheduled. It will be scheduled on next page load.', 'martial-arts-club-manager' );
			echo '</p>';
		}
	}

	/**
	 * Handle test reminder submission
	 *
	 * @since 1.0.18
	 */
	public function handle_test_reminder() {
		// Check nonce.
		$nonce = isset( $_POST['macm_test_reminder_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['macm_test_reminder_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'macm_test_reminder' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'martial-arts-club-manager' ) );
		}

		// Check permissions.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'martial-arts-club-manager' ) );
		}

		// Get test email.
		$test_email = isset( $_POST['test_email'] ) ? sanitize_email( wp_unslash( $_POST['test_email'] ) ) : '';

		if ( empty( $test_email ) || ! is_email( $test_email ) ) {
			wp_safe_redirect(
				add_query_arg(
					array(
						'page'    => 'kcm-license-reminders',
						'message' => 'invalid_email',
					),
					admin_url( 'admin.php' )
				)
			);
			exit;
		}

		// Send test email.
		$sent = $this->send_test_email( $test_email );

		// Redirect with message.
		wp_safe_redirect(
			add_query_arg(
				array(
					'page'    => 'kcm-license-reminders',
					'message' => $sent ? 'test_sent' : 'test_failed',
				),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}

	/**
	 * Send test email
	 *
	 * @since 1.0.18
	 * @param string $email Email address.
	 * @return bool True if sent, false otherwise.
	 */
	private function send_test_email( $email ) {
		// Create sample member data.
		$current_user  = wp_get_current_user();
		$sample_member = (object) array(
			'user_id'            => $current_user->ID,
			'user_email'         => $email,
			'display_name'       => $current_user->display_name,
			'full_name'          => 'John Doe (Sample)',
			'license_number'     => 'ABC123456',
			'license_expiration' => wp_date( 'Y-m-d', strtotime( '+14 days' ) ),
		);

		// Get templates.
		$subject_template = get_option( 'macm_license_reminder_subject', '' );
		$body_template    = get_option( 'macm_license_reminder_body', '' );

		// Use defaults if empty.
		if ( empty( $subject_template ) ) {
			$reminders  = new MACM_License_Reminders();
			$reflection = new ReflectionClass( $reminders );
			$method     = $reflection->getMethod( 'get_default_subject' );
			$method->setAccessible( true );
			$subject_template = $method->invoke( $reminders );
		}

		if ( empty( $body_template ) ) {
			$reminders  = new MACM_License_Reminders();
			$reflection = new ReflectionClass( $reminders );
			$method     = $reflection->getMethod( 'get_default_body' );
			$method->setAccessible( true );
			$body_template = $method->invoke( $reminders );
		}

		// Replace placeholders.
		$subject = $this->replace_test_placeholders( $subject_template, $sample_member );
		$body    = $this->replace_test_placeholders( $body_template, $sample_member );

		// Add test notice to body.
		$body = '<div style="background: #fff3cd; border: 1px solid #ffc107; padding: 15px; margin-bottom: 20px;">'
			. '<strong>' . __( 'TEST EMAIL', 'martial-arts-club-manager' ) . '</strong><br>'
			. __( 'This is a test email using sample data. Actual emails will use real member information.', 'martial-arts-club-manager' )
			. '</div>' . $body;

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

	/**
	 * Replace placeholders for test email
	 *
	 * @since 1.0.18
	 * @param string $template Template string.
	 * @param object $member   Sample member data.
	 * @return string Replaced template.
	 */
	private function replace_test_placeholders( $template, $member ) {
		// Get site logo HTML (same as production emails).
		$site_logo_html = $this->get_site_logo_html();

		$placeholders = array(
			'{user_name}'             => 'John Smith',
			'{user_first_name}'       => 'John',
			'{user_last_name}'        => 'Smith',
			'{member_name}'           => $member->full_name,
			'{license_number}'        => $member->license_number,
			'{expiration_date}'       => date_i18n( get_option( 'date_format' ), strtotime( $member->license_expiration ) ),
			'{days_until_expiration}' => '14',
			'{site_name}'             => get_bloginfo( 'name' ),
			'{site_url}'              => home_url(),
			'{site_logo}'             => $site_logo_html,
		);

		return str_replace(
			array_keys( $placeholders ),
			array_values( $placeholders ),
			$template
		);
	}

	/**
	 * Get site logo HTML for email
	 *
	 * @since 1.0.44
	 * @return string HTML for site logo or empty string.
	 */
	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;" />';
			}
		}

		// Fallback: Use site name as text logo.
		return '<div style="font-size: 32px; font-weight: 700; color: #ffffff; text-align: center;">' . esc_html( get_bloginfo( 'name' ) ) . '</div>';
	}

	/**
	 * Handle manual license check request
	 *
	 * @since 1.0.38
	 */
	public function handle_run_license_check() {
		// Check nonce.
		$nonce = isset( $_POST['macm_run_license_check_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['macm_run_license_check_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'macm_run_license_check' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'martial-arts-club-manager' ) );
		}

		// Check permissions.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'martial-arts-club-manager' ) );
		}

		// Get the members that would be checked.
		global $wpdb;
		$start_date = wp_date( 'Y-m-d', strtotime( '-60 days' ) );
		$end_date   = wp_date( 'Y-m-d', strtotime( '+30 days' ) );

		// Query for members with expiring licenses.
		$members = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT m.*, u.user_email, u.display_name
				FROM {$wpdb->prefix}macm_members m
				INNER JOIN {$wpdb->prefix}users u ON m.user_id = u.ID
				WHERE m.license_expiration BETWEEN %s AND %s
				AND m.license_number IS NOT NULL
				AND '' != m.license_number
				AND m.status = 'active'
				ORDER BY m.license_expiration ASC",
				$start_date,
				$end_date
			)
		);

		if ( empty( $members ) ) {
			// No members found.
			wp_safe_redirect(
				add_query_arg(
					array(
						'page'    => 'kcm-license-reminders',
						'message' => 'no_members_found',
					),
					admin_url( 'admin.php' )
				)
			);
			exit;
		}

		// Trigger the cron function which will handle sending and tracking.
		$reminders = new MACM_License_Reminders();

		// Use reflection to call the check method and get results.
		$reflection = new ReflectionClass( $reminders );
		$method     = $reflection->getMethod( 'check_expiring_licenses' );
		$method->setAccessible( true );
		$results = $method->invoke( $reminders );

		// Redirect with actual results.
		wp_safe_redirect(
			add_query_arg(
				array(
					'page'    => 'kcm-license-reminders',
					'message' => 'cron_executed',
					'found'   => $results['found'],
					'sent'    => $results['sent'],
					'skipped' => $results['skipped'],
				),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}

	/**
	 * Handle reset email template request
	 *
	 * @since 1.0.42
	 */
	public function handle_reset_template() {
		// Check nonce.
		$nonce = isset( $_POST['macm_reset_template_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['macm_reset_template_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'macm_reset_template' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'martial-arts-club-manager' ) );
		}

		// Check permissions.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'martial-arts-club-manager' ) );
		}

		// Delete the saved templates to force use of defaults.
		delete_option( 'macm_license_reminder_subject' );
		delete_option( 'macm_license_reminder_body' );

		// Redirect with success message.
		wp_safe_redirect(
			add_query_arg(
				array(
					'page'    => 'kcm-license-reminders',
					'message' => 'template_reset',
				),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}
}

// Initialize - PREMIUM feature.
// This block will be removed from the free version by Freemius.
if ( function_exists( 'macm_fs' ) && macm_fs()->is__premium_only() ) {
	if ( macm_fs()->can_use_premium_code() ) {
		new MACM_Admin_License_Reminders();
	}
}
