<?php
/**
 * Email Statistics Trait for ACR Tiles
 *
 * Provides shared email statistics querying with caching to prevent
 * redundant database queries when multiple tiles need the same data.
 *
 * @package     EDD\Pro\CartRecovery\Admin\Reports\Endpoints\Tiles\Traits
 * @copyright   Copyright (c) 2026, Sandhills Development, LLC
 * @license     https://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       3.6.5
 */

namespace EDD\Pro\CartRecovery\Admin\Reports\Endpoints\Tiles\Traits;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit; // @codeCoverageIgnore

/**
 * Trait for sharing email statistics queries across multiple tiles.
 *
 * Uses a static cache to ensure the database query only runs once
 * even when multiple tiles request the same data.
 *
 * @since 3.6.5
 */
trait Emails {

	/**
	 * Cached email statistics keyed by date range.
	 *
	 * @var array
	 */
	private static $email_stats_cache = array();

	/**
	 * Gets email statistics for the current date range.
	 *
	 * Results are cached statically so multiple tiles can access
	 * the same data without running redundant queries.
	 *
	 * @since 3.6.5
	 * @return array {
	 *     Email statistics.
	 *
	 *     @type int   $sent       Emails sent.
	 *     @type int   $opened     Emails opened.
	 *     @type int   $clicked    Emails clicked.
	 *     @type int   $converted  Emails converted.
	 *     @type float $open_rate  Open rate percentage.
	 *     @type float $click_rate Click rate percentage.
	 * }
	 */
	protected function get_email_stats(): array {
		global $wpdb;

		// Create cache key from date range.
		$cache_key = sprintf(
			'%s_%s',
			$this->dates['start']->format( 'Y-m-d-H-i-s' ),
			$this->dates['end']->format( 'Y-m-d-H-i-s' )
		);

		// Return cached result if available.
		if ( isset( self::$email_stats_cache[ $cache_key ] ) ) {
			return self::$email_stats_cache[ $cache_key ];
		}

		$table_name = $wpdb->prefix . 'edd_acr_emails';

		$date_start  = $this->dates['start']->format( 'Y-m-d H:i:s' );
		$date_finish = $this->dates['end']->format( 'Y-m-d H:i:s' );

		$stats = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT
					COUNT(*) AS sent,
					COUNT(CASE WHEN date_opened IS NOT NULL THEN 1 END) AS opened,
					COUNT(CASE WHEN date_clicked IS NOT NULL THEN 1 END) AS clicked,
					COUNT(CASE WHEN date_converted IS NOT NULL THEN 1 END) AS converted
				 FROM {$table_name}
				 WHERE date_sent BETWEEN %s AND %s",
				$date_start,
				$date_finish
			)
		);

		if ( empty( $stats ) ) {
			$default_stats = $this->get_default_email_stats();
			self::$email_stats_cache[ $cache_key ] = $default_stats;
			return $default_stats;
		}

		$sent      = (int) $stats->sent;
		$opened    = (int) $stats->opened;
		$clicked   = (int) $stats->clicked;
		$converted = (int) $stats->converted;

		// Calculate rates with safe division.
		$open_rate  = $sent > 0 ? round( ( $opened / $sent ) * 100, 2 ) : 0.0;
		$click_rate = $opened > 0 ? round( ( $clicked / $opened ) * 100, 2 ) : 0.0;

		$result = array(
			'sent'       => $sent,
			'opened'     => $opened,
			'clicked'    => $clicked,
			'converted'  => $converted,
			'open_rate'  => $open_rate,
			'click_rate' => $click_rate,
		);

		// Cache the result.
		self::$email_stats_cache[ $cache_key ] = $result;

		return $result;
	}

	/**
	 * Returns default email statistics structure.
	 *
	 * @since 3.6.5
	 * @return array
	 */
	private function get_default_email_stats(): array {
		return array(
			'sent'       => 0,
			'opened'     => 0,
			'clicked'    => 0,
			'converted'  => 0,
			'open_rate'  => 0.0,
			'click_rate' => 0.0,
		);
	}
}
