<?php
/**
 * Customize WP Emails Module
 *
 * Customize default WordPress system emails. Port from Fluent Security.
 *
 * @package CustomWpEmails
 * @since 1.0.0
 */

namespace CustomWpEmails;

use WP_PowerSuite\Core\Contracts\DataLocationsInterface;
use WP_PowerSuite\Core\AbstractModule;
use WP_PowerSuite\Core\NetworkScope;
use CustomWpEmails\Includes\SystemEmailService;
use CustomWpEmails\Includes\WPSystemEmailHandler;

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

require_once __DIR__ . '/includes/SystemEmailService.php';
require_once __DIR__ . '/includes/SmartCodeParser.php';
require_once __DIR__ . '/includes/WPSystemEmailHandler.php';

class Module extends AbstractModule implements DataLocationsInterface {

	private const MODULE_ID = 'custom-wp-emails';

	private const TEST_EMAIL_RATE_LIMIT = 5;

	public function getId(): string {
		return self::MODULE_ID;
	}

	public function getName(): string {
		return __( 'Customize WP Emails', 'wp-powersuite' );
	}

	public function getVersion(): string {
		return '1.0.0';
	}

	public function getDescription(): string {
		return __( 'Branded templates and sender settings for core WordPress emails; enable or disable each type.', 'wp-powersuite' );
	}

	public function getContext(): string|array {
		return [ 'admin', 'frontend', 'ajax' ];
	}

	public function getDependencies(): array {
		return [];
	}

	private function isLicenseActive(): bool {
		return function_exists( 'wp_powersuite_is_license_valid' ) && wp_powersuite_is_license_valid();
	}

	public function getDataLocations(): array {
		return [
			'options' => [ SystemEmailService::get_option_key() ],
		];
	}


	protected function registerHooks(): void {
		if ( ! $this->isLicenseActive() ) {
			return;
		}

		( new WPSystemEmailHandler() )->register();

		if ( is_admin() ) {
		add_action( 'admin_menu', [ $this, 'addAdminMenu' ], 20 );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueueScripts' ] );
		add_action( 'admin_post_wpps_custom_wp_emails_save_template', [ $this, 'handleSaveTemplate' ] );
		add_action( 'admin_post_wpps_custom_wp_emails_save_email', [ $this, 'handleSaveEmail' ] );
		add_action( 'wp_ajax_wpps_custom_wp_emails_preview', [ $this, 'ajaxPreview' ] );
		add_action( 'wp_ajax_wpps_custom_wp_emails_template_preview', [ $this, 'ajaxTemplatePreview' ] );
		add_action( 'wp_ajax_wpps_custom_wp_emails_test_email', [ $this, 'ajaxTestEmail' ] );
		}
	}

	/**
	 * Add SmartCode button next to Add media in the editor toolbar.
	 *
	 * @param string $editor_id The editor ID (e.g. body_user_registration_to_user).
	 */
	public function addSmartCodeMediaButton( string $editor_id ): void {
		if ( strpos( $editor_id, 'body_' ) !== 0 ) {
			return;
		}
		$email_id = substr( $editor_id, 5 );
		?>
		<button type="button" class="button wpps-smartcode-trigger wpps-smartcode-media-btn" data-target="body" data-email-id="<?php echo esc_attr( $email_id ); ?>" title="<?php esc_attr_e( 'Insert SmartCode', 'wp-powersuite' ); ?>">
			+ <?php esc_html_e( 'SmartCode', 'wp-powersuite' ); ?>
		</button>
		<?php
	}

	public function addAdminMenu(): void {
		add_submenu_page(
			'powersuite',
			__( 'Customize WP Emails', 'wp-powersuite' ),
			__( 'Customize WP Emails', 'wp-powersuite' ),
			$this->adminCapability(),
			'powersuite-custom-wp-emails',
			[ $this, 'renderSettingsPage' ]
		);
	}

	public function enqueueScripts( string $hook ): void {
		if ( $hook !== 'wp-powersuite_page_powersuite-custom-wp-emails' ) {
			return;
		}
		$base = defined( 'WP_POWERSUITE_PLUGIN_URL' ) ? WP_POWERSUITE_PLUGIN_URL : '';
		wp_enqueue_style( 'dashicons' );
		wp_enqueue_style( 'wp-powersuite-admin' );
		wp_enqueue_style( 'wpps-cwe-admin', $base . 'modules/custom-wp-emails/assets/cwe-admin.css', [ 'wp-powersuite-admin' ], '1.1.2' );
		wp_enqueue_editor();
		wp_enqueue_media();
		add_filter( 'user_can_richedit', '__return_true' );
		wp_tinymce_inline_scripts();
		add_action( 'media_buttons', [ $this, 'addSmartCodeMediaButton' ], 11 );
	}

	public function renderTemplateDesignPage(): void {
		if ( ! $this->canManagePlugin() ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'wp-powersuite' ) );
		}
		$settings = SystemEmailService::get_global_settings();
		$template = $settings['template_settings'] ?? [];
		$default_colors = [
			'body_bg'              => '#f3f4f6',
			'content_bg'           => '#ffffff',
			'content_color'        => '#374151',
			'footer_content_color' => '#6b7280',
			'highlight_bg'         => 'rgb(249, 250, 251)',
			'highlight_color'      => '#374151',
		];
		$preview_html = $this->get_template_preview_html( $template );
		include __DIR__ . '/views/template-design-page.php';
	}

	public function renderSettingsPage(): void {
		if ( ! $this->canManagePlugin() ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'wp-powersuite' ) );
		}
		if ( ! $this->isLicenseActive() ) {
			?>
			<div class="wrap">
				<h1><?php esc_html_e( 'Customize WordPress Emails', 'wp-powersuite' ); ?></h1>
				<div class="notice notice-warning inline" style="margin:0;">
					<p>
						<?php esc_html_e( 'Customize WordPress Emails requires an active license. Activate your license to design system email templates.', 'wp-powersuite' ); ?>
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=powersuite-license' ) ); ?>"><?php esc_html_e( 'Activate license', 'wp-powersuite' ); ?></a>
					</p>
				</div>
			</div>
			<?php
			return;
		}
		$tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : '';
		if ( $tab === 'template' ) {
			$this->renderTemplateDesignPage();
			return;
		}
		$emails = SystemEmailService::get_email_indexes();
		$settings = SystemEmailService::get_global_settings();
		$defaults = SystemEmailService::get_email_defaults();
		$edit_email_id   = isset( $_GET['edit'] ) ? sanitize_key( wp_unslash( $_GET['edit'] ) ) : null;
		$edit_email_meta = null;
		$edit_smartcodes = [];
		if ( $edit_email_id && isset( $emails[ $edit_email_id ] ) ) {
			$edit_email_meta = $emails[ $edit_email_id ];
			$edit_smartcodes = array_merge(
				$edit_email_meta['additional_smartcodes'] ?? [],
				[
					'{{user.display_name}}' => __( 'Display Name', 'wp-powersuite' ),
					'{{user.user_login}}'  => __( 'Username', 'wp-powersuite' ),
					'{{user.user_email}}'  => __( 'Email', 'wp-powersuite' ),
					'{{user.roles}}'       => __( 'User Roles', 'wp-powersuite' ),
					'{{site.name}}'        => __( 'Site Title', 'wp-powersuite' ),
					'{{site.url}}'         => __( 'Site URL', 'wp-powersuite' ),
					'##site.login_url##'   => __( 'Login URL', 'wp-powersuite' ),
					'{{site.admin_email}}' => __( 'Admin Email', 'wp-powersuite' ),
				]
			);
			if ( in_array( $edit_email_id, [ 'comment_notification_to_author', 'comment_moderation_to_admin' ], true ) ) {
				$edit_smartcodes['##comment.message##'] = __( 'WordPress Comment Message', 'wp-powersuite' );
			}
		} else {
			$edit_email_id = null;
		}
		include __DIR__ . '/views/settings-page.php';
	}

	private function get_template_preview_html( array $template ): string {
		if ( ! defined( 'WPPS_PREVIEWING_EMAIL' ) ) {
			define( 'WPPS_PREVIEWING_EMAIL', true );
		}
		$defaults = [
			'body_bg'              => '#f3f4f6',
			'content_bg'           => '#ffffff',
			'content_color'        => '#374151',
			'footer_content_color' => '#6b7280',
			'highlight_bg'         => 'rgb(249, 250, 251)',
			'highlight_color'      => '#374151',
			'font_family'          => '',
			'logo'                 => '',
		];
		$template = wp_parse_args( $template, $defaults );
		$user = wp_get_current_user();
		$default_body = SystemEmailService::get_default_email_body( 'user_registration_to_user' );
		$footer = $template['footer_text'] ?? '';
		if ( empty( $footer ) ) {
			$footer = __( 'Email Footer Placeholder', 'wp-powersuite' );
		}
		$parser = new \CustomWpEmails\Includes\SmartCodeParser();
		$body = $parser->parse( $default_body, $user );
		return SystemEmailService::with_html_template( $body, $footer, $user, $template );
	}

	public function ajaxTemplatePreview(): void {
		if ( ! $this->canManagePlugin() || ! check_ajax_referer( 'wpps_custom_wp_emails', 'nonce', false ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid request.', 'wp-powersuite' ) ] );
		}
		if ( ! defined( 'WPPS_PREVIEWING_EMAIL' ) ) {
			define( 'WPPS_PREVIEWING_EMAIL', true );
		}
		$color_defaults = [
			'body_bg'              => '#f3f4f6',
			'content_bg'           => '#ffffff',
			'content_color'        => '#374151',
			'footer_content_color' => '#6b7280',
			'highlight_bg'         => 'rgb(249, 250, 251)',
			'highlight_color'      => '#374151',
		];
		$template = [
			'body_bg'              => SystemEmailService::sanitize_color_value( isset( $_POST['body_bg'] ) ? sanitize_text_field( wp_unslash( $_POST['body_bg'] ) ) : '', $color_defaults['body_bg'] ),
			'content_bg'           => SystemEmailService::sanitize_color_value( isset( $_POST['content_bg'] ) ? sanitize_text_field( wp_unslash( $_POST['content_bg'] ) ) : '', $color_defaults['content_bg'] ),
			'content_color'        => SystemEmailService::sanitize_color_value( isset( $_POST['content_color'] ) ? sanitize_text_field( wp_unslash( $_POST['content_color'] ) ) : '', $color_defaults['content_color'] ),
			'footer_content_color' => SystemEmailService::sanitize_color_value( isset( $_POST['footer_content_color'] ) ? sanitize_text_field( wp_unslash( $_POST['footer_content_color'] ) ) : '', $color_defaults['footer_content_color'] ),
			'highlight_bg'         => SystemEmailService::sanitize_color_value( isset( $_POST['highlight_bg'] ) ? sanitize_text_field( wp_unslash( $_POST['highlight_bg'] ) ) : '', $color_defaults['highlight_bg'] ),
			'highlight_color'      => SystemEmailService::sanitize_color_value( isset( $_POST['highlight_color'] ) ? sanitize_text_field( wp_unslash( $_POST['highlight_color'] ) ) : '', $color_defaults['highlight_color'] ),
			'font_family'          => SystemEmailService::sanitize_font_family( isset( $_POST['font_family'] ) ? sanitize_text_field( wp_unslash( $_POST['font_family'] ) ) : '' ),
			'logo'                 => isset( $_POST['logo'] ) ? esc_url_raw( wp_unslash( $_POST['logo'] ) ) : '',
			'footer_text'          => isset( $_POST['footer_text'] ) ? wp_kses_post( wp_unslash( $_POST['footer_text'] ) ) : '',
		];
		$settings = SystemEmailService::get_global_settings();
		$settings['template_settings'] = array_merge( $settings['template_settings'] ?? [], $template );
		$preview = $this->get_template_preview_html( $settings['template_settings'] );
		wp_send_json_success( [ 'body' => $preview ] );
	}

	public function handleSaveTemplate(): void {
		if ( ! $this->canManagePlugin() || ! check_admin_referer( 'wpps_custom_wp_emails_template' ) ) {
			wp_die( esc_html__( 'Invalid request.', 'wp-powersuite' ) );
		}
		$settings = SystemEmailService::get_global_settings();
		$template = $settings['template_settings'] ?? [];
		$color_defaults = [
			'body_bg'              => '#f3f4f6',
			'content_bg'           => '#ffffff',
			'content_color'        => '#374151',
			'footer_content_color' => '#6b7280',
			'highlight_bg'         => 'rgb(249, 250, 251)',
			'highlight_color'      => '#374151',
		];
		$allowed = [ 'body_bg', 'content_bg', 'content_color', 'footer_content_color', 'highlight_bg', 'highlight_color', 'font_family', 'logo', 'footer_text', 'from_name', 'from_email', 'reply_to_name', 'reply_to_email' ];
		foreach ( $allowed as $key ) {
			if ( ! isset( $_POST[ $key ] ) ) {
				continue;
			}
			if ( $key === 'footer_text' ) {
				$val = wp_kses_post( wp_unslash( $_POST[ $key ] ) );
			} elseif ( $key === 'logo' ) {
				$val = esc_url_raw( wp_unslash( $_POST[ $key ] ) );
			} elseif ( $key === 'font_family' ) {
				$val = SystemEmailService::sanitize_font_family( sanitize_text_field( wp_unslash( $_POST[ $key ] ) ) );
			} elseif ( isset( $color_defaults[ $key ] ) ) {
				$val = SystemEmailService::sanitize_color_value( sanitize_text_field( wp_unslash( $_POST[ $key ] ) ), $color_defaults[ $key ] );
			} elseif ( in_array( $key, [ 'from_name', 'reply_to_name' ], true ) ) {
				$val = SystemEmailService::sanitize_header_name( sanitize_text_field( wp_unslash( $_POST[ $key ] ) ) );
			} elseif ( in_array( $key, [ 'from_email', 'reply_to_email' ], true ) ) {
				$val = sanitize_email( wp_unslash( $_POST[ $key ] ) );
				if ( $val && ! is_email( $val ) ) {
					continue;
				}
			} else {
				$val = sanitize_text_field( wp_unslash( $_POST[ $key ] ) );
			}
			$template[ $key ] = $val;
		}
		$settings['template_settings'] = $template;
		update_option( SystemEmailService::get_option_key(), $settings, false );
		SystemEmailService::bust_settings_cache();
		$return_to_template = ( isset( $_POST['return_to'] ) && sanitize_key( wp_unslash( $_POST['return_to'] ) ) === 'template' );
		$redirect_args = [ 'page' => 'powersuite-custom-wp-emails', 'saved' => 'template' ];
		if ( $return_to_template ) {
			$redirect_args['tab'] = 'template';
		}
		wp_safe_redirect( add_query_arg( $redirect_args, NetworkScope::adminUrl( 'admin.php' ) ) );
		exit;
	}

	public function handleSaveEmail(): void {
		if ( ! $this->canManagePlugin() || ! check_admin_referer( 'wpps_custom_wp_emails_email' ) ) {
			wp_die( esc_html__( 'Invalid request.', 'wp-powersuite' ) );
		}
		$email_id = isset( $_POST['email_id'] ) ? sanitize_key( wp_unslash( $_POST['email_id'] ) ) : '';
		$emails = SystemEmailService::get_email_indexes();
		if ( ! isset( $emails[ $email_id ] ) ) {
			wp_safe_redirect( add_query_arg( [ 'page' => 'powersuite-custom-wp-emails', 'error' => '1' ], NetworkScope::adminUrl( 'admin.php' ) ) );
			exit;
		}
		$status  = SystemEmailService::sanitize_email_status( $email_id, isset( $_POST['status'] ) ? sanitize_key( wp_unslash( $_POST['status'] ) ) : 'system' );
		$subject = isset( $_POST['subject'] ) ? sanitize_text_field( wp_unslash( $_POST['subject'] ) ) : '';
		$body    = isset( $_POST['body'] ) ? wp_kses_post( wp_unslash( $_POST['body'] ) ) : '';

		if ( $status === 'active' ) {
			$validation_error = SystemEmailService::validate_required_smartcodes( $email_id, $subject, $body );
			if ( $validation_error ) {
				$redirect = add_query_arg(
					[
						'page'  => 'powersuite-custom-wp-emails',
						'edit'  => $email_id,
						'error' => 'required_smartcode',
					],
					NetworkScope::adminUrl( 'admin.php' )
				);
				wp_safe_redirect( $redirect );
				exit;
			}
		}

		$settings = SystemEmailService::get_global_settings();
		if ( $status === 'system' ) {
			unset( $settings['emails'][ $email_id ] );
		} else {
			$settings['emails'][ $email_id ] = [
				'status' => $status,
				'email'  => [ 'subject' => $subject, 'body' => $body ],
			];
		}
		update_option( SystemEmailService::get_option_key(), $settings, false );
		SystemEmailService::bust_settings_cache();
		$redirect = add_query_arg( [ 'page' => 'powersuite-custom-wp-emails', 'saved' => 'email' ], NetworkScope::adminUrl( 'admin.php' ) );
		if ( isset( $_POST['return_to_edit'] ) && sanitize_key( wp_unslash( $_POST['return_to_edit'] ) ) === $email_id ) {
			$redirect = add_query_arg( 'edit', $email_id, $redirect );
		}
		wp_safe_redirect( $redirect );
		exit;
	}

	public function ajaxPreview(): void {
		if ( ! $this->canManagePlugin() || ! check_ajax_referer( 'wpps_custom_wp_emails', 'nonce', false ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid request.', 'wp-powersuite' ) ] );
		}
		$email_id = isset( $_POST['email_id'] ) ? sanitize_key( wp_unslash( $_POST['email_id'] ) ) : '';
		$subject = isset( $_POST['subject'] ) ? sanitize_text_field( wp_unslash( $_POST['subject'] ) ) : '';
		$body = isset( $_POST['body'] ) ? wp_kses_post( wp_unslash( $_POST['body'] ) ) : '';
		$emails = SystemEmailService::get_email_indexes();
		if ( ! isset( $emails[ $email_id ] ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid email.', 'wp-powersuite' ) ] );
		}
		if ( ! defined( 'WPPS_PREVIEWING_EMAIL' ) ) {
			define( 'WPPS_PREVIEWING_EMAIL', true );
		}
		$user = $this->get_preview_user( $email_id );
		$parser = new \CustomWpEmails\Includes\SmartCodeParser();
		$defaults = SystemEmailService::get_email_defaults()[ $email_id ]['email'] ?? [];
		$body = $body ?: $this->get_sample_body_for_preview( $email_id );
		$body = $parser->parse( $body, $user );
		$subject = $parser->parse(
			$subject ?: SystemEmailService::resolve_email_field( $defaults, 'subject', '' ),
			$user
		);
		$body = SystemEmailService::with_html_template( $body, null, $user );
		wp_send_json_success( [ 'subject' => $subject, 'body' => $body ] );
	}

	/**
	 * User context for preview/test rendering (sample registrant for admin notifications).
	 */
	private function get_preview_user( string $email_id ): \WP_User {
		if ( $email_id === 'user_registration_to_admin' ) {
			$sample = new \WP_User();
			$sample->init(
				(object) [
					'ID'              => 0,
					'user_login'      => 'sample_user',
					'user_nicename'   => 'sample-user',
					'user_email'      => 'sample@example.com',
					'display_name'    => 'Sample User',
					'user_registered' => gmdate( 'Y-m-d H:i:s' ),
				]
			);
			$sample->roles = [ 'subscriber' ];
			return $sample;
		}

		return wp_get_current_user();
	}

	private function get_sample_body_for_preview( string $email_id ): string {
		$defaults = SystemEmailService::get_email_defaults();
		$body = $defaults[ $email_id ]['email']['body'] ?? '';
		if ( $body !== '' ) {
			return $body;
		}
		if ( $email_id === 'comment_notification_to_author' ) {
			return '<p>' . __( 'New comment on your post "Sample Post Title"', 'wp-powersuite' ) . '</p><p>' . __( 'Author: John Doe', 'wp-powersuite' ) . '</p><p>' . __( 'Comment: This is a sample comment for preview.', 'wp-powersuite' ) . '</p>';
		}
		if ( $email_id === 'comment_moderation_to_admin' ) {
			return '<p>' . __( 'A new comment is waiting for your approval', 'wp-powersuite' ) . '</p><p>' . __( 'Author: Jane Smith', 'wp-powersuite' ) . '</p><p>' . __( 'Comment: Sample comment awaiting moderation.', 'wp-powersuite' ) . '</p>';
		}
		if ( $email_id === 'admin_email_change_confirmation' ) {
			$body = SystemEmailService::get_default_email_body( 'admin_email_change_confirmation' );
			$user = wp_get_current_user();
			$body = str_replace( '###USERNAME###', $user->user_login ?? 'admin', $body );
			$body = str_replace( '###ADMIN_URL###', admin_url( 'options.php' ), $body );
			$body = str_replace( '###EMAIL###', get_option( 'admin_email' ), $body );
			$body = str_replace( '###SITENAME###', get_option( 'blogname' ), $body );
			$body = str_replace( '###SITEURL###', home_url(), $body );
			return $body;
		}
		return '<p>' . __( 'Sample content for preview.', 'wp-powersuite' ) . '</p>';
	}

	public function ajaxTestEmail(): void {
		if ( ! $this->canManagePlugin() || ! check_ajax_referer( 'wpps_custom_wp_emails', 'nonce', false ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid request.', 'wp-powersuite' ) ] );
		}

		$rate_key = 'wpps_cwe_test_email_' . get_current_user_id();
		$sends    = (int) get_transient( $rate_key );
		if ( $sends >= self::TEST_EMAIL_RATE_LIMIT ) {
			wp_send_json_error( [ 'message' => __( 'Too many test emails. Please wait a minute and try again.', 'wp-powersuite' ) ] );
		}

		$email_id = isset( $_POST['email_id'] ) ? sanitize_key( wp_unslash( $_POST['email_id'] ) ) : '';
		$to_email = isset( $_POST['to_email'] ) ? sanitize_email( wp_unslash( $_POST['to_email'] ) ) : '';
		$subject  = isset( $_POST['subject'] ) ? sanitize_text_field( wp_unslash( $_POST['subject'] ) ) : '';
		$body     = isset( $_POST['body'] ) ? wp_kses_post( wp_unslash( $_POST['body'] ) ) : '';

		$emails = SystemEmailService::get_email_indexes();
		if ( ! isset( $emails[ $email_id ] ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid email.', 'wp-powersuite' ) ] );
		}
		if ( ! is_email( $to_email ) ) {
			wp_send_json_error( [ 'message' => __( 'Please enter a valid email address.', 'wp-powersuite' ) ] );
		}

		if ( ! defined( 'WPPS_TESTING_EMAIL' ) ) {
			define( 'WPPS_TESTING_EMAIL', true );
		}

		$user   = wp_get_current_user();
		$parser = new \CustomWpEmails\Includes\SmartCodeParser();
		$defaults = SystemEmailService::get_email_defaults()[ $email_id ]['email'] ?? [];
		$body    = $body ?: $this->get_sample_body_for_preview( $email_id );
		$subject = $parser->parse(
			$subject ?: SystemEmailService::resolve_email_field( $defaults, 'subject', '' ),
			$user
		);
		$body = $parser->parse( $body, $user );
		$body = SystemEmailService::with_html_template( $body, null, $user );

		$headers = SystemEmailService::build_mail_headers( [] );
		$sent    = wp_mail( $to_email, $subject, $body, $headers );
		if ( $sent ) {
			set_transient( $rate_key, $sends + 1, MINUTE_IN_SECONDS );
			wp_send_json_success( [ 'message' => __( 'Test email sent successfully. Security links in test emails use placeholder URLs only.', 'wp-powersuite' ) ] );
		}
		wp_send_json_error( [ 'message' => __( 'Failed to send test email. Check your SMTP or mail configuration.', 'wp-powersuite' ) ] );
	}
}
