<?php
/**
 * Class UltimaKit_Module_Force_Send_All_Email_To
 *
 * @since 1.0.0
 * @package    UltimaKit
 */

/**
 * Class UltimaKit_Module_Force_Send_All_Email_To
 *
 * This module redirects all outgoing emails to a specific email address,
 * which is particularly useful for testing and development environments.
 *
 * @since 1.0.0
 */
class UltimaKit_Module_Force_Send_All_Email_To extends UltimaKit_Module_Manager {
	/**
	 * Unique identifier for the Force Send All Email To module.
	 *
	 * @var string
	 */
	protected $ID = 'ultimakit_force_send_all_email_to';

	/**
	 * The name of the module.
	 *
	 * @var string
	 */
	protected $name;

	/**
	 * A brief description of what the module does.
	 *
	 * @var string
	 */
	protected $description;

	/**
	 * The pricing plan associated with the module.
	 *
	 * @var string
	 */
	protected $plan = 'free';

	/**
	 * The category of functionality the module falls under.
	 *
	 * @var string
	 */
	protected $category = 'Utilities';

	/**
	 * The type of module, indicating its platform or use case.
	 *
	 * @var string
	 */
	protected $type = 'WordPress';

	/**
	 * Flag indicating whether the module is active.
	 *
	 * @var bool
	 */
	protected $is_active;

	/**
	 * URL providing more detailed information about the module.
	 *
	 * @var string
	 */
	protected $read_more_link = 'force-send-all-email-to-in-wordpress';

	/**
	 * The settings associated with the module, if any.
	 *
	 * @var array
	 */
	protected $settings;

	/**
	 * Initializes the module with default values for properties and prepares
	 * any necessary setup or hooks into WordPress. This may include setting
	 * initial values, registering hooks, or preparing resources needed for
	 * the module to function properly within WordPress.
	 */
	public function __construct() {
		$this->name        = __( 'Force Send All Email To', 'ultimakit-for-wp' );
		$this->description = __( 'Redirect all outgoing emails to a specific email address (useful for testing).', 'ultimakit-for-wp' );
		$this->is_active   = $this->isModuleActive( $this->ID );
		$this->settings    = 'yes';
		$this->initializeModule();
	}

	/**
	 * Initializes the specific module within the application.
	 *
	 * This function is responsible for performing the initial setup required to get the module
	 * up and running. This includes registering hooks and filters, enqueing styles and scripts,
	 * and any other preliminary setup tasks that need to be performed before the module can
	 * start functioning as expected.
	 *
	 * It's typically called during the plugin or theme's initialization phase, ensuring that
	 * all module dependencies are loaded and ready for use.
	 *
	 * @return void
	 */
	protected function initializeModule() {
		if ( $this->is_active ) {
			add_action( 'admin_enqueue_scripts', array( $this, 'add_scripts' ) );
			add_action( 'admin_footer', array( $this, 'add_modal' ) );

			// Hook into WordPress email function to redirect emails
			add_filter( 'wp_mail', array( $this, 'redirect_emails' ), 999 );
			
			// Add admin notice for warning
			add_action( 'admin_notices', array( $this, 'display_warning_notice' ) );
		}
	}

	/**
	 * Redirects all outgoing emails to the specified email address.
	 *
	 * @param array $args Email arguments including 'to', 'subject', 'message', 'headers', 'attachments'.
	 * @return array Modified email arguments.
	 */
	public function redirect_emails( $args ) {
		$target_email = $this->getModuleSettings( $this->ID, 'target_email' );
		
		if ( empty( $target_email ) || ! is_email( $target_email ) ) {
			return $args;
		}

		// Store original recipients for logging
		$original_to = $args['to'];
		$original_subject = $args['subject'];

		// Modify the email to redirect to target email
		$args['to'] = $target_email;
		
		// Add original recipient information to subject
		$args['subject'] = '[REDIRECTED] ' . $original_subject;
		
		// Add original recipient information to message
		$redirect_info = "\n\n--- Email Redirection Info ---\n";
		$redirect_info .= "Original Recipient(s): " . ( is_array( $original_to ) ? implode( ', ', $original_to ) : $original_to ) . "\n";
		$redirect_info .= "Original Subject: " . $original_subject . "\n";
		$redirect_info .= "Redirected by: UltimaKit Force Send All Email To Module\n";
		$redirect_info .= "Time: " . current_time( 'Y-m-d H:i:s' ) . "\n";
		$redirect_info .= "--- End Redirection Info ---\n\n";
		
		$args['message'] = $redirect_info . $args['message'];

		// Log the redirection if logging is enabled
		if ( $this->getModuleSettings( $this->ID, 'enable_logging' ) ) {
			$this->log_email_redirection( $original_to, $original_subject, $target_email );
		}

		return $args;
	}

	/**
	 * Logs email redirections for debugging purposes.
	 *
	 * @param string|array $original_to Original recipients.
	 * @param string $original_subject Original subject.
	 * @param string $target_email Target email address.
	 */
	private function log_email_redirection( $original_to, $original_subject, $target_email ) {
		$log_entry = array(
			'timestamp' => current_time( 'Y-m-d H:i:s' ),
			'original_to' => is_array( $original_to ) ? implode( ', ', $original_to ) : $original_to,
			'original_subject' => $original_subject,
			'target_email' => $target_email,
		);

		// Get existing logs
		$logs = get_option( 'ultimakit_email_redirect_logs', array() );
		
		// Add new log entry
		$logs[] = $log_entry;
		
		// Keep only last 100 entries to prevent database bloat
		if ( count( $logs ) > 100 ) {
			$logs = array_slice( $logs, -100 );
		}
		
		update_option( 'ultimakit_email_redirect_logs', $logs );
	}

	/**
	 * Adds a modal dialog to the page.
	 *
	 * This function is responsible for initiating and rendering a modal dialog within the
	 * application or website interface. It typically involves setting up the necessary HTML
	 * and JavaScript for the modal to function and display correctly. The modal can be used
	 * for various purposes, such as displaying information, confirming actions, or collecting
	 * user input.
	 *
	 * @return void
	 */
	public function add_modal() {
		$arguments          = array();
		$arguments['ID']    = $this->ID;
		$arguments['title'] = __( 'Force Send All Email To', 'ultimakit-for-wp' );

		$arguments['fields'] = array(
			'target_email' => array(
				'type'  => 'text',
				'label' => __( 'Target Email Address', 'ultimakit-for-wp' ),
				'value' => $this->getModuleSettings( $this->ID, 'target_email' ),
				'desc'  => __( 'All outgoing emails will be redirected to this email address.', 'ultimakit-for-wp' ),
			),
			'enable_logging' => array(
				'type'    => 'checkbox',
				'label'   => __( 'Enable Logging', 'ultimakit-for-wp' ),
				'value'   => $this->getModuleSettings( $this->ID, 'enable_logging' ),
				'desc'    => __( 'Log email redirections for debugging purposes (stored in database).', 'ultimakit-for-wp' ),
			),
			'show_warning' => array(
				'type'    => 'checkbox',
				'label'   => __( 'Show Warning Notice', 'ultimakit-for-wp' ),
				'value'   => $this->getModuleSettings( $this->ID, 'show_warning' ),
				'desc'    => __( 'Display a warning notice in admin when this module is active.', 'ultimakit-for-wp' ),
			),
		);

		$this->ultimakit_generate_modal( $arguments );
	}

	/**
	 * Enqueues scripts for the theme or plugin.
	 *
	 * This function handles the registration and enqueuing of JavaScript files required
	 * by the theme or plugin. It ensures that scripts are loaded in the correct order and
	 * that dependencies are managed properly. Scripts can include both local and external
	 * resources, and may be conditionally loaded based on the context or user actions.
	 *
	 * Use this function to enqueue all JavaScript necessary for the functionality of your
	 * theme or plugin, adhering to WordPress best practices for script registration and
	 * enqueuing.
	 *
	 * @return void
	 */
	public function add_scripts() {
		wp_enqueue_script(
			'ultimakit-module-script-' . $this->ID,
			plugins_url( '/module-script.js', __FILE__ ),
			array( 'jquery' ),
			ULTIMAKIT_FOR_WP_VERSION,
			true
		);
	}

	/**
	 * Displays admin warning notice when module is active.
	 */
	public function display_warning_notice() {
		if ( ! $this->getModuleSettings( $this->ID, 'show_warning' ) ) {
			return;
		}

		$target_email = $this->getModuleSettings( $this->ID, 'target_email' );
		if ( empty( $target_email ) ) {
			return;
		}

		$message = sprintf(
			__( '⚠️ <strong>Email Redirection Active:</strong> All outgoing emails are being redirected to <strong>%s</strong>. This module is intended for testing purposes only. Please disable it in production environments.', 'ultimakit-for-wp' ),
			esc_html( $target_email )
		);

		echo '<div class="notice notice-warning is-dismissible">';
		echo '<p>' . $message . '</p>';
		echo '</div>';
	}
} 