<?php
/**
 * Gateway logger trait.
 *
 * @package flo-checkout
 */

namespace Flo_Checkout\Gateways\Helpers;

use Exception;
use Flo_Checkout\Shared;
use Northmill_Online_Shared_Checkout\Northmill_Online_Shared\Modules\Loggers\Log_Level_Enum;

defined( 'ABSPATH' ) || exit;

/**
 * Gateway logger trait.
 */
trait Gateway_Logger_Trait {

	/**
	 * Logs a message.
	 *
	 * @param string         $message The message to log.
	 * @param array|null     $context The context to log.
	 * @param Log_Level_Enum $level   The log level.
	 */
	public function log( string $message, ?array $context = null, Log_Level_Enum $level = Log_Level_Enum::DEBUG ): void {

		if ( 'yes' === $this->get_option( 'log_enabled', 'yes' ) ) {
			Shared::instance()->logger->log(
				$this->id,
				$message,
				$context,
				$level
			);
		}
	}


	/**
	 * Throw and log an error.
	 *
	 * @param string         $front_end_message The message to show to the user.
	 * @param array|null     $context           The context to log.
	 * @param string|null    $back_end_message  The message to log. Defaults to the front end message.
	 * @param Log_Level_Enum $log_level         Log level.
	 *
	 * @throws Exception The error.
	 */
	public function log_and_throw_error(
		string $front_end_message,
		?array $context = null,
		?string $back_end_message = null,
		Log_Level_Enum $log_level = Log_Level_Enum::ERROR
	) {
		$back_end_message = $back_end_message ?? $front_end_message;

		$this->log(
			$back_end_message,
			$context,
			$log_level
		);

		throw new Exception(
			esc_html(
				$front_end_message,
			)
		);
	}
}
