<?php // CUSTOM EXTRA
if ( ! function_exists( 'wpj_insert_custom_extra_purchase_order' ) ) {
	function wpj_insert_custom_extra_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();

		// Custom extra id
		$custom_extra_id = isset( $args['custom_extra'] ) && is_numeric( $args['custom_extra'] ) ? $args['custom_extra'] : WPJ_Form::request( 'custom_extra' );
		if ( ! is_numeric( $custom_extra_id ) ) $custom_extra_id = 0;

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

		// Custom extra amount
		$custom_extra_amount = isset( $args['custom_extra_amount'] ) && is_numeric( $args['custom_extra_amount'] ) ? $args['custom_extra_amount'] : '';
		if ( ! is_numeric( $custom_extra_amount ) ) {
			$custom_extras       = wpj_json_decode( wpj_stripslashes( $order->custom_extras ) );
			$custom_extra_amount = $custom_extras[$custom_extra_id]->price;
		}
		if ( ! is_numeric( $custom_extra_amount ) ) $custom_extra_amount = 0;

		$custom_extra_amount_exchanged = wpj_number_format_special_exchange( $custom_extra_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( $custom_extra_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( $custom_extra_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 = $custom_extra_amount + $tax + $processing_fees;
		$payable_amount_exchanged = $custom_extra_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
		$ce_order_id = wpj_insert_custom_extra_order(
			[
				'order_id'             => $order->id,
				'custom_extra_id'      => $custom_extra_id,
				'user_id'              => $user_id,
				'custom_extra_amount'  => $custom_extra_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_custom_extra_order', $ce_order_id, $order->id );

		// Insert payment to database
		wpj_insert_payment(
			[
				'payment_status'         => $payment_status == 'completed' ? 1 : 0,
				'payment_gateway'        => $payment_gateway,
				'payment_type'           => 'custom_extra',
				'payment_type_id'        => $ce_order_id,
				'fees'                   => $processing_fees,
				'amount'                 => $custom_extra_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 $ce_order_id;
	}
}

if ( ! function_exists( 'wpj_insert_custom_extra_to_job_purchase_order' ) ) {
	function wpj_insert_custom_extra_to_job_purchase_order( $args = [] ) {
		$defaults = [
			'oid' => '',
			'content' => '',
			'price' => '',
			'delivery' => '',
			'initiator' => ''
		];

		$args = wp_parse_args( $args, $defaults );

		/**
		 * @var int $oid
		 * @var string $content
		 * @var float $price
		 * @var int $delivery
		 * @var int $initiator
		 */
		extract( $args );

		$msg = false;

		$order = wpj_get_job_order_by_id( $oid );

		if ( $order->uid == get_current_user_id() ) {
			$msg = wpj_get_custom_offer_status( 'something_wrong', true );

		} else {
			// Create custom extra meta data
			$custom_extra                = [];
			$custom_extra['description'] = $content;
			$custom_extra['price']       = $price;
			$custom_extra['delivery']    = $delivery;
			$custom_extra['time']        = current_time( 'timestamp', 1 );
			$custom_extra['paid']        = false;
			$custom_extra['declined']    = false;
			$custom_extra['cancelled']   = false;

			if ( ! $order->custom_extras ) {
				$order->custom_extras = [];

			} else {
				$order->custom_extras = wpj_json_decode( wpj_stripslashes( $order->custom_extras ) );

			}

			array_push( $order->custom_extras, $custom_extra );

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

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

			if ( $this_notification > 0 ) {
				// Update notifications
				wpj_update_user_notifications([
					'user1'       => $order->uid,
					'user2'       => $initiator,
					'type'        => 'notifications',
					'number'      => +1,
					'notify_id'   => $this_notification,
					'notify_type' => 'new_custom_extra',
					'order_id'    => $oid
				]);

				// Update custom extra meta
				wpj_update_order_meta( $oid, 'custom_extras', json_encode( $order->custom_extras ) );

				// Set message
				$msg = wpj_get_custom_offer_status( 'offer_sent', true );

				// Send email
				wpj_notify_user_translated( apply_filters( 'wpj_new_custom_extra_reason_filter', 'new_custom_extra', $oid ), $order->uid, [
					'##sender_username##'       => wpj_get_user_display_type( $initiator ),
					'##transaction_number##'    => wpj_camouflage_oid( $order->id, $order->date_made ),
					'##transaction_page_link##' => wpj_get_order_link( $oid ),
					'##job_name##'              => $order->job_title,
					'##job_link##'              => urldecode( get_permalink( $order->pid ) )
				] );
			}
		}

		return $msg;
	}
}

if ( ! function_exists( 'wpj_accept_custom_extra' ) ) {
	function wpj_accept_custom_extra( $oid = '', $custom_extra_id = '' ) {
		$oid   = WPJ_Form::post( 'oid', $oid );
		$ce_id = WPJ_Form::post( 'custom_extra', $custom_extra_id );

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

			if ( $order ) {
				if ( get_current_user_id() == get_post_field( 'post_author', $order->pid ) ) {
					$custom_extra_arr = wpj_get_custom_extra_order( '*', ['order_id' => $order->id, 'custom_extra_id' => $ce_id], 'row' );

					if ( $custom_extra_arr ) {
						if ( $custom_extra_arr->payment_gateway_name == 'cod' && $custom_extra_arr->payment_gateway_transaction_id == '-1' ) {
							wpj_update_custom_extra_order( ['payment_gateway_transaction_id' => ''], ['order_id' => $order->id, 'custom_extra_id' => $ce_id] );
						}
					}
				}
			}
		}

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

if ( ! function_exists( 'wpj_deny_custom_extra' ) ) {
	function wpj_deny_custom_extra( $oid = '', $custom_extra_id = '' ) {
		$oid   = WPJ_Form::post( 'oid', $oid );
		$ce_id = WPJ_Form::post( 'custom_extra', $custom_extra_id );

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

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

					if (
						$custom_extras[$ce_id]->cancelled == false
						&& $custom_extras[$ce_id]->declined == false
						&& $custom_extras[$ce_id]->paid == false
						&& wpj_is_order_completed( $order->id ) != 1
						&& $order->closed != 1
					) {
						$seller_id = get_post_field( 'post_author', $order->pid );

						// Update custom extra
						$custom_extras[$ce_id]->declined = true;

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

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

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

							// Send email
							wpj_notify_user_translated( apply_filters( 'wpj_decline_custom_extra_reason_filter', 'decline_custom_extra', $order->id ), $seller_id, [
								'##sender_username##'       => wpj_get_user_display_type( $order->uid ),
								'##transaction_number##'    => wpj_camouflage_oid( $order->id, $order->date_made ),
								'##transaction_page_link##' => wpj_get_order_link( $order->id ),
								'##job_name##'              => $order->job_title,
								'##job_link##'              => urldecode( get_permalink( $order->pid ) )
							]);
						}
					}
				}
			}
		}

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

if ( ! function_exists( 'wpj_cancel_custom_extra' ) ) {
	function wpj_cancel_custom_extra( $oid = '', $custom_extra_id = '' ) {
		$oid   = WPJ_Form::post( 'oid', $oid );
		$ce_id = WPJ_Form::post( 'custom_extra', $custom_extra_id );

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

			if ( $order ) {
				$seller_id = get_post_field( 'post_author', $order->pid );

				if ( strpos( $_SERVER['HTTP_REFERER'], 'admin.php' ) ) {
					wpj_notify_user_translated( 'custom_extra_cancelled_by_admin', $order->uid, [
						'##transaction_page_link##' => wpj_get_order_link( $order->id )
					]);

					wpj_notify_user_translated( 'custom_extra_cancelled_by_admin_seller', $seller_id, [
						'##transaction_page_link##' => wpj_get_order_link( $order->id )
					]);
				}

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

					if (
						$custom_extras[$ce_id]->cancelled == false
						&& $custom_extras[$ce_id]->declined == false
						&& $custom_extras[$ce_id]->paid == false
						&& wpj_is_order_completed( $order->id ) != 1
						&& $order->closed != 1
					) {
						// Update custom extra
						$custom_extras[$ce_id]->cancelled = true;

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

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

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

							// Send email
							wpj_notify_user_translated( apply_filters( 'wpj_cancel_custom_extra_reason_filter', 'cancel_custom_extra', $order->id ), $order->uid, [
								'##sender_username##'       => wpj_get_user_display_type( $order->uid ),
								'##transaction_number##'    => wpj_camouflage_oid( $order->id, $order->date_made ),
								'##transaction_page_link##' => wpj_get_order_link( $order->id ),
								'##job_name##'              => $order->job_title,
								'##job_link##'              => urldecode( get_permalink( $order->pid ) )
							]);
						}
					}
				}
			}
		}

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

// HELPERS

if ( ! function_exists( 'wpj_get_custom_extras_amount' ) ) {
	function wpj_get_custom_extras_amount( $row = '', $ret = '' ) {
		$total_amount = 0;
		$total_fees   = 0;
		$total_tax    = 0;

		if ( $row->custom_extras ) {
			$custom_extras = wpj_json_decode( wpj_stripslashes( $row->custom_extras ) );

			if ( $custom_extras ) {
				$i = 0;
				foreach ( $custom_extras as $custom_extra ) {
					if ( $custom_extra->paid ) {
						$custom_extra_ord = wpj_get_custom_extra_order( '*', ['order_id' => $row->id, 'custom_extra_id' => $i], 'row' );

						if ( $custom_extra_ord ) {
							$custom_extra_payment = wpj_get_payment(['payment_type' => 'custom_extra', 'payment_type_id' => $custom_extra_ord->id]);

							if ( $custom_extra_payment ) {
								$total_amount += $custom_extra_payment->amount;
								$total_fees   += $custom_extra_payment->fees;
								$total_tax    += $custom_extra_payment->tax;
							}
						}
					}
					$i++;
				}
			}
		}

		if ( $ret == 'amount' )
			return $total_amount;

		elseif ( $ret == 'fees' )
			return $total_fees;

		elseif ( $ret == 'tax' )
			return $total_tax;

		else
			return $total_amount + $total_fees + $total_tax;
	}
}