<?php
/**
 * Email Report Section: Email Delivery
 *
 * @package EmailReports
 */

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

$primary_color = (string) ( $branding['primary_color'] ?? '#2271b1' );
$sent          = isset( $data['total_sent'] ) ? number_format_i18n( $data['total_sent'] ) : '0';
$failed        = isset( $data['total_failed'] ) ? number_format_i18n( $data['total_failed'] ) : '0';
$delivered     = isset( $data['total_delivered'] ) ? number_format_i18n( $data['total_delivered'] ) : '0';
$bounced       = isset( $data['total_bounced'] ) ? number_format_i18n( $data['total_bounced'] ) : '0';
$failed_color  = (int) ( $data['total_failed'] ?? 0 ) > 0 ? '#d63638' : $primary_color;
$bounce_color  = (int) ( $data['total_bounced'] ?? 0 ) > 0 ? '#d63638' : $primary_color;

wpps_er_render_stat_card( $sent, __( 'Sent', 'wp-powersuite' ), '#00a32a' );
wpps_er_render_stat_card( $delivered, __( 'Delivered', 'wp-powersuite' ), '#00a32a' );
wpps_er_render_stat_card( $failed, __( 'Failed', 'wp-powersuite' ), $failed_color );
wpps_er_render_stat_card( $bounced, __( 'Bounced', 'wp-powersuite' ), $bounce_color );

if ( ! empty( $data['recent_emails'] ) ) :
	wpps_er_render_subheading( __( 'Recent Emails', 'wp-powersuite' ) );
	foreach ( array_slice( $data['recent_emails'], 0, 5 ) as $row ) :
		$status   = (string) ( $row['status'] ?? '' );
		$delivery = sanitize_key( (string) ( $row['delivery_status'] ?? '' ) );
		$label    = $delivery !== '' ? ucfirst( str_replace( '_', ' ', $delivery ) ) : ucfirst( $status );
		$status_color = in_array( $delivery, [ 'bounced', 'complained', 'rejected' ], true ) || $status === 'failed'
			? '#d63638'
			: ( in_array( $delivery, [ 'delivered', 'accepted' ], true ) || $status === 'sent' ? '#00a32a' : $primary_color );
		wpps_er_render_list_item(
			(string) ( $row['subject'] ?? '' ),
			$label,
			[ 'secondary_color' => $status_color ]
		);
	endforeach;
endif;

if ( (int) ( $data['total_sent'] ?? 0 ) === 0 && (int) ( $data['total_failed'] ?? 0 ) === 0 ) :
	?>
	<p style="color:#646970;margin:0;"><?php esc_html_e( 'No emails logged during this period.', 'wp-powersuite' ); ?></p>
	<?php
endif;
