<?php
/**
 * Email Delivery admin — Settings / Overview / Test Email.
 *
 * @package EmailSmtp
 * @var array<string, mixed> $settings
 * @var string               $tab
 * @var list<array{id:string,name:string,description:string,transport_label:string,recommended_use:string}> $providers
 * @var \EmailSmtp\Includes\ProviderInterface|null $active
 * @var array<string, mixed> $diagnostics
 * @var bool                 $email_logs_enabled
 * @var string               $email_logs_url
 * @var bool                 $email_reports_enabled
 * @var string               $email_reports_url
 * @var list<string>         $conflicting
 * @var list<array{id:string, label:string, count:int, plugin_file:string}> $import_sources
 * @var bool                 $saved
 * @var array{key: string, label: string, tone: string, detail: string} $health
 * @var list<array{id: string, label: string, done: bool, hint: string}> $checklist
 * @var array{show?: bool, domain?: string, from_email?: string, score?: int, total?: int, checked_at?: string, checks?: list<array{id: string, label: string, tone: string, detail: string, tip?: string}>} $domain_health
 * @var array<string, array<string, mixed>> $connections
 * @var string               $edit_connection_id
 * @var string               $pick_provider
 */

use EmailSmtp\Module;
use WP_PowerSuite\Admin\PageHero;
use WP_PowerSuite\Core\NetworkScope;

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

$page_url = NetworkScope::adminUrl( 'admin.php', [ 'page' => Module::PAGE_SLUG ] );

$tabs = [
	'settings' => __( 'Settings', 'wp-powersuite' ),
	'overview' => __( 'Overview', 'wp-powersuite' ),
	'test'     => __( 'Test Email', 'wp-powersuite' ),
];

$hero_meta = sprintf(
	'<span class="wpps-ed-status wpps-ed-status--%1$s">%2$s</span>',
	esc_attr(
		$health['tone'] === 'success' ? 'connected' : ( $health['tone'] === 'danger' ? 'failed' : 'incomplete' )
	),
	esc_html( $health['label'] )
);
?>
<div class="wrap wpps-email-delivery wpps-ed-wrap">
	<hr class="wp-header-end" style="margin:0;padding:0;border:none;height:0;overflow:hidden;" />

	<?php if ( ! empty( $settings['simulation_mode'] ) && (string) $settings['simulation_mode'] !== '0' ) : ?>
		<div class="notice notice-warning"><p>
			<strong><?php esc_html_e( 'Email Simulation is enabled.', 'wp-powersuite' ); ?></strong>
			<?php esc_html_e( 'No email will be sent. Attempts are still recorded in Email Logs when that module is on.', 'wp-powersuite' ); ?>
		</p></div>
	<?php endif; ?>

	<?php if ( $saved ) : ?>
		<div class="notice notice-success is-dismissible"><p>
			<?php
			if ( ! empty( $_GET['imported'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
				echo esc_html( sanitize_text_field( rawurldecode( wp_unslash( (string) $_GET['imported'] ) ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			} else {
				esc_html_e( 'Settings saved.', 'wp-powersuite' );
			}
			?>
		</p></div>
	<?php endif; ?>

	<?php if ( ! empty( $_GET['error'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
		<div class="notice notice-error is-dismissible"><p><?php echo esc_html( sanitize_text_field( wp_unslash( (string) $_GET['error'] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?></p></div>
	<?php endif; ?>

	<?php include __DIR__ . '/partials/import-banner.php'; ?>

	<?php
	$oauth_notice = isset( $_GET['oauth'] ) ? sanitize_key( wp_unslash( (string) $_GET['oauth'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( $oauth_notice === 'connected' ) :
		?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'OAuth account connected successfully.', 'wp-powersuite' ); ?></p></div>
	<?php elseif ( $oauth_notice === 'disconnected' ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'OAuth account disconnected. Client credentials were kept.', 'wp-powersuite' ); ?></p></div>
	<?php endif; ?>

	<?php if ( ! empty( $_GET['oauth_error'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
		<?php
		$oauth_error  = sanitize_key( wp_unslash( (string) $_GET['oauth_error'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$oauth_detail = isset( $_GET['oauth_detail'] ) ? sanitize_text_field( rawurldecode( wp_unslash( (string) $_GET['oauth_detail'] ) ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$oauth_messages = [
			'invalid_provider'    => __( 'Invalid OAuth provider.', 'wp-powersuite' ),
			'oauth_denied'        => __( 'Authorization was denied or cancelled.', 'wp-powersuite' ),
			'missing_code'        => __( 'OAuth callback was missing a code or state.', 'wp-powersuite' ),
			'invalid_state'       => __( 'OAuth state was invalid or expired. Try Connect again.', 'wp-powersuite' ),
			'permission'          => __( 'You must be logged in as an administrator to complete OAuth.', 'wp-powersuite' ),
			'token_exchange'      => __( 'Could not exchange the authorization code for tokens.', 'wp-powersuite' ),
			'missing_credentials' => __( 'Client ID and Client Secret are required before connecting.', 'wp-powersuite' ),
		];
		$oauth_msg = $oauth_messages[ $oauth_error ] ?? __( 'OAuth connection failed.', 'wp-powersuite' );
		if ( $oauth_detail !== '' ) {
			$oauth_msg .= ' ' . $oauth_detail;
		}
		?>
		<div class="notice notice-error is-dismissible"><p><?php echo esc_html( $oauth_msg ); ?></p></div>
	<?php endif; ?>

	<?php
	PageHero::render_for_module(
		[
			'icon'      => 'dashicons-email-alt',
			'title'     => __( 'Email Delivery', 'wp-powersuite' ),
			'tagline'   => __( 'Send WordPress email through SMTP or your mail provider. Routed automatically by From address.', 'wp-powersuite' ),
			'meta_html' => $hero_meta,
		]
	);
	?>

	<nav class="nav-tab-wrapper wp-clearfix wpps-ed-tabs" style="margin-bottom: 20px;" aria-label="<?php esc_attr_e( 'Email Delivery sections', 'wp-powersuite' ); ?>">
		<?php foreach ( $tabs as $tab_key => $tab_label ) : ?>
			<a
				href="<?php echo esc_url( add_query_arg( 'tab', $tab_key, $page_url ) ); ?>"
				class="nav-tab <?php echo $tab === $tab_key ? 'nav-tab-active' : ''; ?>"
				data-wpps-ed-tab="<?php echo esc_attr( $tab_key ); ?>"
			><?php echo esc_html( $tab_label ); ?></a>
		<?php endforeach; ?>
		<?php if ( $email_logs_enabled ) : ?>
			<a
				href="<?php echo esc_url( $email_logs_url ); ?>"
				class="nav-tab"
			><?php esc_html_e( 'Email Logs', 'wp-powersuite' ); ?></a>
		<?php else : ?>
			<span
				class="nav-tab wpps-ed-nav-tab--disabled"
				aria-disabled="true"
				title="<?php esc_attr_e( 'Enable the Email Logs module to view delivery history.', 'wp-powersuite' ); ?>"
			><?php esc_html_e( 'Email Logs', 'wp-powersuite' ); ?></span>
		<?php endif; ?>
		<?php if ( $email_reports_enabled ) : ?>
			<a
				href="<?php echo esc_url( $email_reports_url ); ?>"
				class="nav-tab"
			><?php esc_html_e( 'Email Reports', 'wp-powersuite' ); ?></a>
		<?php else : ?>
			<span
				class="nav-tab wpps-ed-nav-tab--disabled"
				aria-disabled="true"
				title="<?php esc_attr_e( 'Enable the Email Reports module to configure scheduled digests.', 'wp-powersuite' ); ?>"
			><?php esc_html_e( 'Email Reports', 'wp-powersuite' ); ?></span>
		<?php endif; ?>
	</nav>

	<div
		id="wpps-ed-tab-panel"
		class="wpps-ed-tab-panel"
		data-current-tab="<?php echo esc_attr( $tab ); ?>"
		aria-live="polite"
	>
		<?php if ( $tab === 'test' ) : ?>
			<?php include __DIR__ . '/partials/test-email.php'; ?>
		<?php elseif ( $tab === 'overview' ) : ?>
			<?php include __DIR__ . '/partials/overview.php'; ?>
		<?php else : ?>
			<?php include __DIR__ . '/partials/configure.php'; ?>
		<?php endif; ?>
	</div>
</div>
