<?php
/**
 * Email Logs - Admin Page
 *
 * @var array  $settings
 * @var array  $logs
 * @var int    $total
 * @var int    $total_pages
 * @var int    $paged
 * @var string $search
 * @var string $status_filter
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use WP_PowerSuite\Admin\PageHero;

$nonce      = wp_create_nonce( 'wpps_email_logs' );
$admin_base = \WP_PowerSuite\Core\NetworkScope::adminUrl( 'admin.php' );
$export_url = wp_nonce_url( add_query_arg( 'action', 'wpps_email_logs_export', admin_url( 'admin-post.php' ) ), 'wpps_email_logs_export' );

$settings_btn = sprintf(
	'<button type="button" class="button button-secondary" id="wpps-el-open-settings">%s</button>',
	esc_html__( 'Settings', 'wp-powersuite' )
);
?>
<div class="wrap wpps-email-logs">
	<hr class="wp-header-end" style="margin:0;padding:0;border:none;height:0;overflow:hidden;">

	<?php if ( isset( $_GET['saved'] ) && sanitize_key( wp_unslash( $_GET['saved'] ) ) === '1' ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Settings saved.', 'wp-powersuite' ); ?></p></div>
	<?php endif; ?>

	<?php
	PageHero::render_for_module(
		[
			'icon'      => 'dashicons-email-alt',
			'title'     => __( 'Email Logs', 'wp-powersuite' ),
			'tagline'   => __( 'View outgoing WordPress mail for debugging delivery issues and monitoring notifications.', 'wp-powersuite' ),
			'meta_html' => $settings_btn,
		]
	);
	?>

	<div class="notice notice-warning inline wpps-el-privacy-notice">
		<p><?php esc_html_e( 'Email logs may contain personal data (recipient addresses, subjects, and optionally message bodies). Password reset and security emails can include sensitive links—keep body logging disabled unless required for debugging, and limit access to trusted administrators.', 'wp-powersuite' ); ?></p>
	</div>

	<div class="wpps-el-panel">
		<h2 class="wpps-el-panel-title">
			<?php esc_html_e( 'Recent activity', 'wp-powersuite' ); ?>
			<span class="wpps-el-count"><?php echo esc_html( sprintf( __( '%d total', 'wp-powersuite' ), $total ) ); ?></span>
		</h2>

		<div class="wpps-el-toolbar">
			<form method="get" action="" class="wpps-el-filters">
				<input type="hidden" name="page" value="powersuite-email-logs" />
				<label for="wpps-el-search" class="screen-reader-text"><?php esc_html_e( 'Search email logs', 'wp-powersuite' ); ?></label>
				<input type="search" id="wpps-el-search" name="s" value="<?php echo esc_attr( $search ); ?>" class="wpps-el-search regular-text" placeholder="<?php esc_attr_e( 'Search by subject or recipient…', 'wp-powersuite' ); ?>" />
				<label for="wpps-el-status" class="screen-reader-text"><?php esc_html_e( 'Filter by status', 'wp-powersuite' ); ?></label>
				<select id="wpps-el-status" name="status" class="wpps-el-status-select">
					<option value=""><?php esc_html_e( 'All statuses', 'wp-powersuite' ); ?></option>
					<option value="sent" <?php selected( $status_filter, 'sent' ); ?>><?php esc_html_e( 'Sent', 'wp-powersuite' ); ?></option>
					<option value="failed" <?php selected( $status_filter, 'failed' ); ?>><?php esc_html_e( 'Failed', 'wp-powersuite' ); ?></option>
					<option value="pending" <?php selected( $status_filter, 'pending' ); ?>><?php esc_html_e( 'Pending', 'wp-powersuite' ); ?></option>
				</select>
				<button type="submit" class="button button-primary"><?php esc_html_e( 'Filter', 'wp-powersuite' ); ?></button>
			</form>
			<?php if ( $total > 0 ) : ?>
				<div class="wpps-el-filters">
					<a href="<?php echo esc_url( $export_url ); ?>" class="button"><?php esc_html_e( 'Export CSV', 'wp-powersuite' ); ?></a>
					<button type="button" class="button wpps-el-delete-all-btn" id="wpps-el-delete-all"><?php esc_html_e( 'Delete All', 'wp-powersuite' ); ?></button>
				</div>
			<?php endif; ?>
		</div>

		<div id="wpps-el-logs-container" class="wpps-el-logs-container">
			<?php if ( empty( $logs ) ) : ?>
				<div class="wpps-el-empty">
					<span class="dashicons dashicons-email-alt" aria-hidden="true"></span>
					<h3><?php esc_html_e( 'No emails logged yet', 'wp-powersuite' ); ?></h3>
					<p class="description"><?php esc_html_e( 'Emails will appear here when WordPress sends them (password resets, notifications, WooCommerce receipts, and more).', 'wp-powersuite' ); ?></p>
				</div>
			<?php else : ?>
				<?php foreach ( $logs as $log ) :
					$date    = date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $log->sent_date ) );
					$is_html = ! empty( $log->message ) && preg_match( '/<[^>]+>/', $log->message );
					?>
				<div class="wpps-el-log-item" data-id="<?php echo esc_attr( $log->id ); ?>">
					<div class="wpps-el-log-header" role="button" tabindex="0" aria-expanded="false">
						<div class="wpps-el-log-main">
							<div class="wpps-el-log-subject"><?php echo esc_html( $log->subject ?: __( '(No subject)', 'wp-powersuite' ) ); ?></div>
							<div class="wpps-el-log-meta">
								<?php echo esc_html( $log->to_email ); ?>
								<span class="wpps-el-meta-sep" aria-hidden="true">•</span>
								<?php echo esc_html( $date ); ?>
								<span class="wpps-el-status wpps-el-status--<?php echo esc_attr( $log->status ); ?>"><?php echo esc_html( ucfirst( $log->status ) ); ?></span>
							</div>
						</div>
						<div class="wpps-el-log-actions">
							<button type="button" class="wpps-el-btn-icon wpps-el-copy" data-id="<?php echo esc_attr( $log->id ); ?>" title="<?php esc_attr_e( 'Copy', 'wp-powersuite' ); ?>">
								<span class="dashicons dashicons-admin-page" aria-hidden="true"></span>
								<span class="screen-reader-text"><?php esc_html_e( 'Copy', 'wp-powersuite' ); ?></span>
							</button>
							<?php if ( $is_html ) : ?>
							<button type="button" class="wpps-el-btn-icon wpps-el-preview" data-id="<?php echo esc_attr( $log->id ); ?>" title="<?php esc_attr_e( 'Preview HTML', 'wp-powersuite' ); ?>">
								<span class="dashicons dashicons-visibility" aria-hidden="true"></span>
								<span class="screen-reader-text"><?php esc_html_e( 'Preview HTML', 'wp-powersuite' ); ?></span>
							</button>
							<?php endif; ?>
							<button type="button" class="wpps-el-btn-icon wpps-el-delete" data-id="<?php echo esc_attr( $log->id ); ?>" title="<?php esc_attr_e( 'Delete', 'wp-powersuite' ); ?>">
								<span class="dashicons dashicons-trash" aria-hidden="true"></span>
								<span class="screen-reader-text"><?php esc_html_e( 'Delete', 'wp-powersuite' ); ?></span>
							</button>
							<span class="wpps-el-accordion-icon dashicons dashicons-arrow-down-alt2" aria-hidden="true"></span>
						</div>
					</div>
					<div class="wpps-el-log-content">
						<?php if ( ! empty( $log->error_message ) ) : ?>
						<div class="wpps-el-log-block">
							<div class="wpps-el-log-block-label"><?php esc_html_e( 'Error', 'wp-powersuite' ); ?></div>
							<div class="wpps-el-log-block-body is-error"><?php echo esc_html( $log->error_message ); ?></div>
						</div>
						<?php endif; ?>
						<div class="wpps-el-log-block">
							<div class="wpps-el-log-block-label"><?php esc_html_e( 'Message', 'wp-powersuite' ); ?></div>
							<div class="wpps-el-log-block-body"><?php echo esc_html( $log->message ?: __( '(No content)', 'wp-powersuite' ) ); ?></div>
						</div>
						<?php if ( ! empty( $log->headers ) ) : ?>
						<div class="wpps-el-log-block">
							<div class="wpps-el-log-block-label"><?php esc_html_e( 'Headers', 'wp-powersuite' ); ?></div>
							<div class="wpps-el-log-block-body"><?php echo esc_html( $log->headers ); ?></div>
						</div>
						<?php endif; ?>
						<?php if ( $is_html ) : ?>
						<textarea id="wpps-el-html-<?php echo esc_attr( $log->id ); ?>" class="screen-reader-text" readonly><?php echo esc_textarea( $log->message ); ?></textarea>
						<?php endif; ?>
						<textarea id="wpps-el-copy-<?php echo esc_attr( $log->id ); ?>" class="screen-reader-text" readonly>To: <?php echo esc_textarea( $log->to_email ); ?>

Subject: <?php echo esc_textarea( $log->subject ); ?>

Date: <?php echo esc_textarea( $log->sent_date ); ?>

<?php if ( ! empty( $log->headers ) ) : ?>Headers:
<?php echo esc_textarea( $log->headers ); ?>

<?php endif; ?>Message:
<?php echo esc_textarea( $log->message ); ?></textarea>
					</div>
				</div>
				<?php endforeach; ?>
			<?php endif; ?>
		</div>

		<?php if ( $total_pages > 1 ) : ?>
		<div class="tablenav bottom wpps-el-pagination">
			<div class="tablenav-pages">
				<?php
				$base = add_query_arg( [ 'page' => 'powersuite-email-logs', 'paged' => '%#%' ], $admin_base );
				if ( $search ) {
					$base = add_query_arg( 's', $search, $base );
				}
				if ( $status_filter ) {
					$base = add_query_arg( 'status', $status_filter, $base );
				}
				echo wp_kses_post(
					paginate_links(
						[
							'base'      => $base,
							'format'    => '',
							'prev_text' => '&laquo;',
							'next_text' => '&raquo;',
							'total'     => $total_pages,
							'current'   => $paged,
						]
					)
				);
				?>
			</div>
		</div>
		<?php endif; ?>
	</div>

	<!-- Settings Modal -->
	<div id="wpps-el-settings-modal" class="wpps-el-modal">
	<div class="wpps-el-modal-content">
		<div class="wpps-el-modal-header">
			<h3><?php esc_html_e( 'Settings', 'wp-powersuite' ); ?></h3>
			<button type="button" class="wpps-el-btn-icon wpps-el-modal-close" id="wpps-el-settings-close" title="<?php esc_attr_e( 'Close', 'wp-powersuite' ); ?>">
				<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
				<span class="screen-reader-text"><?php esc_html_e( 'Close', 'wp-powersuite' ); ?></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"><?php esc_html_e( 'Log Limit', 'wp-powersuite' ); ?></th>
						<td>
							<input type="number" name="limit" value="<?php echo esc_attr( min( 200, (int) $settings['limit'] ) ); ?>" min="10" max="200" class="small-text" />
							<p class="description"><?php esc_html_e( 'Maximum number of emails to keep (10–200). Older entries and excess stored content are automatically removed.', 'wp-powersuite' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Log Content', 'wp-powersuite' ); ?></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', 'wp-powersuite' ); ?>
							</label>
							<p class="description"><?php esc_html_e( 'Off by default for privacy. Enable only when debugging delivery issues. Sensitive links and tokens are masked when stored.', 'wp-powersuite' ); ?></p>
						</td>
					</tr>
				</table>
				<p class="wpps-el-modal-actions">
					<button type="submit" class="button button-primary"><?php esc_html_e( 'Save Settings', 'wp-powersuite' ); ?></button>
					<button type="button" class="button wpps-el-settings-cancel"><?php esc_html_e( 'Cancel', 'wp-powersuite' ); ?></button>
				</p>
			</form>
		</div>
	</div>
</div>

<!-- HTML Preview Modal -->
<div id="wpps-el-preview-modal" class="wpps-el-modal wpps-el-preview-modal">
	<div class="wpps-el-preview-content">
		<div class="wpps-el-preview-header">
			<h3><?php esc_html_e( 'HTML Email Preview', 'wp-powersuite' ); ?></h3>
			<button type="button" class="wpps-el-btn-icon" id="wpps-el-preview-close">
				<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
				<span class="screen-reader-text"><?php esc_html_e( 'Close', 'wp-powersuite' ); ?></span>
			</button>
		</div>
		<iframe id="wpps-el-preview-frame" class="wpps-el-preview-frame" title="<?php esc_attr_e( 'Email preview', 'wp-powersuite' ); ?>" sandbox=""></iframe>
	</div>
</div>
</div>

<script>
(function() {
	var nonce = <?php echo wp_json_encode( $nonce ); ?>;

	document.getElementById('wpps-el-open-settings').addEventListener('click', function() {
		document.getElementById('wpps-el-settings-modal').classList.add('is-open');
		document.body.style.overflow = 'hidden';
	});
	function closeSettingsModal() {
		document.getElementById('wpps-el-settings-modal').classList.remove('is-open');
		document.body.style.overflow = '';
	}
	document.getElementById('wpps-el-settings-close').addEventListener('click', closeSettingsModal);
	var cancelBtn = document.querySelector('.wpps-el-settings-cancel');
	if (cancelBtn) cancelBtn.addEventListener('click', closeSettingsModal);
	document.getElementById('wpps-el-settings-modal').addEventListener('click', function(e) {
		if (e.target === this) closeSettingsModal();
	});

	document.querySelectorAll('.wpps-el-log-header').forEach(function(h) {
		function toggleRow() {
			var content = h.nextElementSibling;
			var isOpen = content.classList.contains('is-open');
			content.classList.toggle('is-open', !isOpen);
			h.classList.toggle('is-open', !isOpen);
			h.setAttribute('aria-expanded', isOpen ? 'false' : 'true');
		}
		h.addEventListener('click', function(e) {
			if (e.target.closest('.wpps-el-btn-icon')) return;
			toggleRow();
		});
		h.addEventListener('keydown', function(e) {
			if (e.key === 'Enter' || e.key === ' ') {
				e.preventDefault();
				toggleRow();
			}
		});
	});

	document.querySelectorAll('.wpps-el-copy').forEach(function(btn) {
		btn.addEventListener('click', function(e) {
			e.stopPropagation();
			var id = this.dataset.id;
			var ta = document.getElementById('wpps-el-copy-' + id);
			if (!ta) return;
			navigator.clipboard.writeText(ta.value).then(function() {
				var icon = btn.querySelector('.dashicons');
				icon.classList.remove('dashicons-admin-page');
				icon.classList.add('dashicons-yes');
				setTimeout(function() {
					icon.classList.remove('dashicons-yes');
					icon.classList.add('dashicons-admin-page');
				}, 2000);
			});
		});
	});

	function closePreviewModal() {
		var modal = document.getElementById('wpps-el-preview-modal');
		var iframe = document.getElementById('wpps-el-preview-frame');
		modal.classList.remove('is-open');
		iframe.srcdoc = '';
		document.body.style.overflow = '';
	}

	document.querySelectorAll('.wpps-el-btn-icon.wpps-el-preview').forEach(function(btn) {
		btn.addEventListener('click', function(e) {
			e.stopPropagation();
			var id = this.dataset.id;
			var ta = document.getElementById('wpps-el-html-' + id);
			if (!ta) return;
			document.getElementById('wpps-el-preview-frame').srcdoc = ta.value;
			document.getElementById('wpps-el-preview-modal').classList.add('is-open');
			document.body.style.overflow = 'hidden';
		});
	});

	document.getElementById('wpps-el-preview-close').addEventListener('click', closePreviewModal);

	document.getElementById('wpps-el-preview-modal').addEventListener('click', function(e) {
		if (e.target === this) {
			closePreviewModal();
		}
	});

	document.addEventListener('keydown', function(e) {
		if (e.key === 'Escape') {
			closePreviewModal();
			closeSettingsModal();
		}
	});

	document.querySelectorAll('.wpps-el-delete').forEach(function(btn) {
		btn.addEventListener('click', function(e) {
			e.stopPropagation();
			if (!confirm(<?php echo wp_json_encode( __( 'Delete this log entry?', 'wp-powersuite' ) ); ?>)) return;
			var logItem = this.closest('.wpps-el-log-item');
			if (!logItem) return;
			var formData = new FormData();
			formData.append('action', 'wpps_email_logs_delete');
			formData.append('nonce', nonce);
			formData.append('id', this.dataset.id || '');
			fetch(ajaxurl, { method: 'POST', body: formData })
				.then(function(r) { return r.json(); })
				.then(function(res) {
					if (res.success && logItem) {
						logItem.remove();
					}
				});
		});
	});

	var deleteAllBtn = document.getElementById('wpps-el-delete-all');
	if (deleteAllBtn) {
		deleteAllBtn.addEventListener('click', function() {
			if (!confirm(<?php echo wp_json_encode( __( 'Delete all email logs? This cannot be undone.', 'wp-powersuite' ) ); ?>)) return;
			var formData = new FormData();
			formData.append('action', 'wpps_email_logs_delete_all');
			formData.append('nonce', nonce);
			fetch(ajaxurl, { method: 'POST', body: formData })
				.then(function(r) { return r.json(); })
				.then(function(res) {
					if (res.success) location.reload();
				});
		});
	}
})();
</script>
