<?php // TIPS
if ( ! function_exists( 'wpj_insert_tips_purchase_order' ) ) {
	function wpj_insert_tips_purchase_order( $args = [] ) {
		// Order info
		$oid = ! empty( $args['oid'] ) ? $args['oid'] : WPJ_Form::request( 'oid' );

		if ( ! $oid ) $oid = get_query_var( 'oid' );

		$order = wpj_get_job_order_by_id( $oid );

		// Payment info
		$payment_status  = ! empty( $args['payment_status'] ) ? $args['payment_status'] : 'pending';
		$payment_gateway = ! empty( $args['payment_gateway'] ) ? $args['payment_gateway'] : WPJ_Form::get( 'pay_for_item' );

		// Currency
		$currency = ! empty( $args['currency'] ) ? $args['currency'] : apply_filters( 'wpjobster_take_allowed_currency_' . $payment_gateway, '' );

		if ( empty( $currency ) ) $currency = wpj_get_site_currency();

		// Tips id
		$tips_id = isset( $args['tips'] ) && is_numeric( $args['tips'] ) ? $args['tips'] : WPJ_Form::request( 'tips' );

		if ( ! is_numeric( $tips_id ) ) $tips_id = 0;

		// User info
		$user_id = ! empty( $args['user_id'] ) ? $args['user_id'] : get_current_user_id();

		// Tips amount
		$tips       = wpj_json_decode( wpj_stripslashes( $order->tips ) );
		$tip_amount = $tips[$tips_id]->amount;

		if ( ! is_numeric( $tip_amount ) ) $tip_amount = 0;

		$tip_amount_exchanged = wpj_number_format_special_exchange( $tip_amount, '1', $currency );

		// Date info
		$added_on = ! empty( $args['added_on'] ) ? $args['added_on'] : current_time( 'timestamp', 1 );

		// Buyer Fee
		$processing_fees = ! empty( $args['processing_fees'] ) ? $args['processing_fees'] : '';

		if ( ! $processing_fees )
			$processing_fees = wpj_get_site_processing_fee_by_amount( $tip_amount, 0, 0 );

		$processing_fees_exchanged = wpj_number_format_special_exchange( $processing_fees, '1', $currency );

		// Tax
		$tax = ! empty( $args['tax'] ) ? $args['tax'] : '';

		if ( ! $tax )
			$tax = wpj_get_site_tax_by_amount( $tip_amount, 0, 0, $processing_fees );

		$tax_exchanged = wpj_number_format_special_exchange( $tax, '1', $currency );

		// Final order price
		$payable_amount = ! empty( $args['payable_amount'] ) ? $args['payable_amount'] : '';

		if ( ! $payable_amount )
			$payable_amount = $tip_amount + $tax + $processing_fees;

		$payable_amount_exchanged = $tip_amount_exchanged + $processing_fees_exchanged + $tax_exchanged;

		// Decrease credits if payment method is Account Balance
		if ( $payment_gateway == 'credits' ) {
			$user_credit = wpj_get_user_credit( $user_id );

			if ( $payable_amount > $user_credit ) {
				wp_redirect( wpj_get_payment_link() . 'topup?no_credits=1' ); exit;
			}

			wpj_update_user_credit( $user_id, $user_credit - $payable_amount );
		}

		// Insert order to database
		$tips_order_id = wpj_insert_tips_order(
			[
				'order_id'             => $order->id,
				'tips_id'              => $tips_id,
				'user_id'              => $user_id,
				'tips_amount'          => $tip_amount,
				'added_on'             => $added_on,
				'payment_status'       => $payment_status,
				'payment_gateway_name' => $payment_gateway,
				'tax'                  => $tax_exchanged,
				'payable_amount'       => $payable_amount_exchanged,
				'currency'             => $currency,
			],
			['%d', '%d', '%d', '%f', '%d', '%s', '%s', '%f', '%f', '%s']
		);

		do_action( 'wpj_after_insert_tips_order', $tips_order_id );

		// Insert payment to database
		wpj_insert_payment(
			[
				'payment_status'         => $payment_status == 'completed' ? 1 : 0,
				'payment_gateway'        => $payment_gateway,
				'payment_type'           => 'tips',
				'payment_type_id'        => $tips_order_id,
				'fees'                   => $processing_fees,
				'amount'                 => $tip_amount,
				'datemade'               => current_time( 'timestamp', 1 ),
				'tax'                    => $tax,
				'currency'               => wpj_get_site_default_currency(),
				'final_amount'           => $payable_amount,
				'final_amount_exchanged' => $payable_amount_exchanged,
				'final_amount_currency'  => $currency,
			],
			['%d', '%s', '%s', '%d', '%f', '%f', '%d', '%f', '%s', '%f', '%f', '%s']
		);

		return $tips_order_id;
	}
}

if ( ! function_exists( 'wpj_add_new_tip' ) ) {
	function wpj_add_new_tip( $oid = '', $reason = '', $uid = '', $amount = '' ) {
		if ( ! is_demo_user() && is_user_logged_in() ) {
			$oid     = WPJ_Form::post( 'oid', $oid );
			$user_id = WPJ_Form::post( 'user', $uid );
			$amount  = WPJ_Form::post( 'tips_amount', $amount );
			$reason  = trim( nl2br( strip_tags( htmlspecialchars( wpj_encode_emoji( WPJ_Form::post( 'tips_reason', $reason ) ) ) ) ) );

			if ( ! $oid ) $oid = get_query_var( 'oid' );

			if ( $oid ) {
				$order = wpj_get_job_order_by_id( $oid );

				if ( $order ) {

					if ( get_current_user_id() != $user_id ) {
						$msg = [
							'description' => __( 'Yo\'re not the buyer!', 'wpjobster' ),
							'cssClass'    => 'negative',
							'code'        => 'error'
						];

					} elseif ( ! $amount || ! is_numeric( $amount ) || $amount <= 0 ) {
						$msg = [
							'description' => __( 'Amount is wrong', 'wpjobster' ),
							'cssClass'    => 'negative',
							'code'        => 'error'
						];

					} else {
						$msg = [
							'description' => __( 'Your tips was successfully sent.', 'wpjobster' ),
							'cssClass'    => 'success',
							'code'        => 'success'
						];

						// Update tips
						$new_tips['reason']    = $reason;
						$new_tips['amount']    = $amount;
						$new_tips['time']      = current_time( 'timestamp', 1 );
						$new_tips['paid']      = false;
						$new_tips['cancelled'] = false;

						if ( ! $order->tips )
							$order->tips = [];
						else
							$order->tips = wpj_json_decode( wpj_stripslashes( $order->tips ) );

						array_push( $order->tips, $new_tips );

						wpj_update_order_meta( $order->id, 'tips', json_encode( $order->tips ) );

						$count = count( $order->tips ) - 1;

						// Insert notification
						$this_notification = wpj_insert_order_notification( ['uid' => -36, 'oid' => $order->id, 'content' => $count], ['%d', '%d', '%s'] );

						// Send email
						if ( $this_notification > 0 )
							wpj_notify_user_translated( 'new_tips', $order->uid, ['##transaction_page_link##' => wpj_get_order_link( $order->id )] );

						$msg['oid']     = $order->id;
						$msg['tips_id'] = $count;
					}

					wp_send_json( $msg );
				}
			}
		}

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

if ( ! function_exists( 'wpj_cancel_tips' ) ) {
	function wpj_cancel_tips( $oid = '', $tips_id = '' ) {
		$oid     = WPJ_Form::post( 'oid', $oid );
		$tips_id = WPJ_Form::post( 'tips', $tips_id );

		if ( $oid && is_numeric( $tips_id ) ) {
			$order = wpj_get_job_order_by_id( $oid );

			if ( $order ) {
				if ( $order->uid == get_current_user_id() ) {
					$tips = wpj_json_decode( wpj_stripslashes( $order->tips ) );

					if ( $tips[$tips_id]->cancelled == false && $tips[$tips_id]->paid == false ) {
						// Update tips
						$tips[$tips_id]->cancelled = true;

						wpj_update_order_meta( $order->id, 'tips', json_encode( $tips ) );

						// Insert notification
						$this_notification = wpj_insert_order_notification( ['uid' => -38, 'oid' => $order->id, 'content' => $tips_id], ['%d', '%d', '%s'] );

						if ( $this_notification > 0 ) {
							// Update notifications
							wpj_update_user_notifications([
								'user1'       => $order->uid,
								'user2'       => get_post_field( 'post_author', $order->pid ),
								'type'        => 'notifications',
								'number'      => +1,
								'notify_id'   => $this_notification,
								'notify_type' => 'cancel_tips',
								'order_id'    => $order->id
							]);

							// Send email
							wpj_notify_user_translated( 'cancel_tips', $order->uid, ['##transaction_page_link##' => wpj_get_order_link( $order->id )] );

							// Update tips order
							wpj_update_tips_order( ['payment_status' => 'cancelled'], ['order_id' => $order->id, 'tips_id' => $tips_id] );
						}
					}
				}
			}
		}

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