<?php
/**
 * Last-send bookkeeping shared by both email transports.
 *
 * @package RewindBrevoFormBridge
 */

namespace RewindBrevoFormBridge\Emails;

defined( 'ABSPATH' ) || exit;

/**
 * Records the outcome of the most recent site email so the Email settings
 * screen can answer "is this actually working?" without a log table.
 *
 * Two autoload-off options only — this is a status light, not a log.
 *
 * @since 0.5.0
 */
class MailStatus {

	/**
	 * Option holding the last failure as ['message', 'created_at'].
	 *
	 * @var string
	 */
	const ERROR_OPTION = 'rbfb_email_last_error';

	/**
	 * Option holding the UTC timestamp of the last accepted send.
	 *
	 * @var string
	 */
	const SENT_OPTION = 'rbfb_email_last_sent';

	/**
	 * Record an accepted send and clear any stale failure.
	 *
	 * @since 0.5.0
	 * @return void
	 */
	public static function record_success(): void {
		update_option( self::SENT_OPTION, current_time( 'mysql', true ), false );

		if ( false !== get_option( self::ERROR_OPTION, false ) ) {
			delete_option( self::ERROR_OPTION );
		}
	}

	/**
	 * Record a failure.
	 *
	 * @since 0.5.0
	 * @param string $message Human-readable failure.
	 * @return void
	 */
	public static function record_failure( string $message ): void {
		update_option(
			self::ERROR_OPTION,
			array(
				'message'    => $message,
				'created_at' => current_time( 'mysql', true ),
			),
			false
		);
	}

	/**
	 * The last failure, or null when the last send went through.
	 *
	 * @since 0.5.0
	 * @return array|null ['message' => string, 'created_at' => string]
	 */
	public static function last_error(): ?array {
		$stored = get_option( self::ERROR_OPTION, null );

		return is_array( $stored ) && isset( $stored['message'] ) ? $stored : null;
	}

	/**
	 * UTC timestamp of the last accepted send.
	 *
	 * @since 0.5.0
	 * @return string Empty string when nothing has been sent yet.
	 */
	public static function last_sent(): string {
		return (string) get_option( self::SENT_OPTION, '' );
	}

	/**
	 * Forget both records.
	 *
	 * @since 0.5.0
	 * @return void
	 */
	public static function clear(): void {
		delete_option( self::ERROR_OPTION );
		delete_option( self::SENT_OPTION );
	}
}
