<?php
/**
 * A class of utilities for dealing with plugin-related methods.
 *
 * @since 3.0.0
 */

declare(strict_types=1);
namespace FeData\FastEvents\Utilities;

/**
 * A class of utilities for dealing with plugin-related methods.
 */
class PluginUtil {


	/**
	 * Get the home domain.
	 *
	 * @since 1.0
	 *
	 * @return string
	 */
	public static function get_home_domain(): string {
		return str_replace( 'http://', '', str_replace( 'https://', '', home_url() ) );
	}


	/**
	 * Get the signature for tracking qrcodes.
	 *
	 * @since 1.0
	 *
	 * @param string $qrcode    The 16 bytes long qrcode.
	 * @param int    $qrcode_id The unique id of the qrcode.
	 *
	 * @return string
	 */
	public static function get_qrcode_signature( string $qrcode, int $qrcode_id ): string {
		return substr( wp_hash( $qrcode . ':' . $qrcode_id . ':' . self::get_home_domain(), 'nonce' ), 0, 16 );
	}


	/**
	 * Get the plugin url.
	 *
	 * @since 1.0
	 *
	 * @return string
	 */
	public static function plugin_url(): string {
		return untrailingslashit( plugins_url( '/', FAST_EVENTS_PLUGIN_FILE ) );
	}


	/**
	 * Get the plugin path.
	 *
	 * @since 1.0
	 *
	 * @return string
	 */
	public static function plugin_path(): string {
		return untrailingslashit( plugin_dir_path( FAST_EVENTS_PLUGIN_FILE ) );
	}


	/**
	 * Return User-Agent string for REST-API calls.
	 *
	 * @since 2.4.0
	 *
	 * @return string
	 */
	public static function get_user_agent(): string {
		global $wp_version;

		return 'Fast-Events-plugin/' . $GLOBALS['fast_events']::FAST_EVENTS_VERSION . ' WordPress/' . $wp_version . ' PHP/' . phpversion();
	}

	/**
	 * Get the clients ip address
	 *
	 * @return string
	 * @since 1.0
	 */
	public static function get_ip(): string {
		foreach ( array( 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR' ) as $key ) {
			if ( true === array_key_exists( $key, $_SERVER ) ) {
				foreach ( array_map( 'trim', explode( ',', sanitize_text_field( wp_unslash( $_SERVER[ $key ] ) ) ) ) as $ip ) {
					if ( false !== filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6 ) ) {
						return substr( $ip, 0, 45 );
					}
				}
			}
		}
		return '0.0.0.0'; // No ipaddress found.
	}
}
