<?php
/**
 * Admin UI scaffold for Mail Doctor.
 *
 * @package MailDoctor
 */

namespace MailDoctor;

require_once MAIL_DOCTOR_PATH . 'includes/admin/modules/module-status.php';
require_once MAIL_DOCTOR_PATH . 'includes/admin/modules/module-logs.php';
require_once MAIL_DOCTOR_PATH . 'includes/admin/modules/module-settings.php';
require_once MAIL_DOCTOR_PATH . 'includes/admin/modules/module-ajax.php';
require_once MAIL_DOCTOR_PATH . 'includes/admin/modules/module-shared.php';

use MailDoctor\Admin\Modules\Shared_Trait;
use MailDoctor\Admin\Modules\Ajax_Trait;
use MailDoctor\Admin\Modules\Logs_Trait;
use MailDoctor\Admin\Modules\Settings_Trait;
use MailDoctor\Admin\Modules\Status_Trait;
use MailDoctor\Helpers\Dependencies;
use MailDoctor\Woo;

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

if ( ! class_exists( 'MailDoctor\\Admin' ) ) {
	/**
	 * Admin controller.
	 */
	class Admin {

		use Shared_Trait;
		use Status_Trait;
		use Logs_Trait;
		use Settings_Trait;
		use Ajax_Trait;

		/**
		 * Page slug used for routing.
		 */
		const PAGE_SLUG = 'maildoctor';

		/**
		 * Capability required for access.
		 */
		const CAPABILITY = 'manage_woocommerce';

		/**
		 * Option key used to persist Mail Doctor settings.
		 */
		const OPTION_KEY = 'mail_doctor_settings';

		/**
		 * Determine capability required for current user.
		 *
		 * @return string
		 */
		public static function required_capability(): string {
			if ( current_user_can( self::CAPABILITY ) ) {
				return self::CAPABILITY;
			}

			return 'manage_options';
		}

		/**
		 * Check if current user can access Mail Doctor.
		 *
		 * @return bool
		 */
		protected static function user_has_access(): bool {
			return current_user_can( self::CAPABILITY ) || current_user_can( 'manage_options' );
		}

		/**
		 * Cached header rendered state.
		 *
		 * @var bool
		 */
		protected static $header_rendered = false;

		/**
		 * Cached screen hook id.
		 *
		 * @var string|null
		 */
		protected static $screen_hook = null;

		/**
		 * Register hooks.
		 *
		 * @return void
		 */
		public static function init(): void {
			add_action( 'admin_menu', array( __CLASS__, 'register_menu' ) );
			add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
			add_filter( 'woocommerce_get_sections_email', array( __CLASS__, 'register_email_section' ) );
			add_filter( 'woocommerce_get_settings_email', array( __CLASS__, 'render_email_settings' ), 10, 2 );
			add_action( 'admin_init', array( __CLASS__, 'handle_settings_form' ) );
			add_action( 'admin_notices', array( __CLASS__, 'render_settings_notices' ) );

			add_action( 'wp_ajax_mail_doctor_send_test_email', array( __CLASS__, 'ajax_send_test_email' ) );
			add_action( 'wp_ajax_mail_doctor_get_status_cards', array( __CLASS__, 'ajax_get_status_cards' ) );
			add_action( 'wp_ajax_mail_doctor_retry_email', array( __CLASS__, 'ajax_retry_email' ) );
			add_action( 'wp_ajax_mail_doctor_resend_email', array( __CLASS__, 'ajax_resend_email' ) );
			add_action( 'wp_ajax_mail_doctor_purge_logs', array( __CLASS__, 'ajax_purge_logs' ) );
			add_action( 'wp_ajax_mail_doctor_run_queue_now', array( __CLASS__, 'ajax_run_queue_now' ) );
			add_action( 'wp_ajax_mail_doctor_test_connection', array( __CLASS__, 'ajax_test_connection' ) );
			add_action( 'wp_ajax_mail_doctor_preview_woo_email', array( __CLASS__, 'ajax_preview_woo_email' ) );
			add_action( 'wp_ajax_mail_doctor_send_preview_woo_email', array( __CLASS__, 'ajax_send_preview_woo_email' ) );
		}

		/**
		 * Register submenu under WooCommerce → Emails.
		 *
		 * @return void
		 */
	public static function register_menu(): void {
		self::$screen_hook = add_submenu_page(
			'woocommerce',
			esc_html__( 'Mail Doctor', 'mail-doctor' ),
			esc_html__( 'Mail Doctor', 'mail-doctor' ),
			self::required_capability(),
			self::PAGE_SLUG,
			array( __CLASS__, 'render_page' )
		);

		// Optionally inject an upgrade link if Pro is not active.
		if ( ! \MailDoctor\Features::is_pro() ) {
			global $submenu;
			// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Need to override WP global to inject external link.
			$submenu['woocommerce'][] = array(
				sprintf(
					'<span style="color: #d63638; font-weight: 600;">%s <span class="dashicons dashicons-external" style="font-size: 14px; margin-top: 3px;"></span></span>',
					esc_html__( 'Upgrade to Pro', 'mail-doctor' )
				),
				self::required_capability(),
				'https://wpdoctorpro.com/products/mail-doctor',
			);
		}
	}

		/**
		 * Enqueue admin assets when on Mail Doctor screen.
		 *
		 * @param string $hook Current screen hook.
		 * @return void
		 */
		public static function enqueue_assets( string $hook ): void {
			if ( ! self::is_mail_doctor_screen( $hook ) ) {
				return;
			}

			wp_enqueue_style( 'woocommerce_admin_styles' );
			wp_enqueue_style( 'wc-enhanced-select' );
			wp_enqueue_style(
				'mail-doctor-admin',
				MAIL_DOCTOR_URL . 'assets/css/admin.css',
				array(),
				MAIL_DOCTOR_VERSION
			);

			wp_enqueue_script( 'woocommerce_admin' );
			wp_add_inline_script( 'woocommerce_admin', 'window.woocommerce_admin = window.woocommerce_admin || {};', 'before' );
			wp_enqueue_script( 'jquery-ui-datepicker' );
			wp_enqueue_script( 'wc-enhanced-select' );
			wp_enqueue_script(
				'mail-doctor-admin',
				MAIL_DOCTOR_URL . 'assets/js/admin.js',
				array( 'jquery', 'wc-enhanced-select', 'jquery-ui-datepicker' ),
				MAIL_DOCTOR_VERSION,
				true
			);
			wp_enqueue_script(
				'mail-doctor-admin-charts',
				MAIL_DOCTOR_URL . 'assets/js/admin/charts.js',
				array( 'mail-doctor-admin' ),
				MAIL_DOCTOR_VERSION,
				true
			);
			wp_enqueue_script(
				'mail-doctor-admin-forms',
				MAIL_DOCTOR_URL . 'assets/js/admin/forms.js',
				array( 'mail-doctor-admin' ),
				MAIL_DOCTOR_VERSION,
				true
			);
			wp_enqueue_script(
				'mail-doctor-admin-status',
				MAIL_DOCTOR_URL . 'assets/js/admin/status.js',
				array( 'mail-doctor-admin', 'mail-doctor-admin-charts' ),
				MAIL_DOCTOR_VERSION,
				true
			);
			wp_enqueue_script(
				'mail-doctor-admin-integrations',
				MAIL_DOCTOR_URL . 'assets/js/admin/integrations.js',
				array( 'mail-doctor-admin' ),
				MAIL_DOCTOR_VERSION,
				true
			);
			wp_enqueue_script(
				'mail-doctor-admin-tests',
				MAIL_DOCTOR_URL . 'assets/js/admin/tests.js',
				array( 'mail-doctor-admin', 'mail-doctor-admin-forms' ),
				MAIL_DOCTOR_VERSION,
				true
			);
			wp_enqueue_script(
				'mail-doctor-admin-logs',
				MAIL_DOCTOR_URL . 'assets/js/admin/logs.js',
				array( 'mail-doctor-admin' ),
				MAIL_DOCTOR_VERSION,
				true
			);
			wp_enqueue_script(
				'mail-doctor-admin-preview',
				MAIL_DOCTOR_URL . 'assets/js/admin/preview.js',
				array( 'mail-doctor-admin', 'mail-doctor-admin-forms' ),
				MAIL_DOCTOR_VERSION,
				true
			);
			wp_enqueue_script(
				'mail-doctor-admin-guides',
				MAIL_DOCTOR_URL . 'assets/js/admin/guides.js',
				array( 'mail-doctor-admin' ),
				MAIL_DOCTOR_VERSION,
				true
			);

			$woo_available      = Dependencies::is_woocommerce_available();
			$woo_preview_emails = $woo_available ? Woo::get_previewable_emails() : array();

			wp_localize_script(
				'mail-doctor-admin',
				'MailDoctorAdmin',
				array(
					'ajaxUrl'      => admin_url( 'admin-ajax.php' ),
					'adminPostUrl' => admin_url( 'admin-post.php' ),
					'nonces'       => array(
						'test'        => wp_create_nonce( 'mail_doctor_test_email_nonce' ),
						'status'      => wp_create_nonce( 'mail_doctor_status_cards_nonce' ),
						'retry'       => wp_create_nonce( 'mail_doctor_retry_nonce' ),
						'resend'      => wp_create_nonce( 'mail_doctor_resend_nonce' ),
						'purge'       => wp_create_nonce( 'mail_doctor_purge_logs_nonce' ),
						'run_queue'   => wp_create_nonce( 'mail_doctor_run_queue_nonce' ),
						'connection'  => wp_create_nonce( 'mail_doctor_connection_nonce' ),
						'preview'     => wp_create_nonce( 'mail_doctor_preview_email_nonce' ),
						'previewSend' => wp_create_nonce( 'mail_doctor_preview_send_nonce' ),
						'export'      => wp_create_nonce( 'mail_doctor_export_logs_nonce' ),
					),
					'screen'       => self::$screen_hook,
					'i18n'         => array(
						'sending'                 => esc_html__( 'Sending test email…', 'mail-doctor' ),
						'sendSuccess'             => esc_html__( 'Test email sent successfully.', 'mail-doctor' ),
						'sendError'               => esc_html__( 'Unable to send the test email. Check the email log for details.', 'mail-doctor' ),
						'loading'                 => esc_html__( 'Loading…', 'mail-doctor' ),
						'retrying'                => esc_html__( 'Queuing retry…', 'mail-doctor' ),
						'retrySuccess'            => esc_html__( 'Retry request queued.', 'mail-doctor' ),
						'retryError'              => esc_html__( 'Retry request failed.', 'mail-doctor' ),
						'resendPrompt'            => esc_html__( 'Send to which email address?', 'mail-doctor' ),
						'resendSuccess'           => esc_html__( 'Resend queued.', 'mail-doctor' ),
						'resendError'             => esc_html__( 'Unable to queue the resend request.', 'mail-doctor' ),
						'runQueue'                => esc_html__( 'Triggering queue…', 'mail-doctor' ),
						'runQueueSuccess'         => esc_html__( 'Queue run triggered.', 'mail-doctor' ),
						'runQueueError'           => esc_html__( 'Queue run failed.', 'mail-doctor' ),
						'purgeSuccess'            => esc_html__( 'Email logs cleared.', 'mail-doctor' ),
						'purgeError'              => esc_html__( 'Unable to clear email logs.', 'mail-doctor' ),
						'copied'                  => esc_html__( 'Copied!', 'mail-doctor' ),
						'copyError'               => esc_html__( 'Copy failed', 'mail-doctor' ),
						'previewLoading'          => esc_html__( 'Rendering preview…', 'mail-doctor' ),
						'previewError'            => esc_html__( 'Unable to render the preview. Check the email log for details.', 'mail-doctor' ),
						'previewReady'            => esc_html__( 'Preview generated below.', 'mail-doctor' ),
						'previewSent'             => esc_html__( 'Preview email sent to your inbox.', 'mail-doctor' ),
						'previewSelect'           => esc_html__( 'Select a WooCommerce email before requesting a preview.', 'mail-doctor' ),
						'previewSendError'        => esc_html__( 'Unable to send the preview email.', 'mail-doctor' ),
						/* translators: %TOTAL%: Count, %FAILED%: Count, %QUARANTINED%: Count */
						'queueNarrative'          => esc_html__( 'Total: %TOTAL%. Failed: %FAILED%. Quarantined: %QUARANTINED%.', 'mail-doctor' ),
						/* translators: %TOTAL%: Total emails, %SENT%: Sent count, %FAILED%: Failed count */
						'deliveryNarrative'       => esc_html__( 'Total emails: %TOTAL%. Sent: %SENT%. Failed: %FAILED%.', 'mail-doctor' ),
						'apiKeyCreating'          => esc_html__( 'Generating API key…', 'mail-doctor' ),
						'apiKeyCreated'           => esc_html__( 'API key generated. Copy the secret now — it will not be shown again.', 'mail-doctor' ),
						'apiKeyRevokeConfirm'     => esc_html__( 'Revoke this API key? Automation using this key will receive 403 errors immediately.', 'mail-doctor' ),
						'apiKeyRevoked'           => esc_html__( 'API key revoked.', 'mail-doctor' ),
						'apiKeyErrorGeneric'      => esc_html__( 'The request failed. Refresh the page and try again.', 'mail-doctor' ),
						'apiKeyNoScopes'          => esc_html__( 'No scopes', 'mail-doctor' ),
						/* translators: %s: Last known IP address */
						'apiKeyLastIp'            => esc_html__( 'Last IP: %s', 'mail-doctor' ),
						'apiKeyRevoke'            => esc_html__( 'Revoke', 'mail-doctor' ),
						/* translators: %s: Key description or user */
						'apiKeySecretFor'         => esc_html__( 'Secret generated for %s', 'mail-doctor' ),
						'apiKeyNeverUsed'         => esc_html__( 'Never used', 'mail-doctor' ),
						'apiKeyStatusActive'      => esc_html__( 'Active', 'mail-doctor' ),
						'trendVsPrevious'         => esc_html__( 'vs previous hour', 'mail-doctor' ),
						'trendNoData'             => esc_html__( 'Not enough data yet.', 'mail-doctor' ),
						'failuresNone'            => esc_html__( 'No recent failures detected in the last 24 hours.', 'mail-doctor' ),
						/* translators: %s: Number of events */
						'failuresCount'           => esc_html__( '%s events', 'mail-doctor' ),
						'failureSeverityWarning'  => esc_html__( 'Warn', 'mail-doctor' ),
						'failureSeverityError'    => esc_html__( 'Error', 'mail-doctor' ),
						'failureSeverityCritical' => esc_html__( 'Critical', 'mail-doctor' ),
						'failureSeverityInfo'     => esc_html__( 'Info', 'mail-doctor' ),
						'failuresUnknownProvider' => esc_html__( 'Unknown provider', 'mail-doctor' ),
						'providersNone'           => esc_html__( 'No provider activity recorded yet.', 'mail-doctor' ),
						'queueNoNextRetry'        => esc_html__( 'Not scheduled', 'mail-doctor' ),
					),
					'woo'          => array(
						'available' => $woo_available,
						'emails'    => $woo_preview_emails,
					),
				)
			);
		}

		/**
		 * Determine whether the current screen is the Mail Doctor page.
		 *
		 * @param string|null $hook Screen hook.
		 * @return bool
		 */
		protected static function is_mail_doctor_screen( ?string $hook = null ): bool {
			if ( ! empty( $_GET['page'] ) && self::PAGE_SLUG === sanitize_key( wp_unslash( $_GET['page'] ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- view context.
				return true;
			}

			if ( null === $hook ) {
				return false;
			}

			return self::$screen_hook === $hook;
		}

		/**
		 * Render Mail Doctor page.
		 *
		 * @return void
		 */
		public static function render_page(): void {
			self::assert_capability();

			$tab = self::get_current_tab();

			self::render_page_header( $tab );

			switch ( $tab ) {
				case 'logs':
					self::render_logs_tab();
					break;
				case 'settings':
					self::render_settings_tab();
					break;
				case 'guides':
					self::render_guides_tab();
					break;
				case 'status':
					self::render_status_tab();
					break;
				default:
					if ( isset( self::get_tabs()[ $tab ] ) ) {
						do_action( 'mail_doctor_render_tab_' . $tab );
					} else {
						self::render_status_tab();
					}
					break;
			}
		}

		/**
		 * Render status dashboard.
		 *
		 * @return void
		 */
		/**
		 * Render logs table.
		 *
		 * @return void
		 */




































		/**
		 * Register Mail Doctor entry in WooCommerce email settings.
		 *
		 * @param array<string,string> $sections Sections.
		 * @return array<string,string>
		 */
		public static function register_email_section( array $sections ): array {
			$sections['maildoctor'] = esc_html__( 'Mail Doctor (SMTP & Retry)', 'mail-doctor' );
			return $sections;
		}

		/**
		 * Render settings for custom section (link only).
		 *
		 * @param array<int,array<string,mixed>> $settings Existing settings.
		 * @param string                         $current_section Current section slug.
		 * @return array<int,array<string,mixed>>
		 */
		public static function render_email_settings( array $settings, string $current_section ): array {
			if ( 'maildoctor' !== $current_section ) {
				return $settings;
			}

			return array(
				array(
					'title' => esc_html__( 'Mail Doctor (SMTP & Retry)', 'mail-doctor' ),
					'type'  => 'title',
					'id'    => 'mail_doctor_settings_title',
					'desc'  => sprintf(
						/* translators: 1: URL, 2: Anchor text */
						'<a class=\"button button-primary\" href=\"%1$s\">%2$s</a>',
						esc_url( self::page_url( 'status' ) ),
						esc_html__( 'Open Mail Doctor', 'mail-doctor' )
					),
				),
				array(
					'type' => 'sectionend',
					'id'   => 'mail_doctor_settings_title',
				),
			);
		}

		/**
		 * Retrieve current tab from query.
		 *
		 * @return string
		 */
		protected static function get_current_tab(): string {
			$tab  = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'status'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- view context.
			$tabs = array_keys( self::get_tabs() );

			if ( ! in_array( $tab, $tabs, true ) ) {
				$tab = 'status';
			}

			return $tab;
		}

		/**
		 * Retrieve current settings sub-section.
		 *
		 * @return string
		 */
		protected static function get_current_section(): string {
			$section  = isset( $_GET['section'] ) ? sanitize_key( wp_unslash( $_GET['section'] ) ) : 'smtp'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- view context.
			$sections = array_keys( self::get_settings_sections() );

			if ( ! in_array( $section, $sections, true ) ) {
				$section = 'smtp';
			}

			return $section;
		}

		/**
		 * Primary nav tabs.
		 *
		 * @return array<string,string>
		 */
		public static function get_tabs(): array {
			$tabs = array(
				'status'    => esc_html__( 'Status', 'mail-doctor' ),
				'settings'  => esc_html__( 'Settings', 'mail-doctor' ),
				'logs'      => esc_html__( 'Logs', 'mail-doctor' ),
				'guides'    => esc_html__( 'Guides', 'mail-doctor' ),
			);

			return apply_filters( 'mail_doctor_admin_tabs', $tabs );
		}

		/**
		 * Output shared header (title + tabs) for Mail Doctor admin screens.
		 *
		 * @param string $active_tab Current tab slug.
		 * @return void
		 */
		public static function render_page_header( string $active_tab ): void {
			if ( self::$header_rendered ) {
				return;
			}

			self::$header_rendered = true;

			$tabs       = self::get_tabs();
			$title      = esc_html__( 'Mail Doctor', 'mail-doctor' );
			$nav_label  = esc_html__( 'Mail Doctor sections', 'mail-doctor' );

			?>
			<div class="wrap maildoctor-admin-wrap">
				<div class="maildoctor-header">
					<div class="maildoctor-branding">
						<h1 class="maildoctor-branding__title">
							<?php echo esc_html( $title ); ?>
						</h1>
					</div>

					<?php if ( ! empty( $tabs ) ) : ?>
						<nav class="nav-tab-wrapper woo-nav-tab-wrapper maildoctor-header__tabs"
							aria-label="<?php echo esc_attr( $nav_label ); ?>">
							<?php foreach ( $tabs as $tab_slug => $tab_label ) : ?>
								<?php
								$is_active    = ( $active_tab === $tab_slug );
								$aria_current = $is_active ? 'page' : 'false';
								?>
								<a href="<?php echo esc_url( self::page_url( $tab_slug ) ); ?>"
									class="nav-tab <?php echo esc_attr( $is_active ? 'nav-tab-active' : '' ); ?>"
									aria-current="<?php echo esc_attr( $aria_current ); ?>">
									<?php echo esc_html( $tab_label ); ?>
								</a>
							<?php endforeach; ?>

							<?php if ( ! \MailDoctor\Features::is_pro() ) : ?>
								<a href="https://wpdoctorpro.com/products/mail-doctor" target="_blank" rel="noopener noreferrer"
									class="nav-tab maildoctor-nav-upgrade"
									style="margin-left: auto; background-color: #d63638; color: #fff; font-weight: 600; border-color: #d63638;">
									<span class="dashicons dashicons-star-filled" style="font-size: 16px; margin-top: 2px;"></span>
									<?php esc_html_e( 'Upgrade to Pro', 'mail-doctor' ); ?>
								</a>
							<?php endif; ?>
						</nav>
					<?php endif; ?>
				</div>
			</div>
			<?php
		}

		/**
		 * Secondary settings sections.
		 *
		 * @return array<string,string>
		 */
		public static function get_settings_sections(): array {
			return array(
				'smtp'         => esc_html__( 'SMTP & Identity', 'mail-doctor' ),
				'profiles'     => esc_html__( 'Profiles', 'mail-doctor' ),
				'retry'        => esc_html__( 'Retry & Queue', 'mail-doctor' ),
				'logging'      => esc_html__( 'Logging & Privacy', 'mail-doctor' ),
				'woocommerce'  => esc_html__( 'WooCommerce', 'mail-doctor' ),
				'advanced'     => esc_html__( 'Advanced', 'mail-doctor' ),
			);
		}

		/**
		 * Build base URL with optional tab.
		 *
		 * @param string|null $tab Tab slug.
		 * @return string
		 */
		public static function page_url( ?string $tab = null ): string {
			$args = array( 'page' => self::PAGE_SLUG );

			if ( $tab ) {
				$args['tab'] = $tab;
			}

			return add_query_arg( $args, admin_url( 'admin.php' ) );
		}
	}
}
