<?php
if ( ! function_exists( 'wpj_is_email_valid' ) ) {
	function wpj_is_email_valid( $email ) {
		return preg_match( "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,10})$/i", $email );
	}
}

if ( ! function_exists( 'wpj_filter_emails' ) ) {
	function wpj_filter_emails( $text, $replace = true ) {
		preg_match_all( '/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]+)/', $text, $matches, PREG_SET_ORDER );

		$status       = 0;
		$matchesCount = count( $matches );

		for ( $i = 0; $i < $matchesCount; $i++ ) {
			if ( filter_var( $matches[$i][0], FILTER_VALIDATE_EMAIL ) ) {
				if ( $replace ) {
					$text = str_replace( $matches[$i][0], '*****', $text );
				}

				$status = 1;
			}
		}

		return [$text, $status];
	}
}

if ( ! function_exists( 'wpj_get_email_verification_status' ) ) {
	function wpj_get_email_verification_status( $return = '' ) {
		$status = $title = $message = '';

		if ( ! empty( $_GET['username'] ) AND ! empty( $_GET['key'] ) ) {
			$user = get_user_by( 'slug', $_GET['username'] );

			if ( ! $user ) $not_allowed = true;

			if ( ! empty( $not_allowed ) ) {
				$status  = "not_allowed";
				$title   = __( "Not allowed", "wpjobster" );
				$message = __( "You do not have permission to access this page", "wpjobster" );

			} else {
				if ( WPJ_Form::get( 'action' ) == 'withdrawal' ) { // Withdrawal
					if ( isset( $_GET['key'] ) ) {
						$row = wpj_get_withdrawal_order( 'id', ['uid' => $user->ID, 'activation_key' => $_GET['key']], 'row' );

						if ( ! empty( $row->id ) ) {
							$status  = "ok";
							$title   = __( "Withdrawal Confirmed", "wpjobster" );
							$message = __( "Your withdrawal request was successfully confirmed.", "wpjobster" );

						} else {
							$status  = "wrongkey";
							$title   = __( "Wrong Link", "wpjobster" );
							$message = __( "Oops. It seems that the withdrawal verification link is wrong or the request was already verified.", "wpjobster" );

						}
					}

				} else { // Email verification
					if ( get_user_meta( $user->ID, 'uz_email_verification', true ) == 1 ) {
						if ( hash( "sha256", $user->user_nicename . get_user_meta( $user->ID, 'uz_email_verification_key', true ), false ) == $_GET['key'] ) {
							$status  = "alreadyok";
							$title   = __( "Email Verified", "wpjobster" );
							$message = __( "Your email was already verified.", "wpjobster" );

						} else {
							$status  = "wrongkey";
							$title   = __( "Wrong Link", "wpjobster" );
							$message = __( "Oops. It seems that the email verification link is wrong. Please try again or login to your account and generate a new one.", "wpjobster" );

						}

					} elseif ( hash( "sha256", $user->user_nicename . get_user_meta( $user->ID, 'uz_email_verification_key', true ), false ) == $_GET['key'] ) {
						$status  = "ok";
						$title   = __( "Email Verified", "wpjobster" );
						$message = __( "Your email was successfully verified.", "wpjobster" );

					} else {
						$status  = "wrongkey";
						$title   = __( "Wrong Link", "wpjobster" );
						$message = __( "Oops. It seems that the email verification link is wrong. Please try again or login to your account and generate a new one.", "wpjobster" );

					}

				}
			}

		} elseif ( is_user_logged_in() && WPJ_Form::get( 'action' ) == 'resend' && get_user_meta( get_current_user_id(), 'uz_email_verification', true ) != 1 ) {
			$status  = "resent";
			$title   = __( "Verification Email Sent", "wpjobster" );
			$message = __( "The verification email was sent to your email address.", "wpjobster" );

		} else {
			$status  = "invalid";
			$title   = __( "Invalid", "wpjobster" );
			$message = __( "The way you try to access the page is invalid", "wpjobster" );

		}

		if ( $return == 'status' )  return $status;
		if ( $return == 'title' )   return $title;
		if ( $return == 'message' ) return $message;

		return ['status' => $status, 'title' => $title, 'message' => $message];
	}
}

if ( ! function_exists( 'wpj_process_email_verification' ) ) {
	function wpj_process_email_verification() {
		if ( ! empty( $_GET['username'] ) && ! empty( $_GET['key'] ) ) {
			$user = get_user_by( 'slug', $_GET['username'] );

			if ( empty( $user->ID ) ) $not_allowed = true;

			if ( ! isset( $not_allowed ) ) {
				do_action( 'wpj_before_email_key_verification_process', WPJ_Form::get( 'action' ), WPJ_Form::get( 'key' ), $user );

				// Withdrawal
				if ( WPJ_Form::get( 'action' ) == 'withdrawal' ) {
					if ( isset( $_GET['key'] ) ) {
						$row = wpj_get_withdrawal_order( 'id, payedamount, methods', ['uid' => $user->ID, 'activation_key' => $_GET['key']], 'row' );

						if ( ! empty( $row->id ) ) {
							wpj_update_withdrawal_order( ['activation_key' => ''], ['id' => $row->id] );

							$data     = explode( '|', $row->payedamount );
							$currency = $data[0];
							$amount   = $data[1];

							// Email the admin
							wpj_notify_user_translated( 'admin_new_withdrawal_request', 'admin', [
								'##withdrawal_username##' => wpj_get_user_display_type( $user->ID ),
								'##withdrawal_amount##'   => wpj_show_price_precise( $amount, 2, $currency ),
								'##withdrawal_method##'   => $row->methods
							]);
						}
					}

				// Email verification
				} elseif ( hash( "sha256", $user->user_nicename . get_user_meta( $user->ID, 'uz_email_verification_key', true ), false ) == $_GET['key'] ) {
					update_user_meta( $user->ID, 'uz_email_verification', 1 );

				}
			}

		// Resend Email Verification
		} elseif ( is_user_logged_in() && WPJ_Form::get( 'action' ) == 'resend' && get_user_meta( get_current_user_id(), 'uz_email_verification', true ) != 1 ) {
			$user_data = get_userdata( get_current_user_id() );

			$email_key_generated = hash( "sha256", rand( 0, 1000000 ), false );

			update_user_meta( get_current_user_id(), 'uz_email_verification_key', $email_key_generated );
			update_user_meta( get_current_user_id(), 'uz_email_verification', 0 );

			$email_key           = $email_key_generated;
			$email_key_processed = hash( "sha256", $user_data->user_nicename . $email_key, false );
			$email_verification  = get_permalink( wpj_get_option( 'wpjobster_verify_email_page_id' ) ) . "?username=" . $user_data->user_nicename . "&key=" . $email_key_processed;

			if ( wpj_get_option( 'wpjobster_verify_email' ) != 'no' ) {
				wpj_notify_user_translated( 'user_verification', get_current_user_id(), [
					'##email_verification##' => $email_verification,
					'##receiver_email##'     => $user_data->user_email
				]);
			}
		}
	}
}

if ( ! function_exists( 'wpj_resend_withdrawal_confirmation_email' ) ) {
	function wpj_resend_withdrawal_confirmation_email( $uid = '', $act_key = '' ) {
		if ( ! $uid )     $uid     = $_POST['uid'];
		if ( ! $act_key ) $act_key = $_POST['key'];

		if ( $uid && $act_key ) {
			$row = wpj_get_withdrawal_order( 'payedamount, methods', ['uid' => $uid, 'activation_key' => $act_key], 'row' );

			if ( $row ) {
				$details = explode( '|', $row->payedamount );

				$currency = $details[0];
				$amount   = $details[1];

				$user_data = get_userdata( $uid );

				wpj_notify_user_translated( 'withdraw_req_confirmation', $uid, [
					'##amount_withdrawn##'              => wpj_show_price_precise( $amount, 2, $currency ),
					'##withdraw_method##'               => wpj_translate_string( $row->methods ),
					'##withdrawal_email_verification##' => get_permalink( wpj_get_option( 'wpjobster_verify_email_page_id' ) ) . "?username=" . $user_data->user_nicename . "&key=" . $act_key . "&action=withdrawal"
				]);

				if ( wpj_is_ajax_call() ) echo 'success';

			} else {
				if ( wpj_is_ajax_call() ) echo 'error';

			}

		} else {
			if ( wpj_is_ajax_call() ) echo 'error';

		}

		if ( wpj_is_ajax_call() ) wp_die();
	}
}

if ( ! function_exists( 'wpj_set_email_from' ) ) {
	function wpj_set_email_from( $old ) {
		$email_addr_from = trim( wpj_get_option( 'wpjobster_email_addr_from' ) );

		if ( empty( $email_addr_from ) )
			$email_addr_from = get_bloginfo( 'admin_email' );

		if ( ! empty( $email_addr_from ) )
			return $email_addr_from;

		else
			return 'info@wpjobster.com';
	}
}

if ( ! function_exists( 'wpj_set_name_from' ) ) {
	function wpj_set_name_from( $old ) {
		$email_name_from = trim( wpj_get_option( 'wpjobster_email_name_from' ) );

		if ( ! empty( $email_name_from ) )
			return $email_name_from;

		else
			return 'wpjobster.com';
	}
}

if ( ! function_exists( 'wpj_set_email_content_type' ) ) {
	function wpj_set_email_content_type() {
		if ( ! function_exists( 'is_plugin_active' ) ) {
			include_once ( ABSPATH . 'wp-admin/includes/plugin.php' );
		}

		if ( wpj_get_option( 'wpjobster_allow_html_emails' ) == 'yes' && ! is_plugin_active( 'wp-better-emails/wpbe.php' ) )
			return "text/html";

		else
			return "text/plain";
	}
}