<?php
/**
 * Logs PeachPay-related PHP fatals locally when WP_DEBUG is enabled.
 *
 * @package PeachPay
 */

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

register_shutdown_function( 'peachpay_notify_error' );

/**
 * Maps integer error code to an error code constant.
 *
 * @param int $err_code PHP Error Code.
 */
function peachpay_error_mapping( $err_code ) {
	switch ( $err_code ) {
		case 1:
			return 'E_ERROR';
		default:
			return 'UNK';
	}
}

/**
 * Logs PeachPay errors locally when WP_DEBUG is enabled.
 *
 * @param Exception|null $error Optional exception to log. If null, uses error_get_last().
 */
function peachpay_notify_error( $error = null ) {
	if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) {
		return;
	}

	try {
		if ( $error ) {
			$error = array(
				'type'    => get_class( $error ),
				'message' => $error->getMessage(),
				'file'    => $error->getFile(),
				'line'    => $error->getLine(),
			);
		} else {
			$error = error_get_last();
		}

		if ( null !== $error && ( 1 === $error['type'] || is_string( $error['type'] ) ) ) {
			$body = array(
				'host'                     => site_url(),
				'error_type'               => is_string( $error['type'] ) ? $error['type'] : peachpay_error_mapping( $error['type'] ),
				'error_message'            => $error['message'],
				'error_file'               => $error['file'],
				'error_line'               => $error['line'],
				'error_uri'                => isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : 'N/A',
				'pp_version'               => defined( 'PEACHPAY_VERSION' ) ? PEACHPAY_VERSION : 'unknown',
				'test_mode'                => peachpay_get_settings_option( 'peachpay_payment_options', 'test_mode', false ),
				'php_version'              => phpversion(),
				'wp_version'               => get_bloginfo( 'version' ),
				'woocommerce_class_exists' => class_exists( 'WooCommerce' ),
			);

			// Always log to PHP debug log when WP_DEBUG is on (no extra settings).
			error_log( '[PeachPay Error] ' . wp_json_encode( $body ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log

			// Also send to WooCommerce logs when Advanced Logging is enabled (peachpay_log no-ops otherwise).
			if ( function_exists( 'peachpay_log' ) ) {
				peachpay_log(
					'error',
					'PeachPay Error: ' . wp_json_encode( $body ),
					array(
						'line'    => $error['line'],
						'file'    => $error['file'],
						'message' => $error['message'],
						'type'    => $error['type'],
						'uri'     => isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : 'N/A',
						'version' => defined( 'PEACHPAY_VERSION' ) ? PEACHPAY_VERSION : 'unknown',
					)
				);
			}
		}
	} catch ( Exception $ex ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
		// Fail silently.
	}
}
