<?php
/**
 * Overview — status, delivery chart, recent logs.
 *
 * @package EmailSmtp
 * @var array<string, mixed> $settings
 * @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<string, mixed> $diagnostics
 * @var bool $email_logs_enabled
 * @var string $email_logs_url
 * @var list<string> $conflicting
 * @var string $page_url
 * @var array<string, array<string, mixed>> $connections
 * @var array<string, mixed>|null $overview_series
 * @var list<object> $overview_recent_logs
 */

use EmailSmtp\Includes\ConnectionStore;
use EmailSmtp\Includes\ProviderRegistry;
use WP_PowerSuite\Core\NetworkScope;

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

$settings_url = add_query_arg( [ 'tab' => 'settings' ], $page_url );
$test_url     = add_query_arg( [ 'tab' => 'test' ], $page_url );
$default_id   = sanitize_key( (string) ( $settings['default_connection_id'] ?? '' ) );
$default      = $connections[ $default_id ] ?? null;
$is_ready     = ( $health['key'] ?? '' ) === 'ready';
$conn_count   = count( $connections );

$overview_series      = isset( $overview_series ) && is_array( $overview_series ) ? $overview_series : null;
$overview_recent_logs = isset( $overview_recent_logs ) && is_array( $overview_recent_logs ) ? $overview_recent_logs : [];

$range_start = is_array( $overview_series ) ? (string) ( $overview_series['start'] ?? '' ) : '';
$range_end   = is_array( $overview_series ) ? (string) ( $overview_series['end'] ?? '' ) : '';
$sent_total  = is_array( $overview_series ) ? (int) ( $overview_series['totals']['sent'] ?? 0 ) : 0;
$fail_total  = is_array( $overview_series ) ? (int) ( $overview_series['totals']['failed'] ?? 0 ) : 0;
$site_today  = ( new \DateTimeImmutable( 'today', wp_timezone() ) )->format( 'Y-m-d' );
?>

<?php if ( $conflicting !== [] ) : ?>
	<div class="notice notice-warning inline"><p>
		<?php esc_html_e( 'Another email delivery plugin is active. Disable it if mail delivery misbehaves.', 'wp-powersuite' ); ?>
	</p></div>
<?php endif; ?>

<div class="wpps-ed-panel">
	<h2 class="wpps-ed-panel-title"><?php esc_html_e( 'Connection status', 'wp-powersuite' ); ?></h2>
	<div class="wpps-ed-panel-body">
		<div class="wpps-ed-status-row">
			<span class="wpps-ed-status wpps-ed-status--<?php echo esc_attr( $health['tone'] === 'success' ? 'connected' : ( $health['tone'] === 'danger' ? 'failed' : 'incomplete' ) ); ?>">
				<?php echo esc_html( $health['label'] ); ?>
			</span>
			<p class="description" style="margin:8px 0 0;"><?php echo esc_html( $health['detail'] ); ?></p>
		</div>

		<table class="form-table" role="presentation" style="margin-top:8px;">
			<tr>
				<th><?php esc_html_e( 'Connections', 'wp-powersuite' ); ?></th>
				<td><?php echo esc_html( (string) $conn_count ); ?></td>
			</tr>
			<?php if ( is_array( $default ) ) : ?>
				<?php
				$pid  = sanitize_key( (string) ( $default['provider'] ?? '' ) );
				$prov = ProviderRegistry::get( $pid );
				$icon = ConnectionStore::provider_icon_url( $pid );
				?>
				<tr>
					<th><?php esc_html_e( 'Primary connection', 'wp-powersuite' ); ?></th>
					<td>
						<span class="wpps-ed-conn-provider">
							<?php if ( $icon !== '' ) : ?>
								<img src="<?php echo esc_url( $icon ); ?>" alt="" class="wpps-ed-provider-icon wpps-ed-provider-icon--sm" />
							<?php endif; ?>
							<strong><?php echo esc_html( (string) ( $default['name'] ?? '' ) ); ?></strong>
							— <?php echo esc_html( $prov ? $prov->get_name() : $pid ); ?>
							(<?php echo esc_html( (string) ( $default['from_email'] ?? '' ) ); ?>)
						</span>
					</td>
				</tr>
			<?php endif; ?>
			<tr>
				<th><?php esc_html_e( 'Last success', 'wp-powersuite' ); ?></th>
				<td><?php echo esc_html( ! empty( $diagnostics['last_success_at'] ) ? (string) $diagnostics['last_success_at'] : '—' ); ?></td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'Last failure', 'wp-powersuite' ); ?></th>
				<td><?php echo esc_html( ! empty( $diagnostics['last_failure_at'] ) ? (string) $diagnostics['last_failure_at'] : '—' ); ?></td>
			</tr>
		</table>

		<p>
			<?php if ( ! $is_ready ) : ?>
				<a class="button button-primary" href="<?php echo esc_url( $settings_url ); ?>"><?php esc_html_e( 'Configure connections', 'wp-powersuite' ); ?></a>
			<?php else : ?>
				<a class="button" href="<?php echo esc_url( $settings_url ); ?>"><?php esc_html_e( 'Manage connections', 'wp-powersuite' ); ?></a>
			<?php endif; ?>
			<a class="button" href="<?php echo esc_url( $test_url ); ?>"><?php esc_html_e( 'Send test email', 'wp-powersuite' ); ?></a>
			<?php if ( $email_logs_enabled ) : ?>
				<a class="button" href="<?php echo esc_url( $email_logs_url ); ?>"><?php esc_html_e( 'Email Logs', 'wp-powersuite' ); ?></a>
			<?php endif; ?>
		</p>
	</div>
</div>

<?php if ( $email_logs_enabled && is_array( $overview_series ) ) : ?>
	<div
		class="wpps-ed-panel wpps-ed-overview-card"
		id="wpps-ed-overview-analytics"
		data-start="<?php echo esc_attr( $range_start ); ?>"
		data-end="<?php echo esc_attr( $range_end ); ?>"
	>
		<div class="wpps-ed-overview-card__header">
			<h2 class="wpps-ed-overview-card__title"><?php esc_html_e( 'Overview', 'wp-powersuite' ); ?></h2>
			<div class="wpps-ed-overview-range" id="wpps-ed-overview-range">
				<label class="screen-reader-text" for="wpps-ed-overview-start"><?php esc_html_e( 'Start date', 'wp-powersuite' ); ?></label>
				<input
					type="date"
					id="wpps-ed-overview-start"
					class="wpps-ed-overview-range__input"
					value="<?php echo esc_attr( $range_start ); ?>"
					max="<?php echo esc_attr( $site_today ); ?>"
				/>
				<span class="wpps-ed-overview-range__sep" aria-hidden="true">–</span>
				<label class="screen-reader-text" for="wpps-ed-overview-end"><?php esc_html_e( 'End date', 'wp-powersuite' ); ?></label>
				<input
					type="date"
					id="wpps-ed-overview-end"
					class="wpps-ed-overview-range__input"
					value="<?php echo esc_attr( $range_end ); ?>"
					max="<?php echo esc_attr( $site_today ); ?>"
				/>
			</div>
		</div>
		<div class="wpps-ed-overview-card__body">
			<div class="wpps-ed-overview-stats">
				<div class="wpps-ed-overview-stat">
					<div class="wpps-ed-overview-stat__label">
						<span class="wpps-ed-overview-swatch wpps-ed-overview-swatch--sent" aria-hidden="true"></span>
						<?php esc_html_e( 'Emails sent', 'wp-powersuite' ); ?>
					</div>
					<div class="wpps-ed-overview-stat__value" id="wpps-ed-overview-sent-total"><?php echo esc_html( (string) $sent_total ); ?></div>
				</div>
				<div class="wpps-ed-overview-stat">
					<div class="wpps-ed-overview-stat__label">
						<span class="wpps-ed-overview-swatch wpps-ed-overview-swatch--failed" aria-hidden="true"></span>
						<?php esc_html_e( 'Emails failed', 'wp-powersuite' ); ?>
					</div>
					<div class="wpps-ed-overview-stat__value" id="wpps-ed-overview-failed-total"><?php echo esc_html( (string) $fail_total ); ?></div>
				</div>
			</div>
			<div class="wpps-ed-overview-chart-wrap">
				<svg
					id="wpps-ed-overview-chart"
					class="wpps-ed-overview-chart"
					viewBox="0 0 960 280"
					preserveAspectRatio="none"
					role="img"
					aria-label="<?php esc_attr_e( 'Email sent and failed over time', 'wp-powersuite' ); ?>"
				></svg>
				<div class="wpps-ed-overview-tooltip" id="wpps-ed-overview-tooltip" hidden></div>
				<p class="wpps-ed-overview-chart__empty" id="wpps-ed-overview-empty" hidden>
					<?php esc_html_e( 'No email activity in this date range yet.', 'wp-powersuite' ); ?>
				</p>
			</div>
		</div>
		<script type="application/json" id="wpps-ed-overview-series-data"><?php echo wp_json_encode( $overview_series ); ?></script>
	</div>

	<div class="wpps-ed-panel wpps-ed-recent-logs">
		<div class="wpps-ed-recent-logs__header">
			<h2 class="wpps-ed-recent-logs__title"><?php esc_html_e( 'Recent Email Logs', 'wp-powersuite' ); ?></h2>
			<a class="wpps-ed-recent-logs__view-all" href="<?php echo esc_url( $email_logs_url ); ?>">
				<?php esc_html_e( 'View all', 'wp-powersuite' ); ?>
				<span class="dashicons dashicons-external" aria-hidden="true"></span>
			</a>
		</div>
		<?php if ( $overview_recent_logs === [] ) : ?>
			<div class="wpps-ed-panel-body">
				<p class="description" style="margin:0;"><?php esc_html_e( 'No emails logged yet. New WordPress mail will appear here automatically.', 'wp-powersuite' ); ?></p>
			</div>
		<?php else : ?>
			<div class="wpps-ed-recent-logs__table-wrap">
				<table class="wpps-ed-recent-logs__table">
					<thead>
						<tr>
							<th><?php esc_html_e( 'Email To', 'wp-powersuite' ); ?></th>
							<th><?php esc_html_e( 'Status', 'wp-powersuite' ); ?></th>
							<th><?php esc_html_e( 'Subject', 'wp-powersuite' ); ?></th>
							<th><?php esc_html_e( 'Date', 'wp-powersuite' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $overview_recent_logs as $log ) : ?>
							<?php
							$status    = sanitize_key( (string) ( $log->status ?? 'pending' ) );
							$transport = sanitize_key( (string) ( $log->transport ?? '' ) );
							if ( $transport === 'simulation' ) {
								$label = __( 'Simulated', 'wp-powersuite' );
								$badge = 'pending';
							} elseif ( $status === 'sent' ) {
								$label = __( 'Sent', 'wp-powersuite' );
								$badge = 'success';
							} elseif ( $status === 'failed' ) {
								$label = __( 'Failed', 'wp-powersuite' );
								$badge = 'failed';
							} else {
								$label = ucfirst( $status );
								$badge = 'pending';
							}
							$subject = (string) ( $log->subject ?? '' );
							if ( $subject === '' ) {
								$subject = __( '(No subject)', 'wp-powersuite' );
							}
							$ts        = strtotime( (string) ( $log->sent_date ?? '' ) );
							$date_label = $ts ? date_i18n( 'M d', $ts ) : '—';
							?>
							<tr>
								<td class="wpps-ed-recent-logs__to"><?php echo esc_html( (string) ( $log->to_email ?? '' ) ); ?></td>
								<td>
									<span class="wpps-ed-log-badge wpps-ed-log-badge--<?php echo esc_attr( $badge ); ?>">
										<?php echo esc_html( $label ); ?>
									</span>
								</td>
								<td class="wpps-ed-recent-logs__subject" title="<?php echo esc_attr( $subject ); ?>">
									<?php echo esc_html( wp_html_excerpt( $subject, 36, '…' ) ); ?>
								</td>
								<td class="wpps-ed-recent-logs__date"><?php echo esc_html( $date_label ); ?></td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			</div>
		<?php endif; ?>
	</div>
<?php elseif ( ! $email_logs_enabled ) : ?>
	<div class="wpps-ed-panel">
		<h2 class="wpps-ed-panel-title"><?php esc_html_e( 'Email activity', 'wp-powersuite' ); ?></h2>
		<div class="wpps-ed-panel-body">
			<p class="description" style="margin-top:0;">
				<?php esc_html_e( 'Enable the Email Logs module to see sent/failed charts and recent delivery history on this overview.', 'wp-powersuite' ); ?>
			</p>
			<p>
				<a class="button button-primary" href="<?php echo esc_url( NetworkScope::adminUrl( 'admin.php', [ 'page' => 'powersuite' ] ) ); ?>">
					<?php esc_html_e( 'Open modules', 'wp-powersuite' ); ?>
				</a>
			</p>
		</div>
	</div>
<?php else : ?>
	<div class="wpps-ed-panel">
		<h2 class="wpps-ed-panel-title"><?php esc_html_e( 'Email activity', 'wp-powersuite' ); ?></h2>
		<div class="wpps-ed-panel-body">
			<p class="description" style="margin:0;">
				<?php esc_html_e( 'Email Logs is enabled, but overview analytics could not be loaded. Try refreshing the page.', 'wp-powersuite' ); ?>
			</p>
		</div>
	</div>
<?php endif; ?>
