<?php
/**
 * Send Test Mail Action
 *
 * Handles the admin-post action that sends a test email via MailerService,
 * letting admins verify that the mail stack and template are working.
 *
 * @package AmbassadorHub\Admin\Setup
 */

namespace AmbassadorHub\Admin\Setup;

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

use AmbassadorHub\Mail\MailerService;

use function add_action;
use function add_query_arg;
use function admin_url;
use function check_admin_referer;
use function current_user_can;
use function get_bloginfo;
use function is_email;
use function sanitize_email;
use function wp_die;
use function wp_safe_redirect;

/**
 * Registers and handles the "Send test email" admin-post action.
 */
final class SendTestMailAction {

	/**
	 * Register the admin-post hook.
	 *
	 * @return void
	 */
	public static function init(): void {
		add_action( 'admin_post_ambh_send_test_mail', array( self::class, 'handle' ) );
	}

	/**
	 * Handle the form submission.
	 *
	 * @return void
	 */
	public static function handle(): void {
		check_admin_referer( 'ambh_send_test_mail', 'ambh_send_test_mail_nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'ambassadorhub' ) );
		}

		$to = isset( $_POST['ambh_test_mail_to'] ) ? sanitize_email( wp_unslash( $_POST['ambh_test_mail_to'] ) ) : '';

		$redirect = add_query_arg(
			array(
				'page' => 'ambassadorhub-settings',
				'tab'  => 'tools',
			),
			admin_url( 'admin.php' )
		);

		if ( ! is_email( $to ) ) {
			wp_safe_redirect( add_query_arg( 'ambh_test_mail', 'invalid', $redirect ) );
			exit;
		}

		$site_name = get_bloginfo( 'name' );
		$subject   = sprintf(
			/* translators: %s: site name */
			__( '[%s] Test email', 'ambassadorhub' ),
			$site_name
		);

		$body = '<p>' . sprintf(
			/* translators: %s: site name */
			__( 'This is a test email sent from <strong>%s</strong> to confirm that the AmbassadorHub mail service is configured correctly.', 'ambassadorhub' ),
			esc_html( $site_name )
		) . '</p>'
		. '<p>' . __( 'If you received this email, your mail setup is working.', 'ambassadorhub' ) . '</p>';

		$sent = MailerService::send(
			$to,
			$subject,
			$body,
			__( 'Test email from AmbassadorHub — your mail setup is working.', 'ambassadorhub' )
		);

		$result = $sent ? 'sent' : 'failed';
		wp_safe_redirect( add_query_arg( 'ambh_test_mail', $result, $redirect ) );
		exit;
	}
}
