<?php

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

class WpironHelper {

	const APACHE = 1;
	const NGINX = 2;

	public function wpironis_getOption( $type, $value = null ) {
		$options = get_option( $type, array() );
		if ( isset( $value ) ) {
			return isset( $options[ $value ] ) ? $options[ $value ] : null;
		}
		return $options;
	}

	public function wpironis_detect_web_server() {
		if ( isset( $_SERVER['SERVER_SOFTWARE'] ) ) {
			$server_software = strtolower( $_SERVER['SERVER_SOFTWARE'] );

			if ( str_contains( $server_software, 'apache' ) ) {
				return self::APACHE;
			}

			if ( str_contains( $server_software, 'nginx' ) ) {
				return self::NGINX;
			}
		}

		return 'unknown';
	}

	public function wpironis_table_exists() {
		global $wpdb;
		$table = $wpdb->prefix . 'iron_security_logs';
		return $wpdb->get_var("SHOW TABLES LIKE '$table'") === $table;
	}

	public function wpironis_updateOption( $type, $data ) {
		error_log(print_r( $data, true ));
		$optionsUpdates = update_option( $type, $data );
		return $optionsUpdates;
	}

	public function get_user_ip() {
		$remote_addr     = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( $_SERVER['REMOTE_ADDR'] ) : '0.0.0.0';
		$trusted_proxies = apply_filters( 'iron_security_trusted_proxies', [
			'173.245.48.0/20',
			'103.21.244.0/22',
			'103.22.200.0/22',
			'103.31.4.0/22',
			'141.101.64.0/18',
			'108.162.192.0/18',
			'190.93.240.0/20',
			'188.114.96.0/20',
			'197.234.240.0/22',
			'198.41.128.0/17',
			'162.158.0.0/15',
			'104.16.0.0/13',
			'104.24.0.0/14',
			'172.64.0.0/13',
			'131.0.72.0/22',
		] );

		$is_trusted_proxy = $this->ip_in_trusted_range( $remote_addr, $trusted_proxies );

		if ( $is_trusted_proxy && ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
			$forwarded_ips       = array_map( 'trim',
				explode( ',', sanitize_text_field( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) );
			$client_ip_candidate = reset( $forwarded_ips );
			if ( filter_var( $client_ip_candidate, FILTER_VALIDATE_IP ) ) {
				return $client_ip_candidate;
			}
		}

		return $remote_addr;
	}

	private function ip_in_trusted_range( $ip, $ranges ) {
		if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
			return false;
		}

		foreach ( $ranges as $range ) {
			if ( str_contains( $range, '/' ) ) {
				list( $subnet, $mask ) = explode( '/', $range );

				$ip_long     = ip2long( $ip );
				$subnet_long = ip2long( $subnet );

				$mask_bits = 0xffffffff << ( 32 - intval( $mask ) );
				$mask_ip   = $ip_long & $mask_bits;

				if ( $mask_ip === ( $subnet_long & $mask_bits ) ) {
					return true;
				}
			} else {
				if ( $ip === $range ) {
					return true;
				}
			}
		}

		return false;
	}

}