<?php
/**
 * Email Logs - Admin Page (WP_List_Table + modals).
 *
 * @var array                                  $settings
 * @var \EmailLogs\Includes\EmailLogsListTable $list_table
 * @var string                                 $notice
 * @var array{total:int,sent:int,failed:int,bounced:int,delivered:int,today:int} $stats
 * @var list<string>                           $providers
 */

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

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

$status_filter   = isset( $_REQUEST['status'] ) ? sanitize_key( wp_unslash( (string) $_REQUEST['status'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$search_value    = isset( $_REQUEST['s'] ) ? sanitize_text_field( wp_unslash( (string) $_REQUEST['s'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$provider_filter = isset( $_REQUEST['provider'] ) ? sanitize_key( wp_unslash( (string) $_REQUEST['provider'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$stats           = isset( $stats ) && is_array( $stats ) ? $stats : [];
$providers       = isset( $providers ) && is_array( $providers ) ? $providers : [];
$page_url        = NetworkScope::adminUrl( 'admin.php', [ 'page' => 'powersuite-email-logs' ] );
$delivery_url    = NetworkScope::adminUrl( 'admin.php', [ 'page' => 'powersuite-email-delivery' ] );

$meta_html = sprintf(
	'<a href="%1$s" class="button button-secondary">%2$s</a> <button type="button" class="button button-secondary" id="wpps-el-open-settings">%3$s</button>',
	esc_url( $delivery_url ),
	esc_html__( 'Email Delivery', 'wppowersuite-lite' ),
	esc_html__( 'Settings', 'wppowersuite-lite' )
);

$hero_stats = [
	[
		'value' => number_format_i18n( (int) ( $stats['today'] ?? 0 ) ),
		'label' => __( 'Today', 'wppowersuite-lite' ),
	],
	[
		'value' => number_format_i18n( (int) ( $stats['sent'] ?? 0 ) ),
		'label' => __( 'Sent', 'wppowersuite-lite' ),
	],
	[
		'value' => number_format_i18n( (int) ( $stats['failed'] ?? 0 ) ),
		'label' => __( 'Failed', 'wppowersuite-lite' ),
	],
	[
		'value' => number_format_i18n( (int) ( $stats['bounced'] ?? 0 ) ),
		'label' => __( 'Bounced', 'wppowersuite-lite' ),
	],
];

$has_filters = $status_filter !== '' || $search_value !== '' || $provider_filter !== '';
?>
<div class="wrap wpps-email-logs wpps-el-wrap">
	<hr class="wp-header-end" style="margin:0;padding:0;border:none;height:0;overflow:hidden;">

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

	<?php
	PageHero::render_for_module(
		[
			'icon'      => 'dashicons-email-alt',
			'title'     => __( 'Email Logs', 'wppowersuite-lite' ),
			'tagline'   => __( 'Inspect outbound mail, delivery events, and resend failed messages.', 'wppowersuite-lite' ),
			'stats'     => $hero_stats,
			'meta_html' => $meta_html,
		]
	);
	?>

	<div class="wpps-el-panel">
		<div class="wpps-el-panel-title"><?php esc_html_e( 'Filters', 'wppowersuite-lite' ); ?></div>
		<div class="wpps-el-panel-body">
			<form method="get" action="" class="wpps-el-filter-form">
				<input type="hidden" name="page" value="powersuite-email-logs" />

				<div class="wpps-el-filter-row">
					<div class="wpps-el-filter-group wpps-el-filter-group--grow">
						<label for="wpps-el-search"><?php esc_html_e( 'Search', 'wppowersuite-lite' ); ?></label>
						<input type="search" id="wpps-el-search" name="s" value="<?php echo esc_attr( $search_value ); ?>" placeholder="<?php esc_attr_e( 'Subject, recipient, or message ID…', 'wppowersuite-lite' ); ?>" />
					</div>

					<div class="wpps-el-filter-group">
						<label for="wpps-el-status"><?php esc_html_e( 'Status', 'wppowersuite-lite' ); ?></label>
						<select name="status" id="wpps-el-status">
							<option value=""><?php esc_html_e( 'All statuses', 'wppowersuite-lite' ); ?></option>
							<option value="sent" <?php selected( $status_filter, 'sent' ); ?>><?php esc_html_e( 'Sent', 'wppowersuite-lite' ); ?></option>
							<option value="failed" <?php selected( $status_filter, 'failed' ); ?>><?php esc_html_e( 'Failed', 'wppowersuite-lite' ); ?></option>
							<option value="pending" <?php selected( $status_filter, 'pending' ); ?>><?php esc_html_e( 'Pending', 'wppowersuite-lite' ); ?></option>
							<option value="accepted" <?php selected( $status_filter, 'accepted' ); ?>><?php esc_html_e( 'Accepted', 'wppowersuite-lite' ); ?></option>
							<option value="delivered" <?php selected( $status_filter, 'delivered' ); ?>><?php esc_html_e( 'Delivered', 'wppowersuite-lite' ); ?></option>
							<option value="bounced" <?php selected( $status_filter, 'bounced' ); ?>><?php esc_html_e( 'Bounced', 'wppowersuite-lite' ); ?></option>
							<option value="complained" <?php selected( $status_filter, 'complained' ); ?>><?php esc_html_e( 'Spam complaint', 'wppowersuite-lite' ); ?></option>
							<option value="deferred" <?php selected( $status_filter, 'deferred' ); ?>><?php esc_html_e( 'Deferred', 'wppowersuite-lite' ); ?></option>
						</select>
					</div>

					<div class="wpps-el-filter-group">
						<label for="wpps-el-provider"><?php esc_html_e( 'Provider', 'wppowersuite-lite' ); ?></label>
						<select name="provider" id="wpps-el-provider">
							<option value=""><?php esc_html_e( 'All providers', 'wppowersuite-lite' ); ?></option>
							<?php foreach ( $providers as $provider_id ) : ?>
								<option value="<?php echo esc_attr( $provider_id ); ?>" <?php selected( $provider_filter, $provider_id ); ?>>
									<?php echo esc_html( $provider_id ); ?>
								</option>
							<?php endforeach; ?>
						</select>
					</div>

					<div class="wpps-el-filter-group wpps-el-filter-group--actions">
						<span class="wpps-el-filter-group-label"><?php esc_html_e( 'Actions', 'wppowersuite-lite' ); ?></span>
						<div class="wpps-el-filter-actions">
							<button type="submit" class="button button-primary"><?php esc_html_e( 'Apply', 'wppowersuite-lite' ); ?></button>
							<?php if ( $has_filters ) : ?>
								<a class="button" href="<?php echo esc_url( $page_url ); ?>"><?php esc_html_e( 'Reset', 'wppowersuite-lite' ); ?></a>
							<?php endif; ?>
						</div>
					</div>
				</div>
			</form>
		</div>
	</div>

	<div class="wpps-el-panel wpps-el-panel--table">
		<div class="wpps-el-panel-title wpps-el-panel-title--split">
			<span><?php esc_html_e( 'Outbound mail', 'wppowersuite-lite' ); ?></span>
			<span class="wpps-el-panel-meta">
				<?php
				printf(
					/* translators: %s: total log count */
					esc_html__( '%s stored', 'wppowersuite-lite' ),
					esc_html( number_format_i18n( (int) ( $stats['total'] ?? 0 ) ) )
				);
				?>
			</span>
		</div>
		<div class="wpps-el-panel-body wpps-el-panel-body--table">
			<?php $list_table->views(); ?>

			<form method="post" action="">
				<input type="hidden" name="page" value="powersuite-email-logs" />
				<?php if ( $status_filter !== '' ) : ?>
					<input type="hidden" name="status" value="<?php echo esc_attr( $status_filter ); ?>" />
				<?php endif; ?>
				<?php if ( $search_value !== '' ) : ?>
					<input type="hidden" name="s" value="<?php echo esc_attr( $search_value ); ?>" />
				<?php endif; ?>
				<?php if ( $provider_filter !== '' ) : ?>
					<input type="hidden" name="provider" value="<?php echo esc_attr( $provider_filter ); ?>" />
				<?php endif; ?>
				<?php $list_table->display(); ?>
			</form>
		</div>
	</div>

	<!-- Settings Modal -->
	<div id="wpps-el-settings-modal" class="wpps-el-modal" aria-hidden="true" role="dialog" aria-labelledby="wpps-el-settings-title">
		<div class="wpps-el-modal-dialog" role="document">
			<div class="wpps-el-modal-header">
				<h2 id="wpps-el-settings-title"><?php esc_html_e( 'Settings', 'wppowersuite-lite' ); ?></h2>
				<button type="button" class="button-link wpps-el-modal-close" data-wpps-el-close title="<?php esc_attr_e( 'Close', 'wppowersuite-lite' ); ?>">
					<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
					<span class="screen-reader-text"><?php esc_html_e( 'Close', 'wppowersuite-lite' ); ?></span>
				</button>
			</div>
			<div class="wpps-el-modal-body">
				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
					<input type="hidden" name="action" value="wpps_email_logs_save_settings" />
					<?php wp_nonce_field( 'wpps_email_logs_settings' ); ?>
					<table class="form-table" role="presentation">
						<tr>
							<th scope="row"><label for="wpps-el-retention"><?php esc_html_e( 'Keep logs for', 'wppowersuite-lite' ); ?></label></th>
							<td>
								<select id="wpps-el-retention" name="retention_days">
									<?php foreach ( \EmailLogs\Includes\EmailLogService::retention_day_options() as $days ) : ?>
										<option value="<?php echo esc_attr( (string) $days ); ?>" <?php selected( (int) ( $settings['retention_days'] ?? 30 ), $days ); ?>>
											<?php
											echo esc_html(
												sprintf(
													/* translators: %d: number of days */
													_n( '%d day', '%d days', $days, 'wppowersuite-lite' ),
													$days
												)
											);
											?>
										</option>
									<?php endforeach; ?>
								</select>
								<p class="description"><?php esc_html_e( 'Older entries are removed automatically. Newer mail is kept first.', 'wppowersuite-lite' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="wpps-el-limit"><?php esc_html_e( 'Maximum entries', 'wppowersuite-lite' ); ?></label></th>
							<td>
								<select id="wpps-el-limit" name="limit">
									<?php
									$limit_choices = [ 100, 250, 500, 1000, 2500, 5000 ];
									$current_limit = (int) ( $settings['limit'] ?? 1000 );
									if ( ! in_array( $current_limit, $limit_choices, true ) ) {
										$limit_choices[] = $current_limit;
										sort( $limit_choices );
									}
									foreach ( $limit_choices as $choice ) :
										?>
										<option value="<?php echo esc_attr( (string) $choice ); ?>" <?php selected( $current_limit, $choice ); ?>>
											<?php echo esc_html( number_format_i18n( $choice ) ); ?>
										</option>
									<?php endforeach; ?>
								</select>
								<p class="description"><?php esc_html_e( 'Maximum rows kept inside the retention window (50–5,000).', 'wppowersuite-lite' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e( 'Log Content', 'wppowersuite-lite' ); ?></th>
							<td>
								<label>
									<input type="checkbox" name="log_content" value="1" <?php checked( ! empty( $settings['log_content'] ) ); ?> />
									<?php esc_html_e( 'Store email body content in logs', 'wppowersuite-lite' ); ?>
								</label>
								<p class="description"><?php esc_html_e( 'Off by default for privacy. Enable only when debugging — required for Resend. Password-reset links, magic-login tokens, and one-time codes are redacted before storage and again when you view or resend a log.', 'wppowersuite-lite' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e( 'Dashboard widget', 'wppowersuite-lite' ); ?></th>
							<td>
								<label>
									<input type="hidden" name="dashboard_widget" value="0" />
									<input type="checkbox" name="dashboard_widget" value="1" <?php checked( ! empty( $settings['dashboard_widget'] ) ); ?> />
									<?php esc_html_e( 'Show Email Logs summary on the WordPress Dashboard', 'wppowersuite-lite' ); ?>
								</label>
							</td>
						</tr>
					</table>
					<p class="wpps-el-modal-actions">
						<button type="submit" class="button button-primary"><?php esc_html_e( 'Save Settings', 'wppowersuite-lite' ); ?></button>
						<button type="button" class="button" data-wpps-el-close><?php esc_html_e( 'Cancel', 'wppowersuite-lite' ); ?></button>
					</p>
				</form>
			</div>
		</div>
	</div>

	<!-- View Log Modal -->
	<div id="wpps-el-view-modal" class="wpps-el-modal" aria-hidden="true" role="dialog" aria-labelledby="wpps-el-view-title">
		<div class="wpps-el-modal-dialog wpps-el-modal-dialog--wide wpps-el-modal-dialog--view" role="document">
			<div class="wpps-el-modal-header">
				<div class="wpps-el-modal-header__text">
					<p class="wpps-el-modal-kicker"><?php esc_html_e( 'Email details', 'wppowersuite-lite' ); ?></p>
					<h2 id="wpps-el-view-title"><?php esc_html_e( 'Email details', 'wppowersuite-lite' ); ?></h2>
					<div id="wpps-el-view-badges" class="wpps-el-modal-badges" hidden></div>
				</div>
				<button type="button" class="button-link wpps-el-modal-close" data-wpps-el-close title="<?php esc_attr_e( 'Close', 'wppowersuite-lite' ); ?>">
					<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
					<span class="screen-reader-text"><?php esc_html_e( 'Close', 'wppowersuite-lite' ); ?></span>
				</button>
			</div>
			<div class="wpps-el-modal-body" id="wpps-el-view-body">
				<p class="wpps-el-loading"><?php esc_html_e( 'Loading…', 'wppowersuite-lite' ); ?></p>
			</div>
			<div class="wpps-el-modal-footer" id="wpps-el-view-footer" hidden></div>
		</div>
	</div>

	<!-- HTML Preview Modal -->
	<div id="wpps-el-preview-modal" class="wpps-el-modal" aria-hidden="true" role="dialog" aria-labelledby="wpps-el-preview-title">
		<div class="wpps-el-modal-dialog wpps-el-modal-dialog--preview" role="document">
			<div class="wpps-el-modal-header">
				<h2 id="wpps-el-preview-title"><?php esc_html_e( 'HTML Email Preview', 'wppowersuite-lite' ); ?></h2>
				<button type="button" class="button-link wpps-el-modal-close" data-wpps-el-close title="<?php esc_attr_e( 'Close', 'wppowersuite-lite' ); ?>">
					<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
					<span class="screen-reader-text"><?php esc_html_e( 'Close', 'wppowersuite-lite' ); ?></span>
				</button>
			</div>
			<iframe id="wpps-el-preview-frame" class="wpps-el-preview-frame" title="<?php esc_attr_e( 'Email preview', 'wppowersuite-lite' ); ?>" sandbox="" referrerpolicy="no-referrer" srcdoc="&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;head&gt;&lt;meta charset=&quot;utf-8&quot;&gt;&lt;/head&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt;"></iframe>
		</div>
	</div>
</div>
