<?php

add_action( 'redux/options/jobster_settings/saved', 'maybe_wpj_fetch_exchange_rates' );
function maybe_wpj_fetch_exchange_rates( $options ) {
	if ( is_admin() && $options['wpjobster_enable_open_exchange_api_rate'] == '1' ) {
		if ( ! wpj_get_option( 'exchange_rates' ) ) {
			wpj_fetch_exchange_rates();
		}
	}
}

if ( ! function_exists( 'wpj_fetch_exchange_rates' ) ) {
	function wpj_fetch_exchange_rates() {
		// Get current exchange rates
		$current_json = get_option( 'exchange_rates' );
		$current_json_decoded = wpj_json_decode( $current_json, true );

		// Get API ID
		$appid = wpj_get_option( 'openexchangerates_appid' );

		// If no API KEY, do it weekly
		if ( ! $appid
		     && isset( $current_json_decoded['timestamp'] )
		     && time() - $current_json_decoded['timestamp'] < 604800
		) {
			return false;
		}

		// Add fallback API KEY
		if ( ! $appid ) $appid = 'c9cee23bf1094de1a34b46ead5c9d02d';

		// Call the API
		$file = 'latest.json';

		$ch = curl_init( "http://openexchangerates.org/api/{$file}?app_id={$appid}&show_alternative=1" );

		curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );

		$json_received = curl_exec( $ch );

		curl_close( $ch );

		$json_received_decoded = wpj_json_decode( $json_received, true );

		// Send email empty response
		if ( empty( $json_received_decoded['rates'] ) ) {
			wpj_notify_user_translated( 'admin_openexchangerates_not_responding', 'admin' );

			return false;
		}

		// Get exchange difference
		$percent = wpj_get_option( 'wpjobster_exchange_drop_percent' );

		if ( ! $percent || ! is_numeric( $percent ) ) { $percent = 5; }

		$exchange_differences = [];

		if ( $current_json_decoded ) {
			global $wpjobster_currencies_array;

			if ( $wpjobster_currencies_array ) {
				foreach ( $wpjobster_currencies_array as $ex_c ) {
					if ( ! empty( $json_received_decoded['rates'][$ex_c] ) && ! empty( $current_json_decoded['rates'][$ex_c] ) ) {
						if ( abs( ( ( $json_received_decoded['rates'][$ex_c] / $current_json_decoded['rates'][$ex_c] ) - 1 ) * 100 ) > $percent ) {
							array_push( $exchange_differences, $ex_c );
						}
					}
				}
			}
		}

		// Send exchange difference email
		if ( ! empty( $exchange_differences ) ) {
			$params = [];

			foreach ( $exchange_differences as $ex_d ) {
				$params[] = [
					'##main_currency##'      => $ex_d,
					'##old_price##'          => $current_json_decoded['rates'][$ex_d],
					'##new_price##'          => $json_received_decoded['rates'][$ex_d],
					'##percent_difference##' => abs( ( ( $json_received_decoded['rates'][$ex_d] / $current_json_decoded['rates'][$ex_d] ) - 1 ) * 100 )
				];
			}

			wpj_notify_user_translated( 'admin_openexchangerates_higher', 'admin', '', $params );

			return false;
		}

		// Update exchange with received json
		update_option( 'exchange_rates', $json_received );
	}
}

if ( ! function_exists( 'wpj_get_site_currency' ) ) {
	function wpj_get_site_currency() {
		global $wpjobster_currencies_array;

		$currencies = $wpjobster_currencies_array;

		if ( isset( $_GET['site_currency'] ) ) {
			$currency_get = strtoupper( $_GET['site_currency'] );

			if ( in_array( $currency_get, $currencies ) ) {
				return $currency_get;
			}
		}

		elseif ( isset( $_POST['site_currency'] ) ) {
			$currency_post = strtoupper( $_POST['site_currency'] );

			if ( in_array( $currency_post, $currencies ) ) {
				return $currency_post;
			}
		}

		elseif ( isset( $_COOKIE['site_currency'] ) ) {
			$currency_cookie = strtoupper( $_COOKIE["site_currency"] );

			if ( in_array( $currency_cookie, $currencies ) ) {
				return $currency_cookie;
			}
		}

		return isset( $currencies[0] ) ? $currencies[0] : 'USD';
	}
}

if ( ! function_exists( 'wpj_get_site_default_currency' ) ) {
	function wpj_get_site_default_currency() {
		$currencies = wpj_get_option( 'add-new-currency' );

		return ! empty( $currencies['currency_name'][0] ) ? trim( $currencies['currency_name'][0] ) : 'USD';
	}
}

if ( ! function_exists( 'wpj_get_currency_symbol_by_name' ) ) {
	function wpj_get_currency_symbol_by_name( $currency_iso ) {
		global $wpjobster_currencies_array;
		global $wpjobster_currencies_symbols_array;

		if ( $wpjobster_currencies_array ) {
			if ( in_array( $currency_iso, $wpjobster_currencies_array ) ) {
				return $wpjobster_currencies_symbols_array[$currency_iso];
			}
		}

		return $currency_iso;
	}
}

if ( ! function_exists( 'wpj_get_exchanged_value' ) ) {
	function wpj_get_exchanged_value( $amount, $from, $to ) {
		$amount = preg_replace( '/[^0-9.-]+/', '', $amount );
		$amount = floatval( $amount );

		$from = strtoupper( $from );
		$to   = strtoupper( $to );

		$from = trim( $from );
		$to   = trim( $to );

		$json          = wpj_get_option( 'exchange_rates' );
		$exchangeRates = wpj_json_decode( $json );

		$rate = isset ( $exchangeRates->rates->$from ) ? floatval( $exchangeRates->rates->$from ) : '';

		if ( ! $rate && strtoupper( $from ) == 'USD' ) { $rate = 1; }

		if ( $json = null ) {
			exit( 'Currency exchange error. Please contact the administrators.' );

		} elseif ( ! $rate ) {
			return $amount;

		} elseif ( $from == $to ) {
			return $amount;

		} else {
			if ( $from != 'USD' ) {
				$dollars = $amount / $rate;

			} else {
				$dollars = $amount;

			}

			if ( $to != 'USD' && isset( $exchangeRates->rates->$to ) ) {
				$return = round( $exchangeRates->rates->$to * $dollars, 2 );

			} else {
				$return = round( $dollars, 2 );

			}

			return $return;
		}
	}
}

if ( ! function_exists( 'wpj_get_currencies_list' ) ) {
	function wpj_get_currencies_list() {
		$arr_currency = [
			''    => '-',
			'USD' => 'United States Dollar (USD)',
			'EUR' => 'Euro (EUR)',
			'JPY' => 'Japanese Yen (JPY)',
			'GBP' => 'British Pound Sterling (GBP)',
			'AUD' => 'Australian Dollar (AUD)',
			'CHF' => 'Swiss Franc (CHF)',
			'CAD' => 'Canadian Dollar (CAD)',
			'AED' => 'United Arab Emirates Dirham (AED)',
			'AFN' => 'Afghan Afghani (AFN)',
			'ALL' => 'Albanian Lek (ALL)',
			'AMD' => 'Armenian Dram (AMD)',
			'ANG' => 'Netherlands Antillean Guilder (ANG)',
			'AOA' => 'Angolan Kwanza (AOA)',
			'ARS' => 'Argentine Peso (ARS)',
			'AWG' => 'Aruban Florin (AWG)',
			'AZN' => 'Azerbaijani Manat (AZN)',
			'BAM' => 'Bosnia-Herzegovina Convertible Mark (BAM)',
			'BBD' => 'Barbadian Dollar (BBD)',
			'BDT' => 'Bangladeshi Taka (BDT)',
			'BGN' => 'Bulgarian Lev (BGN)',
			'BHD' => 'Bahraini Dinar (BHD)',
			'BIF' => 'Burundian Franc (BIF)',
			'BMD' => 'Bermudan Dollar (BMD)',
			'BND' => 'Brunei Dollar (BND)',
			'BOB' => 'Bolivian Boliviano (BOB)',
			'BRL' => 'Brazilian Real (BRL)',
			'BSD' => 'Bahamian Dollar (BSD)',
			'BTC' => 'Bitcoin (BTC)',
			'BTN' => 'Bhutanese Ngultrum (BTN)',
			'BWP' => 'Botswanan Pula (BWP)',
			'BYR' => 'Belarusian Ruble (BYR)',
			'BZD' => 'Belize Dollar (BZD)',
			'CDF' => 'Congolese Franc (CDF)',
			'CLF' => 'Chilean Unit of Account (UF) (CLF)',
			'CLP' => 'Chilean Peso (CLP)',
			'CNY' => 'Chinese Yuan (CNY)',
			'COP' => 'Colombian Peso (COP)',
			'CRC' => 'Costa Rican Colón (CRC)',
			'CUC' => 'Cuban Convertible Peso (CUC)',
			'CUP' => 'Cuban Peso (CUP)',
			'CVE' => 'Cape Verdean Escudo (CVE)',
			'CZK' => 'Czech Republic Koruna (CZK)',
			'DJF' => 'Djiboutian Franc (DJF)',
			'DKK' => 'Danish Krone (DKK)',
			'DOP' => 'Dominican Peso (DOP)',
			'DZD' => 'Algerian Dinar (DZD)',
			'EEK' => 'Estonian Kroon (EEK)',
			'EGP' => 'Egyptian Pound (EGP)',
			'ERN' => 'Eritrean Nakfa (ERN)',
			'ETB' => 'Ethiopian Birr (ETB)',
			'FJD' => 'Fijian Dollar (FJD)',
			'FKP' => 'Falkland Islands Pound (FKP)',
			'GEL' => 'Georgian Lari (GEL)',
			'GGP' => 'Guernsey Pound (GGP)',
			'GHS' => 'Ghanaian Cedi (GHS)',
			'GIP' => 'Gibraltar Pound (GIP)',
			'GMD' => 'Gambian Dalasi (GMD)',
			'GNF' => 'Guinean Franc (GNF)',
			'GTQ' => 'Guatemalan Quetzal (GTQ)',
			'GYD' => 'Guyanaese Dollar (GYD)',
			'HKD' => 'Hong Kong Dollar (HKD)',
			'HNL' => 'Honduran Lempira (HNL)',
			'HRK' => 'Croatian Kuna (HRK)',
			'HTG' => 'Haitian Gourde (HTG)',
			'HUF' => 'Hungarian Forint (HUF)',
			'IDR' => 'Indonesian Rupiah (IDR)',
			'ILS' => 'Israeli New Sheqel (ILS)',
			'IMP' => 'Manx pound (IMP)',
			'INR' => 'Indian Rupee (INR)',
			'IQD' => 'Iraqi Dinar (IQD)',
			'IRR' => 'Iranian Rial (IRR)',
			'ISK' => 'Icelandic Króna (ISK)',
			'JEP' => 'Jersey Pound (JEP)',
			'JMD' => 'Jamaican Dollar (JMD)',
			'JOD' => 'Jordanian Dinar (JOD)',
			'KES' => 'Kenyan Shilling (KES)',
			'KGS' => 'Kyrgystani Som (KGS)',
			'KHR' => 'Cambodian Riel (KHR)',
			'KMF' => 'Comorian Franc (KMF)',
			'KPW' => 'North Korean Won (KPW)',
			'KRW' => 'South Korean Won (KRW)',
			'KWD' => 'Kuwaiti Dinar (KWD)',
			'KYD' => 'Cayman Islands Dollar (KYD)',
			'KZT' => 'Kazakhstani Tenge (KZT)',
			'LAK' => 'Laotian Kip (LAK)',
			'LBP' => 'Lebanese Pound (LBP)',
			'LKR' => 'Sri Lankan Rupee (LKR)',
			'LRD' => 'Liberian Dollar (LRD)',
			'LSL' => 'Lesotho Loti (LSL)',
			'LTL' => 'Lithuanian Litas (LTL)',
			'LVL' => 'Latvian Lats (LVL)',
			'LYD' => 'Libyan Dinar (LYD)',
			'MAD' => 'Moroccan Dirham (MAD)',
			'MDL' => 'Moldovan Leu (MDL)',
			'MGA' => 'Malagasy Ariary (MGA)',
			'MKD' => 'Macedonian Denar (MKD)',
			'MMK' => 'Myanma Kyat (MMK)',
			'MNT' => 'Mongolian Tugrik (MNT)',
			'MOP' => 'Macanese Pataca (MOP)',
			'MRO' => 'Mauritanian Ouguiya (MRO)',
			'MTL' => 'Maltese Lira (MTL)',
			'MUR' => 'Mauritian Rupee (MUR)',
			'MVR' => 'Maldivian Rufiyaa (MVR)',
			'MWK' => 'Malawian Kwacha (MWK)',
			'MXN' => 'Mexican Peso (MXN)',
			'MYR' => 'Malaysian Ringgit (MYR)',
			'MZN' => 'Mozambican Metical (MZN)',
			'NAD' => 'Namibian Dollar (NAD)',
			'NGN' => 'Nigerian Naira (NGN)',
			'NIO' => 'Nicaraguan Córdoba (NIO)',
			'NOK' => 'Norwegian Krone (NOK)',
			'NPR' => 'Nepalese Rupee (NPR)',
			'NZD' => 'New Zealand Dollar (NZD)',
			'OMR' => 'Omani Rial (OMR)',
			'PAB' => 'Panamanian Balboa (PAB)',
			'PEN' => 'Peruvian Nuevo Sol (PEN)',
			'PGK' => 'Papua New Guinean Kina (PGK)',
			'PHP' => 'Philippine Peso (PHP)',
			'PKR' => 'Pakistani Rupee (PKR)',
			'PLN' => 'Polish Zloty (PLN)',
			'PYG' => 'Paraguayan Guarani (PYG)',
			'QAR' => 'Qatari Rial (QAR)',
			'RON' => 'Romanian Leu (RON)',
			'RSD' => 'Serbian Dinar (RSD)',
			'RUB' => 'Russian Ruble (RUB)',
			'RWF' => 'Rwandan Franc (RWF)',
			'SAR' => 'Saudi Riyal (SAR)',
			'SBD' => 'Solomon Islands Dollar (SBD)',
			'SCR' => 'Seychellois Rupee (SCR)',
			'SDG' => 'Sudanese Pound (SDG)',
			'SEK' => 'Swedish Krona (SEK)',
			'SGD' => 'Singapore Dollar (SGD)',
			'SHP' => 'Saint Helena Pound (SHP)',
			'SLL' => 'Sierra Leonean Leone (SLL)',
			'SOS' => 'Somali Shilling (SOS)',
			'SRD' => 'Surinamese Dollar (SRD)',
			'STD' => 'São Tomé and Príncipe Dobra (STD)',
			'SVC' => 'Salvadoran Colón (SVC)',
			'SYP' => 'Syrian Pound (SYP)',
			'SZL' => 'Swazi Lilangeni (SZL)',
			'THB' => 'Thai Baht (THB)',
			'TJS' => 'Tajikistani Somoni (TJS)',
			'TMT' => 'Turkmenistani Manat (TMT)',
			'TND' => 'Tunisian Dinar (TND)',
			'TOP' => 'Tongan Paʻanga (TOP)',
			'TRY' => 'Turkish Lira (TRY)',
			'TTD' => 'Trinidad and Tobago Dollar (TTD)',
			'TWD' => 'New Taiwan Dollar (TWD)',
			'TZS' => 'Tanzanian Shilling (TZS)',
			'UAH' => 'Ukrainian Hryvnia (UAH)',
			'UGX' => 'Ugandan Shilling (UGX)',
			'UYU' => 'Uruguayan Peso (UYU)',
			'UZS' => 'Uzbekistan Som (UZS)',
			'VEF' => 'Venezuelan Bolívar Fuerte (VEF)',
			'VND' => 'Vietnamese Dong (VND)',
			'VUV' => 'Vanuatu Vatu (VUV)',
			'WST' => 'Samoan Tala (WST)',
			'XAF' => 'CFA Franc BEAC (XAF)',
			'XAG' => 'Silver (troy ounce) (XAG)',
			'XAU' => 'Gold (troy ounce) (XAU)',
			'XCD' => 'East Caribbean Dollar (XCD)',
			'XDR' => 'Special Drawing Rights (XDR)',
			'XOF' => 'CFA Franc BCEAO (XOF)',
			'XPD' => 'Palladium Ounce (XPD)',
			'XPF' => 'CFP Franc (XPF)',
			'XPT' => 'Platinum Ounce (XPT)',
			'YER' => 'Yemeni Rial (YER)',
			'ZAR' => 'South African Rand (ZAR)',
			'ZMK' => 'Zambian Kwacha (pre-2013) (ZMK)',
			'ZMW' => 'Zambian Kwacha (ZMW)',
			'ZWL' => 'Zimbabwean Dollar (ZWL)'
		];

		$arr_currency = apply_filters( 'wpjobster_arr_curency', $arr_currency );

		return $arr_currency;
	}
}

if ( ! function_exists( 'wpj_set_site_default_currency' ) ) {
	function wpj_set_site_default_currency() {
		global $wpjobster_currencies_array;

		if ( ! isset( $_GET['site_currency'] ) && ! isset( $_COOKIE['site_currency'] ) && isset( $wpjobster_currencies_array[0] ) ) {
			setcookie( 'site_currency', $wpjobster_currencies_array[0], time() + 9993600, '/' );

		} elseif ( isset( $_GET['site_currency'] ) ) {
			setcookie( 'site_currency', $_GET['site_currency'], time() + 9993600, '/' );

		}
	}
}

if ( ! function_exists( 'wpj_set_currency_globals' ) ) {
	function wpj_set_currency_globals() {
		global $wpjobster_currencies_array;
		global $wpjobster_currencies_symbols_array;

		$wpjobster_currencies_array         = [];
		$wpjobster_currencies_symbols_array = [];

		$currencies                = wpj_get_option( 'add-new-currency' );
		$is_allowed_multi_currency = wpj_is_allowed( 'multi_currency' );

		if ( ! empty( $currencies['currency_name'] ) ) {
			for ( $i = 0; $i < count( $currencies['currency_name'] ); $i++ ) {
				$wpjobster_currency_x = trim( $currencies['currency_name'][$i] );

				if ( ! $is_allowed_multi_currency && $i > 0 ) $wpjobster_currency_x = '';

				if ( $wpjobster_currency_x ) {
					array_push( $wpjobster_currencies_array, $wpjobster_currency_x );

					$wpjobster_currency_symbol_x = trim( $currencies['curency_symbol'][$i] );

					if ( $wpjobster_currency_symbol_x ) {
						$wpjobster_currencies_symbols_array[$wpjobster_currency_x] = $wpjobster_currency_symbol_x;

					} else {
						$wpjobster_currencies_symbols_array[$wpjobster_currency_x] = $wpjobster_currency_x;

					}
				}
			}

		} else {
			$wpjobster_currencies_array         = ['0' => 'USD'];
			$wpjobster_currencies_symbols_array = ['USD' => '$'];

		}

		if ( isset( $_COOKIE['site_currency'] ) && ! in_array( $_COOKIE['site_currency'], $wpjobster_currencies_array ) ) {
			if ( isset( $wpjobster_currencies_array[0] ) ) {
				$selected = $wpjobster_currencies_array[0];
				$_COOKIE['site_currency'] = $wpjobster_currencies_array[0];

				setcookie( 'site_currency', $selected, time() + 9993600, '/' );
			}
		}

		if ( isset( $_GET['site_currency'] ) && ! in_array( $_GET['site_currency'], $wpjobster_currencies_array ) ) {
			$_GET['site_currency'] = $wpjobster_currencies_array[0];
		}
	}
}

if ( ! function_exists( 'wpj_change_currency_on_post_new_job_page' ) ) {
	function wpj_change_currency_on_post_new_job_page() {
		global $wpjobster_currencies_array;

		$post_new_job_page = wpj_get_option( 'wpjobster_post_new_page_id' );

		if ( $post_new_job_page ) {
			if ( wpj_is_json( $post_new_job_page ) == 1 ) {
				$post_new_job_page = wpj_json_decode( $post_new_job_page );

			}

			$post_new_job_page_id = $post_new_job_page;

		} else {
			$post_new_job_page_id = wpj_get_option( 'wpjobster_how_it_works_page_id' );

		}

		if ( is_page( $post_new_job_page_id ) ) {
			if ( isset( $_GET['site_currency'] ) && $_GET['site_currency'] != $wpjobster_currencies_array[0] ) {
				$_GET['site_currency'] = $wpjobster_currencies_array[0];

			} elseif (
				isset( $_COOKIE['site_currency'] )
				&& isset( $wpjobster_currencies_array[0] )
				&& $_COOKIE['site_currency'] != $wpjobster_currencies_array[0]
			) {
				$_COOKIE['site_currency'] = $wpjobster_currencies_array[0];

				setcookie( "site_currency", $wpjobster_currencies_array[0], time() + 9993600, "/" );

			}
		}
	}
}
