<?php
/**
 * Form handlers for the email admin UI.
 *
 * @package MailDoctor
 */

namespace MailDoctor;

use MailDoctor\Admin;
use MailDoctor\Email\Template;
use MailDoctor\Email\TemplateRepository;

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

/**
 * Processes admin form submissions and redirects.
 */
trait WPMD_Email_Admin_Actions {


	/**
	 * Process save template request.
	 *
	 * @return void
	 */
	public static function handle_save_template(): void {
		if ( ! current_user_can( self::capability() ) ) {
			wp_die( esc_html__( 'You do not have permission to save templates.', 'mail-doctor' ) );
		}

		check_admin_referer( 'mail_doctor_save_template', 'mail_doctor_nonce' );

		$email_type = isset( $_POST['email_type'] ) ? sanitize_key( wp_unslash( $_POST['email_type'] ) ) : '';
		$context    = isset( $_POST['mail_doctor_context'] ) ? sanitize_key( wp_unslash( $_POST['mail_doctor_context'] ) ) : '';
		if ( '' === $email_type ) {
			self::redirect_with_notice( 'error', $email_type, $context );
		}

		// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized via WPMD_Email_Templates methods.
		$subject     = isset( $_POST['subject'] ) ? WPMD_Email_Templates::sanitize_line_field( sanitize_text_field( wp_unslash( $_POST['subject'] ) ) ) : '';
		$heading     = isset( $_POST['heading'] ) ? WPMD_Email_Templates::sanitize_line_field( sanitize_text_field( wp_unslash( $_POST['heading'] ) ) ) : '';
		$body_html   = isset( $_POST['body_html'] ) ? WPMD_Email_Templates::sanitize_html_field( wp_unslash( $_POST['body_html'] ) ) : '';
		$css         = isset( $_POST['css'] ) ? WPMD_Email_Templates::sanitize_css_field( wp_strip_all_tags( wp_unslash( $_POST['css'] ) ) ) : '';
		// phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		$editor_mode = isset( $_POST['editor_mode'] ) ? sanitize_key( wp_unslash( $_POST['editor_mode'] ) ) : 'code';

		if ( ! in_array( $editor_mode, array( 'visual', 'code' ), true ) ) {
			$editor_mode = 'code';
		}

		$is_active = ! empty( $_POST['is_active'] );

		$template_id = isset( $_POST['template_id'] ) ? absint( wp_unslash( $_POST['template_id'] ) ) : 0;
		update_user_meta( get_current_user_id(), '_mail_doctor_last_editor_mode', $editor_mode );

		if ( $template_id > 0 ) {
			wp_update_post(
				array(
					'ID'         => $template_id,
					'post_title' => WPMD_Email_Templates::get_supported_email_types()[ $email_type ] ?? $email_type,
				)
			);
		} else {
			$template_id = wp_insert_post(
				array(
					'post_type'   => WPMD_Email_Templates::CPT,
					'post_status' => 'publish',
					'post_title'  => WPMD_Email_Templates::get_supported_email_types()[ $email_type ] ?? $email_type,
				)
			);
		}

		if ( is_wp_error( $template_id ) || ! $template_id ) {
			self::redirect_with_notice( 'error', $email_type, $context );
		}

		update_post_meta( $template_id, WPMD_Email_Templates::META_EMAIL_TYPE, $email_type );
		update_post_meta( $template_id, WPMD_Email_Templates::META_SUBJECT, $subject );
		update_post_meta( $template_id, WPMD_Email_Templates::META_HEADING, $heading );
		update_post_meta( $template_id, WPMD_Email_Templates::META_BODY, $body_html );
		update_post_meta( $template_id, WPMD_Email_Templates::META_CSS, $css );
		update_post_meta( $template_id, WPMD_Email_Templates::META_ACTIVE, $is_active ? 1 : 0 );
		update_post_meta( $template_id, '_mail_doctor_editor_mode', $editor_mode );

		$repository = new TemplateRepository();
		$repository->record_history(
			new Template(
				$email_type,
				array(
					'id'          => (string) $template_id,
					'post_id'     => $template_id,
					'email_type'  => $email_type,
					'subject'     => $subject,
					'heading'     => $heading,
					'html'        => $body_html,
					'css'         => $css,
					'source'      => 'custom',
					'is_active'   => $is_active,
					'editor_mode' => $editor_mode,
				)
			),
			array(
				'post_id'     => $template_id,
				'editor_mode' => $editor_mode,
				'locale'      => get_locale(),
			)
		);

		WPMD_Email_Templates::clear_template_cache( $email_type );

		if ( isset( $_POST['reset_template'] ) ) {
			WPMD_Email_Templates::reset_to_defaults( $email_type );
			self::redirect_with_notice( 'reset', $email_type, $context );
		}

		self::redirect_with_notice( 'saved', $email_type, $context );
	}

	/**
	 * Handle enable/disable toggle.
	 *
	 * @return void
	 */
	public static function handle_toggle_templates(): void {
		if ( ! current_user_can( self::capability() ) ) {
			wp_die( esc_html__( 'You do not have permission to update template settings.', 'mail-doctor' ) );
		}

		check_admin_referer( 'mail_doctor_toggle_templates', 'mail_doctor_toggle_nonce' );

		$enabled = ! empty( $_POST['enabled'] );
		$context = isset( $_POST['mail_doctor_context'] ) ? sanitize_key( wp_unslash( $_POST['mail_doctor_context'] ) ) : '';
		update_option( WPMD_Email_Templates::OPTION_ENABLE, $enabled );
		WPMD_Email_Templates::flush_template_cache();

		self::redirect_with_notice( 'toggle', isset( $_POST['email_type'] ) ? sanitize_key( wp_unslash( $_POST['email_type'] ) ) : '', $context );
	}

	/**
	 * Restore a template from history.
	 *
	 * @return void
	 */
	public static function handle_restore_template(): void {
		if ( ! current_user_can( self::capability() ) ) {
			wp_die( esc_html__( 'You do not have permission to restore templates.', 'mail-doctor' ) );
		}

		$version_id = isset( $_POST['version_id'] ) ? sanitize_text_field( wp_unslash( $_POST['version_id'] ) ) : '';
		$nonce      = isset( $_POST['mail_doctor_restore_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['mail_doctor_restore_nonce'] ) ) : '';

		if ( '' === $version_id || ! $nonce || ! wp_verify_nonce( $nonce, 'mail_doctor_restore_' . $version_id ) ) {
			wp_die( esc_html__( 'Invalid restore request.', 'mail-doctor' ) );
		}

		$email_type = isset( $_POST['email_type'] ) ? sanitize_key( wp_unslash( $_POST['email_type'] ) ) : '';
		$context    = isset( $_POST['mail_doctor_context'] ) ? sanitize_key( wp_unslash( $_POST['mail_doctor_context'] ) ) : '';

		$repository = new TemplateRepository();
		$restored   = $repository->restore_version( $version_id );

		if ( $restored instanceof Template ) {
			self::redirect_with_notice(
				'restored',
				$email_type,
				$context,
				array(
					'mail_doctor_version' => $version_id,
				)
			);
		}

		self::redirect_with_notice( 'restore_error', $email_type, $context );
	}

	/**
	 * Redirect back to editor with notice.
	 *
	 * @param string $notice     Notice slug.
	 * @param string $email_type Email type.
	 * @param string $context    Context identifier.
	 * @return void
	 */
	protected static function redirect_with_notice( string $notice, string $email_type, string $context = '', array $extra = array() ): void {
		if ( 'maildoctor' === $context ) {
			$redirect = add_query_arg(
				array(
					'page'        => Admin::PAGE_SLUG,
					'tab'         => 'templates',
					'email_type'  => $email_type,
					'mail_doctor_notice' => $notice,
				) + $extra,
				admin_url( 'admin.php' )
			);
		} else {
			$redirect = add_query_arg(
				array(
					'mail_doctor_notice' => $notice,
				),
				self::edit_link( $email_type )
			);

			if ( ! empty( $extra ) ) {
				$redirect = add_query_arg( $extra, $redirect );
			}
		}

		wp_safe_redirect( $redirect );
		exit;
	}
}
