<?php

namespace RtmMail\Utils;

class LoggerUtils {
	/**
	 * Returns astrisked password if it exists in a array
	 *
	 * @param array $arr
	 *
	 * @return array
	 */
	private static function filterPasswords( array $arr ): array {
		return array_column( array_map( function ( $k, $v ): mixed {
			if ( is_array( $v ) ) {
				$v = self::filterPasswords( $v );
			}

			return str_contains( $k, "password" ) || $k === "pass1" || $k === "pass2" ?
				[ $k, "********" ] : [ $k, $v ];
		}, array_keys( $arr ), $arr ), 1, 0 );
	}

	/**
	 * Filters out specific things for a request before logging
	 *
	 * @param array $request
	 *
	 * @return array
	 */
	public static function filterRequest( $request ): array {
		// Filter out passwords
		$request["HEADERS"] = self::filterPasswords( $request["HEADERS"] );
		$request["POST"]    = self::filterPasswords( $request["POST"] );
		$request["GET"]     = self::filterPasswords( $request["GET"] );

		return $request;
	}

	/**
	 * Returns the userdata of the current user or the ip address
	 * @return array
	 */
	public static function getUser() {
		if ( is_user_logged_in() ) {
			$user = wp_get_current_user();

			return $user->display_name . ' (ID: ' . $user->ID . ')';
		} else {
			$source = $_SERVER['REMOTE_ADDR'];
			if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
				$source = $_SERVER['HTTP_CLIENT_IP'];
			} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
				$source = $_SERVER['HTTP_X_FORWARDED_FOR'];
			}

			return $source;
		}
	}
}
