<?php
/**
 * Request-local mail event type context.
 *
 * @package SubmissionInbox
 */

namespace SUBIN\MailLog;

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

/**
 * Identifies plugin-owned mail purposes without storing message content.
 *
 * The stack makes the context safe for nested/re-entrant wp_mail() calls. A
 * caller must always pop in a finally block so unrelated mail is not tagged.
 */
final class MailEventTypeContext {
	const KIND_GENERIC              = 'generic';
	const KIND_ADMIN_NOTIFICATION   = 'admin_notification';
	const KIND_VISITOR_CONFIRMATION = 'visitor_confirmation';
	const KIND_AUTO_REPLY_TEST      = 'auto_reply_test';
	const KIND_HEALTH_VERIFICATION  = 'health_verification';

	/** @var array<int,string> */
	private static $stack = array();

	/**
	 * Push a validated event kind.
	 *
	 * @param mixed $event_kind Event kind.
	 * @return bool
	 */
	public static function push( $event_kind ) {
		$event_kind = self::sanitize( $event_kind );
		if ( '' === $event_kind ) {
			return false;
		}

		self::$stack[] = $event_kind;
		return true;
	}

	/**
	 * Pop the innermost event kind.
	 *
	 * @return string
	 */
	public static function pop() {
		$value = array_pop( self::$stack );
		return is_string( $value ) ? $value : '';
	}

	/**
	 * Get the innermost event kind.
	 *
	 * @return string
	 */
	public static function current() {
		$value = end( self::$stack );
		return is_string( $value ) ? $value : '';
	}

	/**
	 * Normalize an event kind through a closed allowlist.
	 *
	 * @param mixed $event_kind Event kind.
	 * @return string
	 */
	public static function sanitize( $event_kind ) {
		$event_kind = sanitize_key( is_scalar( $event_kind ) ? (string) $event_kind : '' );
		return in_array( $event_kind, self::allowed(), true ) ? $event_kind : '';
	}

	/** @return array<int,string> */
	public static function allowed() {
		return array(
			self::KIND_GENERIC,
			self::KIND_ADMIN_NOTIFICATION,
			self::KIND_VISITOR_CONFIRMATION,
			self::KIND_AUTO_REPLY_TEST,
			self::KIND_HEALTH_VERIFICATION,
		);
	}
}
