<?php
/**
 * MailDelivery — native wp_mail health check for CartCue settings.
 *
 * @package CartCue
 */

namespace CartCue;

defined( 'ABSPATH' ) || exit;

final class MailDelivery {

	private const OPTION_KEY = 'cartcue_mail_delivery';

	public static function init(): void {
		add_action( 'wp_ajax_cartcue_test_mail_delivery', [ self::class, 'ajax_test' ] );
	}

	/**
	 * @return array{success: bool, message: string, tested_at: int}
	 */
	public static function get_status(): array {
		$stored = get_option( self::OPTION_KEY, [] );
		if ( ! is_array( $stored ) ) {
			$stored = [];
		}
		return [
			'success'   => ! empty( $stored['success'] ),
			'message'   => (string) ( $stored['message'] ?? '' ),
			'tested_at' => (int) ( $stored['tested_at'] ?? 0 ),
		];
	}

	/**
	 * Send a minimal test message via wp_mail (same path as play emails).
	 *
	 * @return array{success: bool, message: string, tested_at: int}
	 */
	public static function run_test(): array {
		$to      = get_option( 'admin_email' );
		$subject = sprintf(
			/* translators: %s: site name */
			__( '[%s] CartCue email delivery test', 'cartcue-sales-automation' ),
			get_bloginfo( 'name' )
		);
		$body = __( 'This is a CartCue delivery test. If you received this, wp_mail is working on your site — the same path used for abandoned cart and order emails.', 'cartcue-sales-automation' );

		$sent = wp_mail(
			$to,
			$subject,
			$body,
			[
				'Content-Type: text/plain; charset=UTF-8',
				sprintf( 'From: %s <%s>', get_bloginfo( 'name' ), $to ),
			]
		);

		$result = [
			'success'   => (bool) $sent,
			'message'   => $sent
				? __( 'Test email accepted by WordPress. Check your inbox (and spam folder).', 'cartcue-sales-automation' )
				: __( 'wp_mail returned false. Install an SMTP plugin (e.g. WP Mail SMTP or FluentSMTP) — the same stack WooCommerce order emails use.', 'cartcue-sales-automation' ),
			'tested_at' => time(),
		];

		update_option( self::OPTION_KEY, $result, false );

		return $result;
	}

	public static function ajax_test(): void {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( __( 'Permission denied.', 'cartcue-sales-automation' ) );
		}
		check_ajax_referer( 'cartcue_test_mail_delivery', 'nonce' );

		$result = self::run_test();
		if ( $result['success'] ) {
			wp_send_json_success( $result );
		}
		wp_send_json_error( $result );
	}

	public static function should_show_failure_notice(): bool {
		$status = self::get_status();
		if ( empty( $status['tested_at'] ) ) {
			return false;
		}
		return ! $status['success'];
	}
}
