<?php
/**
 * PeachPay Advanced Logging.
 *
 * Central logging helper with static cache for zero overhead when disabled.
 * Logs to WooCommerce logger (source: peachpay).
 *
 * @package PeachPay
 */

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

/**
 * Valid log levels in order of severity (least to most severe).
 * Higher index = more severe. We log when message severity >= configured min.
 *
 * @var array<string>
 */
const PEACHPAY_LOG_LEVELS = array( 'debug', 'info', 'warning', 'error' );

/**
 * Checks if advanced logging is enabled (cached per request).
 *
 * @return bool True if enabled.
 */
function peachpay_is_advanced_logging_enabled() {
	static $enabled = null;

	if ( $enabled === null ) {
		$options = get_option( 'peachpay_advanced_logging', array() );
		$enabled = ! empty( $options['enable_logging'] ) && $options['enable_logging'] === 'yes';
	}

	return $enabled;
}

/**
 * Gets the minimum log level (cached per request).
 *
 * @return string One of: debug, info, warning, error.
 */
function peachpay_get_log_level() {
	static $level = null;

	if ( $level === null ) {
		$options = get_option( 'peachpay_advanced_logging', array() );
		$raw    = isset( $options['log_level'] ) ? $options['log_level'] : 'info';
		$level  = in_array( $raw, PEACHPAY_LOG_LEVELS, true ) ? $raw : 'info';
	}

	return $level;
}

/**
 * Checks if a given level should be logged based on the configured minimum level.
 *
 * E.g. min=info logs info, warning, error. min=error logs only error.
 *
 * @param string $min_level Configured minimum level (e.g. 'info').
 * @param string $level     Level of the message (e.g. 'debug').
 * @return bool True if the message should be logged.
 */
function peachpay_log_level_allows( $min_level, $level ) {
	$min_idx = array_search( $min_level, PEACHPAY_LOG_LEVELS, true );
	$idx     = array_search( $level, PEACHPAY_LOG_LEVELS, true );

	if ( $min_idx === false || $idx === false ) {
		return false;
	}

	// Higher index = more severe. Log when message severity >= min (idx >= min_idx).
	return $idx >= $min_idx;
}

/**
 * Logs a message to WooCommerce logs when advanced logging is enabled.
 *
 * Fast path when disabled: single static check, immediate return. No DB, no logger, no I/O.
 *
 * @param string $level   One of: debug, info, warning, error.
 * @param string $message Log message.
 * @param array  $context Optional context (unused for now; WC logger uses source).
 * @return void
 */
function peachpay_log( $level, $message, $context = array() ) {
	if ( ! peachpay_is_advanced_logging_enabled() ) {
		return;
	}

	$min_level = peachpay_get_log_level();
	if ( ! peachpay_log_level_allows( $min_level, $level ) ) {
		return;
	}

	if ( ! function_exists( 'wc_get_logger' ) ) {
		error_log( '[PeachPay ' . strtoupper( $level ) . '] ' . $message );
		return;
	}

	$logger = wc_get_logger();
	$logger->log( $level, $message, array_merge( array( 'source' => 'peachpay' ), $context ) );
}
