<?php

declare(strict_types=1);

namespace Enot;

// Avoid direct access to this piece of code
defined('ABSPATH') || exit;

use Throwable;

final class EnotNotifierLog extends EnotNotifier
{
	public static string $log = '';

	// TODO: Create different methods for the plain and html messages
	// depending on the html_errors

	protected static function format(): string
	{
		$severity = Enot::getSeverityLevel(self::$e);

		$log = sprintf(
			'PHP %1$s (%2$s): %3$s in %4$s on line %5$d',
			self::severityName($severity),
			$severity,
			self::$e->getMessage(),
			\esc_html(self::$e->getFile()),
			filter_var(self::$e->getLine(), FILTER_SANITIZE_NUMBER_INT),
		);

		if (!empty($_SERVER['REQUEST_URI'])) {
			$log .= "\nREQUEST_URI: " . \esc_url_raw(\wp_unslash($_SERVER['REQUEST_URI']));
		}

		if (isset($_SERVER['HTTP_USER_AGENT'])) {
			$log .= "\nUser-Agent: " . \sanitize_text_field(\wp_unslash($_SERVER['HTTP_USER_AGENT']));
		}

		if (!empty($_SERVER['HTTP_REFERER'])) {
			$log .= ", referer: " .  \esc_url_raw(\wp_unslash($_SERVER['HTTP_REFERER']));
		}

		$log .= "\nRequest IP: " . self::getRequestIp();

		return $log;
	}

	public static function notify(Throwable $e): bool
	{
		self::$e = $e;
		$severity = Enot::getSeverityLevel($e);

		// Earlier formatting of the log message for other consumers
		$log = self::format();
		self::$log = $log;

		if (Enot::$config['log_errors'] === false) {
			return false;
		}

		// phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log
		return error_log($log);
	}
}
