<?php
/**
 * Site-wide limit on marketing emails per customer.
 *
 * @package CartCue
 */

namespace CartCue;

defined( 'ABSPATH' ) || exit;

final class GlobalEmailCap {

	public static function is_enabled(): bool {
		$s = MarketingConsent::get_settings();
		return '1' === (string) ( $s['global_email_cap_enabled'] ?? '0' );
	}

	public static function max_count(): int {
		$s = MarketingConsent::get_settings();
		return max( 1, (int) ( $s['global_email_cap_count'] ?? 3 ) );
	}

	public static function window_days(): int {
		$s = MarketingConsent::get_settings();
		return max( 1, (int) ( $s['global_email_cap_days'] ?? 7 ) );
	}

	/**
	 * Whether another CartCue email may be sent to this address.
	 */
	public static function can_send_to( string $email ): bool {
		$email = sanitize_email( $email );
		if ( ! is_email( $email ) || ! self::is_enabled() ) {
			return true;
		}

		global $wpdb;

		$days  = self::window_days();
		$limit = self::max_count();

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$sent = (int) $wpdb->get_var(
			$wpdb->prepare(
				'SELECT COUNT(*) FROM %i
				 WHERE customer_email = %s
				   AND sent_at >= DATE_SUB(NOW(), INTERVAL %d DAY)',
				DB::email_tracking(),
				$email,
				$days
			)
		);

		return $sent < $limit;
	}
}
