<?php
if ( ! function_exists( 'wpj_save_withdrawal_request' ) ) {
	function wpj_save_withdrawal_request() {
		global $wpjobster_currencies_array;

		$post_exist = false;

		if ( wpj_get_withdrawals_payment_gateways() ) {
			foreach ( wpj_get_withdrawals_payment_gateways() as $key => $value ) {
				if ( $_POST['method'] == $value . '_withdraw' ) {
					$post_exist = true;
				}
			}
		}

		$uid = get_current_user_id();

		$currency = apply_filters( 'wpjobster_withdrawal_currency_filter', wpj_get_site_currency() );

		$details = '';

		if ( $post_exist ) {
			$details = isset( $_POST['details'] ) ? esc_sql( trim( $_POST['details'] ) ) : '';

			if ( $_POST['method'] == 'banktransfer_withdraw' ) { // bank transfer
				$details = '';

				// do not translate the strings that should be inserted into the database
				// because it conflicts with TranslatePress and insertion fails in other languages
				$bank_fields = [
					'bank_bank_name'        => 'Bank Name',
					'bank_bank_address'     => 'Bank Address',
					'bank_account_name'     => 'Account Name',
					'bank_account_number'   => 'Account Number',
					'bank_account_currency' => 'Account Currency',
					'bank_additional_info'  => 'Additional Info',
				];

				foreach ( $bank_fields as $field_key => $field_name ) {
					if ( apply_filters( 'wpj_payments_display_' . $field_key . '_field', true ) ) {
						$details .= $field_name . ': ' . get_user_meta( $uid, $field_key, true ) . '<br>';
					}
				}

				$details = esc_sql( wpj_get_allowed_html_tags_for_wysiwyg( $details ) );
			}
		}

		$email  = isset( $_POST['email'] ) ? esc_sql( trim( $_POST['email'] ) ) : '';

		$amount = isset( $_POST['amount'] ) ? trim( $_POST['amount'] ) : '';

		$amount_default = wpj_get_exchanged_value( $amount, $currency, $wpjobster_currencies_array[0] );

		$wpjobster_withdraw_limit = wpj_get_option( 'wpjobster_withdraw_limit' );

		if ( empty( $wpjobster_withdraw_limit ) OR ! is_numeric( $wpjobster_withdraw_limit ) ) $wpjobster_withdraw_limit = 10;

		$tm = current_time( 'timestamp', 1 );

		$err_content = '';

		if ( ! is_numeric( $amount ) || $amount < 0 ) {
			$err_content = __( 'Provide a well formated amount.', 'wpjobster' );

		} elseif ( ! empty( $_POST['email'] ) && wpj_is_email_valid( $email ) == false ) {
			$err_content =  __( 'Invalid email provided.', 'wpjobster' );

		} elseif ( $amount_default < $wpjobster_withdraw_limit ) {
			$err_content = sprintf( __( 'The amount must be higher than: %s.', 'wpjobster' ), wpj_show_price( $wpjobster_withdraw_limit ) );

		} elseif ( wpj_get_user_credit( get_current_user_id() ) < $amount_default ) {
			$err_content = __( 'Your balance is smaller than the amount requested.', 'wpjobster' );

		}

		if ( ! $err_content ) {
			$method = '';

			if ( $_POST['method'] == 'paypal_withdraw' )       $method = "PayPal";
			if ( $_POST['method'] == 'payoneer_withdraw' )     $method = "Payoneer";
			if ( $_POST['method'] == 'banktransfer_withdraw' ) $method = "Bank";

			$method = apply_filters( 'wpjobster_withdraw_method_filter', $method );

			if ( $method ) {
				$row = wpj_get_withdrawal_order( 'id', ['uid' => $uid, 'datemade' => $tm], 'row' );

				if ( ! $row ) {
					$payedamount = $currency . '|' . wpj_number_format_special( $amount, 1 );

					if ( wpj_get_option( 'wpjobster_enable_withdraw_email_verification' ) == 'yes' ) {
						$act_key   = md5( uniqid( mt_rand(), true ) );
						$email_key = 'withdraw_req_confirmation';

					} else {
						$act_key = '';
						$email_key = 'withdraw_req';

					}

					wpj_insert_withdrawal_order(
						[
							'payeremail' => $details,
							'methods' => $method,
							'amount' => $amount_default,
							'datemade' => $tm,
							'uid' => $uid,
							'payedamount' => $payedamount,
							'activation_key' => $act_key
						],
						['%s', '%s', '%f', '%d', '%d', '%s', '%s']
					);

					$credits = wpj_get_user_credit( $uid );

					wpj_update_user_credit( $uid, $credits - $amount_default );

					do_action( 'wpj_after_withdrawal_request', $details, $method, $amount_default, $tm, $uid, $payedamount, $act_key );

					$user_data = get_userdata( $uid );

					$withdrawal_email_verification = get_permalink( wpj_get_option( 'wpjobster_verify_email_page_id' ) ) . "?username=" . $user_data->user_nicename . "&key=" . $act_key . "&action=withdrawal";

					wpj_notify_user_translated( $email_key, $uid, [
						'##amount_withdrawn##' => wpj_show_price_precise( $amount, 2, $currency ),
						'##withdraw_method##' => wpj_translate_string( $method ),
						'##withdrawal_email_verification##' => $withdrawal_email_verification
					] );

					// Email the admin
					if ( wpj_get_option( 'wpjobster_enable_withdraw_email_verification' ) != 'yes' ) {
						wpj_notify_user_translated( 'admin_new_withdrawal_request', 'admin', [
							'##withdrawal_username##' => wpj_get_user_display_type( $uid ),
							'##withdrawal_amount##' => wpj_show_price_precise( $amount, 2, $currency ),
							'##withdrawal_method##' => wpj_translate_string( $method ) ]
						);
					}
				}
			}

			echo json_encode( [ 'status' => 'success' ] );

		} else {
			echo json_encode( [ 'status' => 'error', 'error' => $err_content ] );

		}

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