<?php
if ( ! function_exists( 'wpj_validate_user_login_form' ) ) {
	function wpj_validate_user_login_form( $username = '', $password = '' ) {
		$user = wp_signon([
			'user_login'    => WPJ_Form::post( 'log', $username ),
			'user_password' => WPJ_Form::post( 'pwd', $password ),
			'remember'      => isset( $_POST['rememberme'] )
		], false );

		$error_code = false;
		$error      = false;

		if ( is_wp_error( $user ) ) {
			$error_code = $user->get_error_code();

			if ( $error_code == 'empty_password' )
				$error = __( 'The password field is empty.', 'wpjobster' );

			elseif ( $error_code == 'empty_email' )
				$error = __( 'Please type your email address.', 'wpjobster' );

			elseif ( $error_code == 'invalid_email' )
				$error = __( 'The email address is not correct.', 'wpjobster' );

			elseif ( $error_code == 'invalidcombo' )
				$error = __( 'There is no account with that username or email address.', 'wpjobster' );

			elseif ( $error_code == 'empty_username' )
				$error = __( 'The username field is empty.', 'wpjobster' );

			elseif ( $error_code == 'invalid_username' )
				$error = wpj_get_option( 'wpjobster_enable_login_hints' ) != 'no' ? sprintf( __( 'The username <strong>%s</strong> is not registered on this site. If you are unsure of your username, try your email address instead.', 'wpjobster' ), WPJ_Form::post( 'log' ) ) : __( 'The data entered is incorrect!', 'wpjobster' );

			elseif ( $error_code == 'incorrect_password' )
				$error = wpj_get_option( 'wpjobster_enable_login_hints' ) != 'no' ? sprintf( __( 'The password you entered for the username %s is incorrect.', 'wpjobster' ), WPJ_Form::post( 'log' ) ) : __( 'The data entered is incorrect!', 'wpjobster' );

			elseif ( $error_code == 'retrieve_password_email_failure' )
				$error = wpj_get_option( 'wpjobster_enable_login_hints' ) != 'no' ? __( 'The email could not be sent. Your site may not be correctly configured to send emails. <a href="https://wordpress.org/support/article/resetting-your-password/">Get support for resetting your password</a>.', 'wpjobster' ) : __( 'The data entered is incorrect!', 'wpjobster' );

			else
				$error = $user->get_error_message();

		}

		$data = ['code' => $error_code, 'message' => $error];

		if ( wpj_is_ajax_call() ) wp_send_json( $data );

		return $data;
	}
}

if ( ! function_exists( 'wpj_validate_user_register_form' ) ) {
	function wpj_validate_user_register_form( $errors = [] ) {
		$data = ['code' => false, 'message' => false];

		// remove WP default errors
		if ( ! empty( $errors->errors ) ) $errors->errors = [];

		// username
		if ( empty( $_POST['user_login'] ) ) {
			$data = ['code' => 'empty_username', 'message' => __( 'Please enter a username.', 'wpjobster' )];

			if ( ! wpj_is_ajax_call() ) $errors->add( $data['code'], $data['message'] );

		} elseif ( ! validate_username( $_POST['user_login'] ) ) {
			$data = ['code' => 'invalid_username', 'message' => __( 'This username is invalid because it uses illegal characters. Please enter a valid username.', 'wpjobster' )];

			if ( ! wpj_is_ajax_call() ) $errors->add( $data['code'], $data['message'] );

		} elseif ( username_exists( $_POST['user_login'] ) ) {
			$data = ['code' => 'username_exists', 'message' => __( 'This username is already registered. Please choose another one.', 'wpjobster' )];

			if ( ! wpj_is_ajax_call() ) $errors->add( $data['code'], $data['message'] );

		} elseif ( ctype_digit( $_POST['user_login'] ) ) {
			$data = ['code' => 'numeric_username', 'message' => __( 'Usernames cannot consist of only numbers. Please choose a different username.', 'wpjobster' )];

			if ( ! wpj_is_ajax_call() ) $errors->add( $data['code'], $data['message'] );

		} else {
			$illegal_user_logins = (array) apply_filters( 'illegal_user_logins', [] );

			if ( in_array( strtolower( $_POST['user_login'] ), array_map( 'strtolower', $illegal_user_logins ), true ) ) {
				$data = ['code' => 'invalid_username', 'message' => __( 'Sorry, that username is not allowed.', 'wpjobster' )];

				if ( ! wpj_is_ajax_call() ) $errors->add( $data['code'], $data['message'] );

			}

		}

		// email
		if ( empty( $_POST['user_email'] ) ) {
			$data = ['code' => 'empty_email', 'message' => __( 'Please type your email address.', 'wpjobster' )];

			if ( ! wpj_is_ajax_call() ) $errors->add( $data['code'], $data['message'] );

		} elseif ( ! is_email( $_POST['user_email'] ) ) {
			$data = ['code' => 'invalid_email', 'message' => __( 'The email address is not correct.', 'wpjobster' )];

			if ( ! wpj_is_ajax_call() ) $errors->add( $data['code'], $data['message'] );

		} elseif ( email_exists( $_POST['user_email'] ) ) {
			$data = ['code' => 'email_exists', 'message' => sprintf( __( 'This email address is already registered. <a class="login-link" href="%s">Log in</a> with this address or choose another one.', 'wpjobster' ), wpj_get_login_link() )];

			if ( ! wpj_is_ajax_call() ) $errors->add( $data['code'], $data['message'] );

		}

		// password
		if ( empty( $_POST['provider'] ) ) {
			if ( empty( $_POST['user_password'] ) ) {
				$data = ['code' => 'empty_password', 'message' => __( 'Please enter a password.', 'wpjobster' )];

				if ( ! wpj_is_ajax_call() ) $errors->add( $data['code'], $data['message'] );

			} elseif ( $_POST['user_password'] != $_POST['user_confirm_password'] ) {
				$data = ['code' => 'confirm_password', 'message' => __( 'Passwords do not match.', 'wpjobster' )];

				if ( ! wpj_is_ajax_call() ) $errors->add( $data['code'], $data['message'] );

			}
		}

		// phone number
		if ( wpj_get_option( 'wpjobster_enable_phone_number' ) == 'yes' && wpj_get_option( 'wpjobster_phone_number_mandatory' ) == 'yes' ) {
			if ( empty( $_POST['cell_number'] ) ) {
				$data = ['code' => 'empty_cell_number', 'message' => __( 'Please enter phone number.', 'wpjobster' )];

				if ( ! wpj_is_ajax_call() ) $errors->add( $data['code'], $data['message'] );

			} else {
				$results = wpj_get_user_meta( 'user_id', ['meta_key' => 'cell_number', 'meta_value' => $_POST['cell_number']], 'row' );

				if ( $results ) {
					$data = ['code' => 'phone_exists', 'message' => __( 'This phone number is already registered, please choose another one.', 'wpjobster' )];

					if ( ! wpj_is_ajax_call() ) $errors->add( $data['code'], $data['message'] );

				}

			}

		}

		// tos
		if ( wpj_get_option( 'wpjobster_register_tos_and_privacy' ) == 'checkbox' ) {
			if ( ! isset( $_POST['wpj_agree_tos_privacy'] ) ) {
				$data = ['code' => 'error_tos_privacy', 'message' => __( 'Terms of Service and Privacy Policy agreement is required.', 'wpjobster' )];

				if ( ! wpj_is_ajax_call() ) $errors->add( $data['code'], $data['message'] );

			}
		}

		// reCaptcha
		if (
			wpj_get_option( 'wpjobster_enable_user_register_reCaptcha' ) == 'yes'
			&& wpj_get_option( 'wpjobster_recaptcha_api_key' )
			&& wpj_get_option( 'wpjobster_recaptcha_api_secret' )
		) {
			$parameters = [
				'secret'   => wpj_get_option( 'wpjobster_recaptcha_api_secret' ),
				'response' => $_POST['g-recaptcha-response']
			];

			if ( ! empty( $_COOKIE['g_recaptcha_response'] ) && $_COOKIE['g_recaptcha_response'] != $_POST['g-recaptcha-response'] ) {
				setcookie( "g_recaptcha_response", $_POST['g-recaptcha-response'], time() + 60, "/" ); /* 60 seconds */

				$response      = wpj_get_data_with_cURL( 'https://www.google.com/recaptcha/api/siteverify?' . http_build_query( $parameters ) );
				$json_response = wpj_json_decode( $response, true );

				if ( isset( $json_response['error-codes'] ) && is_array( $json_response['error-codes'] ) ) {
					$data = ['code' => 'captcha_error', 'message' => implode( ',', $json_response['error-codes'] )];

					if ( ! wpj_is_ajax_call() ) $errors->add( $data['code'], $data['message'] );

				} elseif ( $json_response['success'] == false ) {
					$data = ['code' => 'captcha_error', 'message' => __( 'Please verify the captcha.', 'wpjobster' )];

					if ( ! wpj_is_ajax_call() ) $errors->add( $data['code'], $data['message'] );

				}
			}
		}

		$return = [
			'data'   => apply_filters( 'wpj_registration_data_filter', $data, 'ajax_call' ),
			'errors' => apply_filters( 'wpj_registration_errors_filter', $errors, 'wp_call' )
		];

		if ( wpj_is_ajax_call() ) wp_send_json( $return['data'] );

		return $return['errors'];
	}
}

if ( ! function_exists( 'wpj_validate_user_lostpassword_form' ) ) {
	function wpj_validate_user_lostpassword_form() {
		$data = ['code' => false, 'message' => false ];

		if ( empty( $_POST['user_login'] ) )
			$data = ['code' => 'empty_username', 'message' => __( 'Please enter a username or email address.', 'wpjobster' )];

		elseif ( strpos( $_POST['user_login'], '@' ) )
			$user_data = get_user_by( 'email', trim( wp_unslash( $_POST['user_login'] ) ) );

		else
			$user_data = get_user_by( 'login', trim( wp_unslash( $_POST['user_login'] ) ) );

		if ( empty( $user_data ) )
			$data = ['code' => 'invalidcombo', 'message' => __( 'There is no account with that username or email address.', 'wpjobster' )];

		if ( wpj_is_ajax_call() ) wp_send_json( $data );

		return $data;
	}
}

if ( ! function_exists( 'wpj_validate_user_recaptcha_field' ) ) {
	function wpj_validate_user_recaptcha_field( $user = '', $password = '' ) {
		if (
			! is_user_logged_in()
			&& wpj_get_option( 'wpjobster_enable_user_login_reCaptcha' ) == 'yes'
			&& wpj_get_option( 'wpjobster_recaptcha_api_key' )
			&& wpj_get_option( 'wpjobster_recaptcha_api_secret' )
		) {

			if (
				! isset( $_POST['_wp_http_referer'] )
				&& ! isset( $_POST['bouncer_account_linking'] )
				&& ! isset( $_POST['g-recaptcha-response'] )
			) {
				$parameters = [
					'secret'   => urlencode(  wpj_get_option( 'wpjobster_recaptcha_api_secret' ) ),
					'response' => urlencode( $_POST['g-recaptcha-response'] )
				];

				$response      = wpj_get_data_with_cURL( 'https://www.google.com/recaptcha/api/siteverify?' . http_build_query( $parameters ) );
				$json_response = wpj_json_decode( $response, true );

				if ( isset( $json_response['error-codes'] ) && is_array( $json_response['error-codes'] ) )
					return new WP_Error( 'captcha_error', implode( ',', $json_response['error-codes'] ) );

				elseif ( $json_response['success'] == false )
					return new WP_Error( 'captcha_error', __( 'Please verify the captcha.', 'wpjobster' ) );
			}

		}

		return $user;
	}
}

if ( ! function_exists( 'wpj_validate_user_2fa_field' ) ) {
	function wpj_validate_user_2fa_field( $user = '', $password = '' ) {
		if (
			! is_user_logged_in()
			&& wpj_get_option( 'wpjobster_enable_user_2fa' ) == 'yes'
			&& get_user_meta( wpj_get_user_id_by_IP(), 'user_2fa', true ) == 'on'
		) {
			include_once get_template_directory() . '/vendor/google-authenticator/FixedBitNotation.php';
			include_once get_template_directory() . '/vendor/google-authenticator/GoogleAuthenticatorInterface.php';
			include_once get_template_directory() . '/vendor/google-authenticator/GoogleAuthenticator.php';
			include_once get_template_directory() . '/vendor/google-authenticator/GoogleQrUrl.php';
			include_once get_template_directory() . '/vendor/google-authenticator/RuntimeException.php';

			$g = new \Sonata\GoogleAuthenticator\GoogleAuthenticator();

			$secret = get_user_meta( preg_replace( "/[^0-9]/", "", wpj_get_user_ip() ), '2fa_secret_code', true );

			if ( $g->checkCode( $secret, $_POST['2fa_code'] ) ) {}
			else return new WP_Error( 'two_fa_error', __( 'The verification code is invalid.', 'wpjobster' ) );
		}

		return $user;
	}
}


if ( ! function_exists( 'wpj_get_user_authentication_links' ) ) {
	function wpj_get_user_authentication_links( $device = 'pc' ) {
		$buttons_list = [
			'login' => [
				'label'   => __( 'Login', 'wpjobster' ),
				'url'     => esc_url( wpj_get_login_link() ),
				'a_class' => "login-link " . ( $device == 'mobile' ? 'item' : 'text-button text-button-simple' ),
			],
			'register' => [
				'label'   => __( 'Register', 'wpjobster' ),
				'url'     => esc_url( wpj_get_register_link() ),
				'a_class' => "register-link " . ( $device == 'mobile' ? 'item' : 'text-button' ),
			],
		];

		$buttons_list = apply_filters( 'wpj_header_buttons_filter', $buttons_list );

		return $buttons_list;
	}
}

if ( ! function_exists( 'wpj_generate_user_empty_password' ) ) {
	function wpj_generate_user_empty_password() {
		return WPJ_Form::post( 'user_password', wpj_generate_random_value( 10 ) );
	}
}

if ( ! function_exists( 'wpj_change_social_login_label' ) ) {
	function wpj_change_social_login_label( $provider_id, $provider_name, $authenticate_url ) {
		ob_start();

		wpj_display_social_login_field( $provider_id, $provider_name, $authenticate_url );

		return ob_get_clean();
	}
}

if ( ! function_exists( 'wpj_validate_username' ) ) {
	function wpj_validate_username( $valid = '', $username = '' ) {
		if ( preg_match( "/\\s/", $username ) || preg_match( "/@/", $username ) )
			$valid = false;

		return $valid;
	}
}

if ( ! function_exists( 'wpj_set_user_avatar_from_social_media' ) ) {
	function wpj_set_user_avatar_from_social_media() {
		if ( function_exists( 'wsl_get_stored_hybridauth_user_profiles_by_user_id' ) ) {
			$uid       = get_current_user_id();
			$is_social = wsl_get_stored_hybridauth_user_profiles_by_user_id( $uid );

			if ( $is_social ) {
				if ( $uid ) {
					$wsl_photo_updated = get_user_meta( $uid, 'wsl_photo_updated', true );
					if ( $wsl_photo_updated != 'done' ) {
						$avatar = get_user_meta( $uid, 'avatar', true );

						if ( $avatar == '' ) {
							$wsl_account = wsl_get_stored_hybridauth_user_profiles_by_user_id( $uid );

							if ( $wsl_account != '' ) {
								if ( isset( $wsl_account[0]->photourl ) ) {
									$wsl_avatar = $wsl_account[0]->photourl;

									update_user_meta( $uid, 'avatar', $wsl_avatar );
									update_user_meta( $uid, 'wsl_photo_updated', 'done' );
								}
							}
						}
					}
				}
			}
		}
	}
}

if ( ! function_exists( 'wpj_reset_password' ) ) {
	function wpj_reset_password( $message, $reset_key, $user_login, $user_data ) {
		if ( wpj_get_option( "uz_email_user_forgot_password_enable" ) != 'no' )
			wpj_notify_user_translated( 'user_forgot_password', $user_data->ID, [
				'##password_reset_link##' => apply_filters( 'wpj_reset_password_link_filter', get_bloginfo( 'url' ) . "/wp-login.php?action=rp&key={$reset_key}&login=" . rawurlencode( $user_data->user_login ), $reset_key, $user_data->user_login ),
				'##receiver_email##'      => $user_data->user_email
			] );

		else
			return $message;

		return false;
	}
}

if ( ! function_exists( 'wpj_replace_wp_error_messages' ) ) {
	function wpj_replace_wp_error_messages( $errors ) {
		if ( wpj_get_option( 'wpjobster_enable_login_hints' ) != 'no' )
			return $errors;

		else
			return __( 'The data entered is incorrect!', 'wpjobster' );
	}
}

if ( ! function_exists( 'wpj_deregister_load_style_php_style' ) ) {
	function wpj_deregister_load_style_php_style() {
		if ( $GLOBALS['pagenow'] === 'wp-login.php' )
			wp_deregister_style( 'login' );
	}
}

if ( ! function_exists( 'wpj_register_dashicons_style' ) ) {
	function wpj_register_dashicons_style() {
		if ( $GLOBALS['pagenow'] === 'wp-login.php' )
			wp_enqueue_style( 'dashicons' );
	}
}