<?php
/**
 * Request and response logger trait.
 *
 * @package flo-checkout
 */

namespace Flo_Checkout\Gateways\Shift4_APM\Traits;

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

defined( 'ABSPATH' ) || exit;

/**
 * Request and response logger trait.
 */
trait Request_And_Response_Logger_Trait {

	/**
	 * Logs a message to the log.
	 *
	 * @param string         $message The message.
	 * @param array|null     $context Any context.
	 * @param Log_Level_Enum $level   Log level.
	 *
	 * @return void
	 */
	protected function log( string $message, ?array $context = null, Log_Level_Enum $level = Log_Level_Enum::DEBUG ): void {
		Shared::instance()->logger->log(
			'shift4-apm',
			$message,
			$context,
			$level
		);
	}

	/**
	 * Logs and throws an error.
	 *
	 * @param string         $front_end_message Message to display in application front end (to end user).
	 * @param array|null     $context           Any context to log (and not show).
	 * @param string|null    $back_end_message  Title of message to log (not shown). Defaults to front end message.
	 * @param Log_Level_Enum $log_level Log level.
	 *
	 * @throws Exception Always throws an error.
	 */
	protected 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
	): never {
		$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,
			)
		);
	}
}
