<?php
/**
 * Helper functions for Security Pack.
 *
 * @package Security_Pack
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Helper class with utility functions.
 */
class WPSP_Helper {

	/**
	 * Get the real client IP address.
	 *
	 * Handles proxies and CDNs like Cloudflare.
	 *
	 * @return string|null
	 */
	public static function get_client_ip() {
		$ip = null;

		// Priority order for IP detection.
		$headers = array(
			'HTTP_CF_CONNECTING_IP', // Cloudflare.
			'HTTP_X_REAL_IP',        // Nginx reverse proxy.
			'HTTP_X_FORWARDED_FOR',  // Generic proxy.
			'REMOTE_ADDR',           // Direct connection.
		);

		foreach ( $headers as $header ) {
			if ( ! empty( $_SERVER[ $header ] ) ) {
				// X-Forwarded-For can contain multiple IPs, get the first one.
				$ip = sanitize_text_field( wp_unslash( $_SERVER[ $header ] ) );
				if ( 'HTTP_X_FORWARDED_FOR' === $header && strpos( $ip, ',' ) !== false ) {
					$ips = explode( ',', $ip );
					$ip  = trim( $ips[0] );
				}
				break;
			}
		}

		// Validate IP.
		if ( $ip && filter_var( $ip, FILTER_VALIDATE_IP ) ) {
			return $ip;
		}

		return null;
	}

	/**
	 * Check if an IP is in a CIDR range.
	 *
	 * @param string $ip   IP address to check.
	 * @param string $cidr CIDR notation (e.g., 192.168.1.0/24).
	 * @return bool
	 */
	public static function ip_in_cidr( $ip, $cidr ) {
		// Handle exact IP match (no CIDR notation).
		if ( strpos( $cidr, '/' ) === false ) {
			return $ip === $cidr;
		}

		list( $network, $mask ) = explode( '/', $cidr );

		// Detect IP version.
		$ip_is_v6      = filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 );
		$network_is_v6 = filter_var( $network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 );

		// Both must be same version.
		if ( $ip_is_v6 !== $network_is_v6 ) {
			return false;
		}

		if ( $ip_is_v6 ) {
			return self::ipv6_in_cidr( $ip, $network, (int) $mask );
		}

		return self::ipv4_in_cidr( $ip, $network, (int) $mask );
	}

	/**
	 * Check if IPv4 is in CIDR range.
	 *
	 * @param string $ip      IPv4 address.
	 * @param string $network Network address.
	 * @param int    $mask    CIDR mask.
	 * @return bool
	 */
	private static function ipv4_in_cidr( $ip, $network, $mask ) {
		$ip_long      = ip2long( $ip );
		$network_long = ip2long( $network );

		if ( false === $ip_long || false === $network_long ) {
			return false;
		}

		// Calculate network mask.
		// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
		$network_mask = ~( ( 1 << ( 32 - $mask ) ) - 1 );

		return ( $ip_long & $network_mask ) === ( $network_long & $network_mask );
	}

	/**
	 * Check if IPv6 is in CIDR range.
	 *
	 * @param string $ip      IPv6 address.
	 * @param string $network Network address.
	 * @param int    $mask    CIDR mask.
	 * @return bool
	 */
	private static function ipv6_in_cidr( $ip, $network, $mask ) {
		$ip_bin      = inet_pton( $ip );
		$network_bin = inet_pton( $network );

		if ( false === $ip_bin || false === $network_bin ) {
			return false;
		}

		// Compare full bytes.
		$full_bytes = (int) floor( $mask / 8 );
		for ( $i = 0; $i < $full_bytes; $i++ ) {
			if ( $ip_bin[ $i ] !== $network_bin[ $i ] ) {
				return false;
			}
		}

		// Compare remaining bits.
		$remaining_bits = $mask % 8;
		if ( $remaining_bits > 0 && $full_bytes < 16 ) {
			$bit_mask = ( ( 1 << $remaining_bits ) - 1 ) << ( 8 - $remaining_bits );
			if ( ( ord( $ip_bin[ $full_bytes ] ) & $bit_mask ) !== ( ord( $network_bin[ $full_bytes ] ) & $bit_mask ) ) {
				return false;
			}
		}

		return true;
	}

	/**
	 * Check if an IP matches any rule in a list.
	 *
	 * @param string $ip    IP address to check.
	 * @param array  $rules Array of IP addresses or CIDR ranges.
	 * @return bool
	 */
	public static function ip_matches_rules( $ip, $rules ) {
		if ( empty( $rules ) || ! is_array( $rules ) ) {
			return false;
		}

		foreach ( $rules as $rule ) {
			$rule = trim( $rule );
			if ( empty( $rule ) || strpos( $rule, '#' ) === 0 ) {
				continue; // Skip empty lines and comments.
			}

			if ( self::ip_in_cidr( $ip, $rule ) ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Parse IP list from textarea.
	 *
	 * @param string $text Textarea content with IPs/CIDRs.
	 * @return array
	 */
	public static function parse_ip_list( $text ) {
		if ( empty( $text ) ) {
			return array();
		}

		$lines = explode( "\n", $text );
		$ips   = array();

		foreach ( $lines as $line ) {
			$line = trim( $line );

			// Skip empty lines and comments.
			if ( empty( $line ) || strpos( $line, '#' ) === 0 ) {
				continue;
			}

			// Remove inline comments.
			if ( strpos( $line, '#' ) !== false ) {
				$line = trim( substr( $line, 0, strpos( $line, '#' ) ) );
			}

			// Validate IP or CIDR.
			if ( self::is_valid_ip_or_cidr( $line ) ) {
				$ips[] = $line;
			}
		}

		return $ips;
	}

	/**
	 * Check if a string is a valid IP or CIDR.
	 *
	 * @param string $value Value to check.
	 * @return bool
	 */
	public static function is_valid_ip_or_cidr( $value ) {
		// Plain IP.
		if ( filter_var( $value, FILTER_VALIDATE_IP ) ) {
			return true;
		}

		// CIDR notation.
		if ( strpos( $value, '/' ) !== false ) {
			list( $ip, $mask ) = explode( '/', $value );

			if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
				return false;
			}

			$mask     = (int) $mask;
			$is_ipv6  = filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 );
			$max_mask = $is_ipv6 ? 128 : 32;

			return $mask >= 0 && $mask <= $max_mask;
		}

		return false;
	}

	/**
	 * Get country list for geo-blocking UI.
	 *
	 * @return array
	 */
	public static function get_countries() {
		return array(
			'AF' => __( 'Afghanistan', 'security-pack' ),
			'AL' => __( 'Albania', 'security-pack' ),
			'DZ' => __( 'Algeria', 'security-pack' ),
			'AS' => __( 'American Samoa', 'security-pack' ),
			'AD' => __( 'Andorra', 'security-pack' ),
			'AO' => __( 'Angola', 'security-pack' ),
			'AI' => __( 'Anguilla', 'security-pack' ),
			'AQ' => __( 'Antarctica', 'security-pack' ),
			'AG' => __( 'Antigua and Barbuda', 'security-pack' ),
			'AR' => __( 'Argentina', 'security-pack' ),
			'AM' => __( 'Armenia', 'security-pack' ),
			'AW' => __( 'Aruba', 'security-pack' ),
			'AU' => __( 'Australia', 'security-pack' ),
			'AT' => __( 'Austria', 'security-pack' ),
			'AZ' => __( 'Azerbaijan', 'security-pack' ),
			'BS' => __( 'Bahamas', 'security-pack' ),
			'BH' => __( 'Bahrain', 'security-pack' ),
			'BD' => __( 'Bangladesh', 'security-pack' ),
			'BB' => __( 'Barbados', 'security-pack' ),
			'BY' => __( 'Belarus', 'security-pack' ),
			'BE' => __( 'Belgium', 'security-pack' ),
			'BZ' => __( 'Belize', 'security-pack' ),
			'BJ' => __( 'Benin', 'security-pack' ),
			'BM' => __( 'Bermuda', 'security-pack' ),
			'BT' => __( 'Bhutan', 'security-pack' ),
			'BO' => __( 'Bolivia', 'security-pack' ),
			'BA' => __( 'Bosnia and Herzegovina', 'security-pack' ),
			'BW' => __( 'Botswana', 'security-pack' ),
			'BR' => __( 'Brazil', 'security-pack' ),
			'BN' => __( 'Brunei', 'security-pack' ),
			'BG' => __( 'Bulgaria', 'security-pack' ),
			'BF' => __( 'Burkina Faso', 'security-pack' ),
			'BI' => __( 'Burundi', 'security-pack' ),
			'KH' => __( 'Cambodia', 'security-pack' ),
			'CM' => __( 'Cameroon', 'security-pack' ),
			'CA' => __( 'Canada', 'security-pack' ),
			'CV' => __( 'Cape Verde', 'security-pack' ),
			'KY' => __( 'Cayman Islands', 'security-pack' ),
			'CF' => __( 'Central African Republic', 'security-pack' ),
			'TD' => __( 'Chad', 'security-pack' ),
			'CL' => __( 'Chile', 'security-pack' ),
			'CN' => __( 'China', 'security-pack' ),
			'CO' => __( 'Colombia', 'security-pack' ),
			'KM' => __( 'Comoros', 'security-pack' ),
			'CG' => __( 'Congo', 'security-pack' ),
			'CD' => __( 'Congo (DRC)', 'security-pack' ),
			'CR' => __( 'Costa Rica', 'security-pack' ),
			'CI' => __( 'Ivory Coast', 'security-pack' ),
			'HR' => __( 'Croatia', 'security-pack' ),
			'CU' => __( 'Cuba', 'security-pack' ),
			'CY' => __( 'Cyprus', 'security-pack' ),
			'CZ' => __( 'Czech Republic', 'security-pack' ),
			'DK' => __( 'Denmark', 'security-pack' ),
			'DJ' => __( 'Djibouti', 'security-pack' ),
			'DM' => __( 'Dominica', 'security-pack' ),
			'DO' => __( 'Dominican Republic', 'security-pack' ),
			'EC' => __( 'Ecuador', 'security-pack' ),
			'EG' => __( 'Egypt', 'security-pack' ),
			'SV' => __( 'El Salvador', 'security-pack' ),
			'GQ' => __( 'Equatorial Guinea', 'security-pack' ),
			'ER' => __( 'Eritrea', 'security-pack' ),
			'EE' => __( 'Estonia', 'security-pack' ),
			'ET' => __( 'Ethiopia', 'security-pack' ),
			'FJ' => __( 'Fiji', 'security-pack' ),
			'FI' => __( 'Finland', 'security-pack' ),
			'FR' => __( 'France', 'security-pack' ),
			'GA' => __( 'Gabon', 'security-pack' ),
			'GM' => __( 'Gambia', 'security-pack' ),
			'GE' => __( 'Georgia', 'security-pack' ),
			'DE' => __( 'Germany', 'security-pack' ),
			'GH' => __( 'Ghana', 'security-pack' ),
			'GR' => __( 'Greece', 'security-pack' ),
			'GL' => __( 'Greenland', 'security-pack' ),
			'GD' => __( 'Grenada', 'security-pack' ),
			'GU' => __( 'Guam', 'security-pack' ),
			'GT' => __( 'Guatemala', 'security-pack' ),
			'GN' => __( 'Guinea', 'security-pack' ),
			'GW' => __( 'Guinea-Bissau', 'security-pack' ),
			'GY' => __( 'Guyana', 'security-pack' ),
			'HT' => __( 'Haiti', 'security-pack' ),
			'HN' => __( 'Honduras', 'security-pack' ),
			'HK' => __( 'Hong Kong', 'security-pack' ),
			'HU' => __( 'Hungary', 'security-pack' ),
			'IS' => __( 'Iceland', 'security-pack' ),
			'IN' => __( 'India', 'security-pack' ),
			'ID' => __( 'Indonesia', 'security-pack' ),
			'IR' => __( 'Iran', 'security-pack' ),
			'IQ' => __( 'Iraq', 'security-pack' ),
			'IE' => __( 'Ireland', 'security-pack' ),
			'IL' => __( 'Israel', 'security-pack' ),
			'IT' => __( 'Italy', 'security-pack' ),
			'JM' => __( 'Jamaica', 'security-pack' ),
			'JP' => __( 'Japan', 'security-pack' ),
			'JO' => __( 'Jordan', 'security-pack' ),
			'KZ' => __( 'Kazakhstan', 'security-pack' ),
			'KE' => __( 'Kenya', 'security-pack' ),
			'KI' => __( 'Kiribati', 'security-pack' ),
			'KP' => __( 'North Korea', 'security-pack' ),
			'KR' => __( 'South Korea', 'security-pack' ),
			'KW' => __( 'Kuwait', 'security-pack' ),
			'KG' => __( 'Kyrgyzstan', 'security-pack' ),
			'LA' => __( 'Laos', 'security-pack' ),
			'LV' => __( 'Latvia', 'security-pack' ),
			'LB' => __( 'Lebanon', 'security-pack' ),
			'LS' => __( 'Lesotho', 'security-pack' ),
			'LR' => __( 'Liberia', 'security-pack' ),
			'LY' => __( 'Libya', 'security-pack' ),
			'LI' => __( 'Liechtenstein', 'security-pack' ),
			'LT' => __( 'Lithuania', 'security-pack' ),
			'LU' => __( 'Luxembourg', 'security-pack' ),
			'MO' => __( 'Macao', 'security-pack' ),
			'MK' => __( 'North Macedonia', 'security-pack' ),
			'MG' => __( 'Madagascar', 'security-pack' ),
			'MW' => __( 'Malawi', 'security-pack' ),
			'MY' => __( 'Malaysia', 'security-pack' ),
			'MV' => __( 'Maldives', 'security-pack' ),
			'ML' => __( 'Mali', 'security-pack' ),
			'MT' => __( 'Malta', 'security-pack' ),
			'MH' => __( 'Marshall Islands', 'security-pack' ),
			'MR' => __( 'Mauritania', 'security-pack' ),
			'MU' => __( 'Mauritius', 'security-pack' ),
			'MX' => __( 'Mexico', 'security-pack' ),
			'FM' => __( 'Micronesia', 'security-pack' ),
			'MD' => __( 'Moldova', 'security-pack' ),
			'MC' => __( 'Monaco', 'security-pack' ),
			'MN' => __( 'Mongolia', 'security-pack' ),
			'ME' => __( 'Montenegro', 'security-pack' ),
			'MA' => __( 'Morocco', 'security-pack' ),
			'MZ' => __( 'Mozambique', 'security-pack' ),
			'MM' => __( 'Myanmar', 'security-pack' ),
			'NA' => __( 'Namibia', 'security-pack' ),
			'NR' => __( 'Nauru', 'security-pack' ),
			'NP' => __( 'Nepal', 'security-pack' ),
			'NL' => __( 'Netherlands', 'security-pack' ),
			'NZ' => __( 'New Zealand', 'security-pack' ),
			'NI' => __( 'Nicaragua', 'security-pack' ),
			'NE' => __( 'Niger', 'security-pack' ),
			'NG' => __( 'Nigeria', 'security-pack' ),
			'NO' => __( 'Norway', 'security-pack' ),
			'OM' => __( 'Oman', 'security-pack' ),
			'PK' => __( 'Pakistan', 'security-pack' ),
			'PW' => __( 'Palau', 'security-pack' ),
			'PS' => __( 'Palestine', 'security-pack' ),
			'PA' => __( 'Panama', 'security-pack' ),
			'PG' => __( 'Papua New Guinea', 'security-pack' ),
			'PY' => __( 'Paraguay', 'security-pack' ),
			'PE' => __( 'Peru', 'security-pack' ),
			'PH' => __( 'Philippines', 'security-pack' ),
			'PL' => __( 'Poland', 'security-pack' ),
			'PT' => __( 'Portugal', 'security-pack' ),
			'PR' => __( 'Puerto Rico', 'security-pack' ),
			'QA' => __( 'Qatar', 'security-pack' ),
			'RO' => __( 'Romania', 'security-pack' ),
			'RU' => __( 'Russia', 'security-pack' ),
			'RW' => __( 'Rwanda', 'security-pack' ),
			'SA' => __( 'Saudi Arabia', 'security-pack' ),
			'SN' => __( 'Senegal', 'security-pack' ),
			'RS' => __( 'Serbia', 'security-pack' ),
			'SC' => __( 'Seychelles', 'security-pack' ),
			'SL' => __( 'Sierra Leone', 'security-pack' ),
			'SG' => __( 'Singapore', 'security-pack' ),
			'SK' => __( 'Slovakia', 'security-pack' ),
			'SI' => __( 'Slovenia', 'security-pack' ),
			'SB' => __( 'Solomon Islands', 'security-pack' ),
			'SO' => __( 'Somalia', 'security-pack' ),
			'ZA' => __( 'South Africa', 'security-pack' ),
			'SS' => __( 'South Sudan', 'security-pack' ),
			'ES' => __( 'Spain', 'security-pack' ),
			'LK' => __( 'Sri Lanka', 'security-pack' ),
			'SD' => __( 'Sudan', 'security-pack' ),
			'SR' => __( 'Suriname', 'security-pack' ),
			'SZ' => __( 'Eswatini', 'security-pack' ),
			'SE' => __( 'Sweden', 'security-pack' ),
			'CH' => __( 'Switzerland', 'security-pack' ),
			'SY' => __( 'Syria', 'security-pack' ),
			'TW' => __( 'Taiwan', 'security-pack' ),
			'TJ' => __( 'Tajikistan', 'security-pack' ),
			'TZ' => __( 'Tanzania', 'security-pack' ),
			'TH' => __( 'Thailand', 'security-pack' ),
			'TL' => __( 'Timor-Leste', 'security-pack' ),
			'TG' => __( 'Togo', 'security-pack' ),
			'TO' => __( 'Tonga', 'security-pack' ),
			'TT' => __( 'Trinidad and Tobago', 'security-pack' ),
			'TN' => __( 'Tunisia', 'security-pack' ),
			'TR' => __( 'Turkey', 'security-pack' ),
			'TM' => __( 'Turkmenistan', 'security-pack' ),
			'TV' => __( 'Tuvalu', 'security-pack' ),
			'UG' => __( 'Uganda', 'security-pack' ),
			'UA' => __( 'Ukraine', 'security-pack' ),
			'AE' => __( 'United Arab Emirates', 'security-pack' ),
			'GB' => __( 'United Kingdom', 'security-pack' ),
			'US' => __( 'United States', 'security-pack' ),
			'UY' => __( 'Uruguay', 'security-pack' ),
			'UZ' => __( 'Uzbekistan', 'security-pack' ),
			'VU' => __( 'Vanuatu', 'security-pack' ),
			'VE' => __( 'Venezuela', 'security-pack' ),
			'VN' => __( 'Vietnam', 'security-pack' ),
			'YE' => __( 'Yemen', 'security-pack' ),
			'ZM' => __( 'Zambia', 'security-pack' ),
			'ZW' => __( 'Zimbabwe', 'security-pack' ),
		);
	}

	/**
	 * Sanitize a custom login URL slug.
	 *
	 * @param string $slug The slug to sanitize.
	 * @return string
	 */
	public static function sanitize_login_slug( $slug ) {
		$slug = sanitize_title( $slug );
		$slug = preg_replace( '/[^a-z0-9\-]/', '', $slug );

		// Prevent common reserved slugs.
		$reserved = array( 'wp-admin', 'wp-login', 'admin', 'login', 'wp-content', 'wp-includes' );
		if ( in_array( $slug, $reserved, true ) ) {
			return '';
		}

		return $slug;
	}

	/**
	 * Get the server's public IP address.
	 *
	 * Uses external service to determine the server's outbound IP.
	 * Result is cached for 1 hour to avoid excessive external requests.
	 *
	 * @return string|null Server IP or null on failure.
	 */
	public static function get_server_ip() {
		$cached = get_transient( 'wpsp_server_ip' );
		if ( false !== $cached ) {
			return $cached;
		}

		// Try multiple services for reliability.
		$services = array(
			'https://api.ipify.org',
			'https://ifconfig.me/ip',
			'https://icanhazip.com',
		);

		$ip = null;

		foreach ( $services as $service ) {
			$response = wp_remote_get(
				$service,
				array(
					'timeout'   => 5,
					'sslverify' => true,
				)
			);

			if ( ! is_wp_error( $response ) && 200 === wp_remote_retrieve_response_code( $response ) ) {
				$body = trim( wp_remote_retrieve_body( $response ) );
				if ( filter_var( $body, FILTER_VALIDATE_IP ) ) {
					$ip = $body;
					break;
				}
			}
		}

		if ( $ip ) {
			// Cache for 1 hour.
			set_transient( 'wpsp_server_ip', $ip, HOUR_IN_SECONDS );
		}

		return $ip;
	}

	/**
	 * Get country flag emoji from country code.
	 *
	 * Converts ISO 3166-1 alpha-2 country codes to Unicode flag emojis.
	 *
	 * @param string $country_code Two-letter country code (e.g., "US", "GB").
	 * @return string Flag emoji or globe emoji for invalid codes.
	 */
	public static function get_country_flag( $country_code ) {
		if ( empty( $country_code ) || strlen( $country_code ) !== 2 ) {
			return '🌐'; // Globe emoji for invalid codes.
		}

		$country_code = strtoupper( $country_code );

		// Convert country code to Unicode regional indicator symbols.
		// Regional indicators are U+1F1E6 (A) through U+1F1FF (Z).
		$first_letter  = mb_chr( ord( $country_code[0] ) - ord( 'A' ) + 0x1F1E6, 'UTF-8' );
		$second_letter = mb_chr( ord( $country_code[1] ) - ord( 'A' ) + 0x1F1E6, 'UTF-8' );

		return $first_letter . $second_letter;
	}

	/**
	 * Get countries array with flags.
	 *
	 * @return array Country code => "Flag Name" format.
	 */
	public static function get_countries_with_flags() {
		$countries      = self::get_countries();
		$countries_flags = array();

		foreach ( $countries as $code => $name ) {
			$flag                    = self::get_country_flag( $code );
			$countries_flags[ $code ] = $flag . ' ' . $name;
		}

		return $countries_flags;
	}
}
