<?php
namespace DigitalApps\PaymentsForAdyen;

defined('ABSPATH') || exit;

/**
 * WooCommerce logger adapter for Digital Apps Payments for Adyen.
 */
class Logger
{
	const SOURCE = 'digital-apps-payments-for-adyen';

	/**
	 * Write a log entry through WooCommerce's logger and retention controls.
	 *
	 * @param string $level   Log level (ERROR, WARNING, INFO).
	 * @param array  $context Context data.
	 */
	public function log($level, array $context = [])
	{
		if (!function_exists('wc_get_logger')) {
			return;
		}

		$level = strtolower((string) $level);
		$allowed_levels = ['emergency', 'alert', 'critical', 'error', 'warning', 'notice', 'info', 'debug'];
		if (!in_array($level, $allowed_levels, true)) {
			$level = 'info';
		}

		$settings = get_option(Settings_Store::OPTION_NAME, []);
		if ('debug' === $level && empty($settings['debugLogging'])) {
			return;
		}

		$redacted = $this->redact($context);
		$message = isset($redacted['message']) ? (string) $redacted['message'] : __('Adyen plugin event', 'digital-apps-payments-for-adyen');
		unset($redacted['message']);
		if (!empty($redacted)) {
			$message .= ' ' . wp_json_encode($redacted);
		}

		wc_get_logger()->log($level, $message, ['source' => self::SOURCE]);
	}

	/**
	 * Legacy compatibility method. Logs are now viewed in WooCommerce.
	 *
	 * @param int $limit Number of entries.
	 * @return array
	 */
	public function get_logs($limit = 100)
	{
		unset($limit);
		return [];
	}

	/**
	 * Legacy compatibility method. Log deletion is managed by WooCommerce.
	 */
	public function clear_logs()
	{
		return;
	}

	/**
	 * Recursively redact credentials, payment state, and customer data.
	 *
	 * @param mixed  $value Context value.
	 * @param string $key Context key.
	 * @return mixed
	 */
	private function redact($value, $key = '')
	{
		if ($this->is_sensitive_key($key)) {
			return '[redacted]';
		}

		if (!is_array($value)) {
			return $value;
		}

		$redacted = [];
		foreach ($value as $child_key => $child_value) {
			$redacted[$child_key] = $this->redact($child_value, (string) $child_key);
		}

		return $redacted;
	}

	/**
	 * Determine whether a context key can contain sensitive data.
	 *
	 * @param string $key Context key.
	 * @return bool
	 */
	private function is_sensitive_key($key)
	{
		$normalized = strtolower((string) preg_replace('/[^a-z0-9]/i', '', $key));
		if (in_array($normalized, ['body', 'email', 'key'], true)) {
			return true;
		}

		$sensitive_fragments = [
			'action',
			'apikey',
			'authorization',
			'billing',
			'details',
			'hmac',
			'licensekey',
			'password',
			'paymentdata',
			'paymentmethod',
			'rawresponse',
			'responsebody',
			'sessiondata',
			'sessionkey',
			'shipping',
			'shopperip',
			'token',
		];

		foreach ($sensitive_fragments as $fragment) {
			if (false !== strpos($normalized, $fragment)) {
				return true;
			}
		}

		return false;
	}
}
