<?php class WPJ_Custom_Extra {

	private $payment_gateway;

	public function __construct( $payment_gateway = '' ) {
		if ( ! $payment_gateway ) $this->payment_gateway = WPJ_Form::get( 'pay_for_item' );
		else $this->payment_gateway = $payment_gateway;

		add_action( 'wpjobster_custom_extra_payment_success', [$this, 'process'], 10, 5 );
		add_action( 'wpjobster_custom_extra_payment_failed',  [$this, 'failed'],  10, 5 );
		add_action( 'wpjobster_custom_extra_payment_other',   [$this, 'other'],   10, 6 );
	}

	public function insert( $payment_gateway = '' ) {
		// Get payment gateway
		if ( ! $payment_gateway ) $payment_gateway = $this->payment_gateway;

		// Insert custom extra to database
		$oid = wpj_insert_custom_extra_purchase_order( ['payment_gateway' => $payment_gateway] );

		// Get the new order data
		$order = wpj_get_custom_extra_order( '*', ['id' => $oid], 'row' );

		// Action
		do_action( 'wpj_after_new_custom_extra_order', $order );

		// Return
		return $order;
	}

	public function process( $oid, $payment_gateway = '', $details = '', $response = '', $redirect = 'yes' ) {
		// Get custom extra order
		$custom_extra_order = wpj_get_custom_extra_order( '*', ['id' => $oid], 'row' );

		// Get payment gateway
		if ( ! $payment_gateway ) $payment_gateway = $this->payment_gateway;

		// Get details
		if ( ! $details ) $details = $payment_gateway;

		// Get parent order ID
		$parent_order_id = $custom_extra_order->order_id;

		// Start the payment process
		if ( isset( $custom_extra_order->payment_status ) && $custom_extra_order->payment_status != 'completed' ) {
			// Insert notification
			$this_notification = wpj_insert_order_notification( ['uid' => -34, 'oid' => $parent_order_id, 'content' => $oid], ['%d', '%d', '%s'] );

			if ( $this_notification > 0 ) {
				// Get parent order data
				$parent_order_details = wpj_get_job_order_by_id( $parent_order_id );

				// Get users IDs
				$buyer_id  = $custom_extra_order->user_id;
				$seller_id = get_post_field( 'post_author', $parent_order_details->pid );

				// Update notification
				wpj_update_user_notifications([
					'user1'       => $seller_id,
					'user2'       => $buyer_id,
					'type'        => 'notifications',
					'number'      => +1,
					'notify_id'   => $this_notification,
					'notify_type' => 'custom_extra_paid_new',
					'order_id'    => $parent_order_id
				]);

				// Get custom extra
				$custom_extras = wpj_json_decode( wpj_stripslashes( $parent_order_details->custom_extras ) );
				$custom_extra  = $custom_extras[$custom_extra_order->custom_extra_id];

				// Currency
				$currency = $custom_extra_order->currency;

				// Add delivery days to main order
				wpj_update_expected_delivery_add_days( $parent_order_details, $custom_extra->delivery );

				// Save log for buyer
				$reason = apply_filters( 'wpj_custom_extra_string_with_dots_filter', __( 'Custom extra:', 'wpjobster' ) ) . '&nbsp;<a href="' . get_permalink( $parent_order_details->pid ) . '">' . $custom_extra->description . '</a>';

				wpj_add_history_log([
					'tp'        => '0',
					'reason'    => $reason,
					'amount'    => $custom_extra->price,
					'uid'       => $buyer_id,
					'oid'       => $parent_order_id,
					'rid'       => 18,
					'details'   => $custom_extra_order->custom_extra_id,
					'payed_amt' => $currency . '|' . wpj_number_format_special_exchange( $custom_extra->price, 1, $currency )
				]);

				// Save fee log for buyer
				$processing_fees = wpj_get_site_processing_fee_by_amount( $custom_extra->price, 0, 0 );

				if ( $processing_fees ) {
					$reason = __( 'Processing fee for custom extra', 'wpjobster' ) . ': <a href="' . get_permalink( $parent_order_details->pid ) . '">' . $custom_extra->description . '</a>';

					wpj_add_history_log([
						'tp'        => '0',
						'reason'    => $reason,
						'amount'    => $processing_fees,
						'uid'       => $buyer_id,
						'oid'       => $parent_order_id,
						'rid'       => 16,
						'details'   => $custom_extra_order->custom_extra_id,
						'payed_amt' => $currency . '|' . wpj_number_format_special_exchange( $processing_fees, 1, $currency )
					]);
				}

				// Save tax log for buyer
				$tax = wpj_get_site_tax_by_amount( $custom_extra->price, 0, 0, $processing_fees );

				if ( $tax ) {
					$reason = __( 'Tax for custom extra', 'wpjobster' ) . ': <a href="' . get_permalink( $parent_order_details->pid ) . '">' . $custom_extra->description . '</a>';

					wpj_add_history_log([
						'tp'        => '0',
						'reason'    => $reason,
						'amount'    => $tax,
						'uid'       => $buyer_id,
						'oid'       => $parent_order_id,
						'rid'       => 17,
						'details'   => $custom_extra_order->custom_extra_id,
						'payed_amt' => $currency . '|' . wpj_number_format_special_exchange( $tax, 1, $currency )
					]);
				}

				// Save collected log for seller
				$reason = __( 'Payment collected for custom extra', 'wpjobster' ) . ': <a href="' . get_permalink( $parent_order_details->pid ) . '">' . $custom_extra->description . '</a>';

				wpj_add_history_log([
					'tp'        => '2',
					'reason'    => $reason,
					'amount'    => $custom_extra->price,
					'uid'       => $seller_id,
					'oid'       => $parent_order_id,
					'rid'       => 19,
					'details'   => $custom_extra_order->custom_extra_id,
					'payed_amt' => $currency . '|' . wpj_number_format_special_exchange( $custom_extra->price, 1, $currency )
				]);

				// Update custom extra inside order
				$custom_extras[$custom_extra_order->custom_extra_id]->paid = true;

				if ( $processing_fees )
					$custom_extras[$custom_extra_order->custom_extra_id]->processing_fees = $processing_fees;

				if ( $tax )
					$custom_extras[$custom_extra_order->custom_extra_id]->tax = $tax;

				wpj_update_order_meta( $parent_order_id, 'custom_extras', json_encode( $custom_extras ) );

				// Send emails
				wpj_notify_user_translated( apply_filters( 'wpj_custom_extra_paid_new_reason_filter', 'custom_extra_paid_new', $parent_order_id ), $buyer_id, [
					'##sender_username##'       => wpj_get_user_display_type( $seller_id ),
					'##transaction_number##'    => wpj_camouflage_oid( $parent_order_details->id, $parent_order_details->date_made ),
					'##transaction_page_link##' => wpj_get_order_link( $parent_order_id ),
					'##job_name##'              => $parent_order_details->job_title,
					'##job_link##'              => urldecode( get_permalink( $parent_order_details->pid ) )
				]);

				wpj_notify_user_translated( apply_filters( 'wpj_custom_extra_paid_new_seller_reason_filter', 'custom_extra_paid_new_seller', $parent_order_id ), $seller_id, [
					'##sender_username##'       => wpj_get_user_display_type( $buyer_id ),
					'##transaction_number##'    => wpj_camouflage_oid( $parent_order_details->id, $parent_order_details->date_made ),
					'##transaction_page_link##' => wpj_get_order_link( $parent_order_id ),
					'##job_name##'              => $parent_order_details->job_title,
					'##job_link##'              => urldecode( get_permalink( $parent_order_details->pid ) )
				]);

				wpj_notify_user_translated( 'custom_extra_paid_admin_new', 'admin', [
					'##username##'              => wpj_get_user_display_type( $buyer_id ),
					'##transaction_page_link##' => wpj_get_order_link( $parent_order_id )
				]);

				// Update payment
				wpj_update_payment(
					['payment_status' => 'completed', 'payment_details' => $details, 'payment_response' => $response],
					['payment_type_id' => $oid, 'payment_type' => 'custom_extra']
				);

				// Update order
				wpj_update_custom_extra_order(
					['payment_status' => 'completed', 'paid_on' => current_time( 'timestamp', 1 ), 'payment_gateway_transaction_id' => $details, 'payment_response' => $response],
					['id' => $oid]
				);

				// Action
				do_action( 'wpj_custom_extra_payment_completed', $oid );
			}
		}

		// Redirect
		$this->redirect( $redirect, $parent_order_id );
	}

	public function failed( $oid, $payment_gateway = '', $details = '', $response = '', $redirect = 'yes' ) {
		// Get custom extra order
		$custom_extra_order = wpj_get_custom_extra_order( 'order_id', ['id' => $oid], 'row' );

		// Get payment gateway
		if ( ! $payment_gateway ) $payment_gateway = $this->payment_gateway;

		// Get details
		if ( ! $details ) $details = $payment_gateway;

		// Update payment
		wpj_update_payment(
			['payment_status' => 'cancelled', 'payment_details' => $details, 'payment_response' => $response],
			['payment_type_id' => $oid, 'payment_type' => 'custom_extra']
		);

		// Update order
		wpj_update_custom_extra_order(
			['payment_status' => 'cancelled', 'paid_on' => current_time( 'timestamp', 1 ), 'payment_gateway_transaction_id' => $details, 'payment_response' => $response],
			['id' => $oid]
		);

		// Cancel custom extra
		if ( $payment_gateway == 'banktransfer' )
			wpj_cancel_custom_extra( $custom_extra_order->order_id, $oid );

		// Actions
		do_action( 'wpj_after_order_is_cancelled', $oid, 'custom_extra' );
		do_action( 'wpj_custom_extra_payment_failed', $oid );

		// Redirect
		$this->redirect( $redirect, $custom_extra_order->order_id );
	}

	public function other( $oid, $payment_gateway = '', $details = '', $response = '', $status = 'processing', $redirect = 'yes' ) {
		// Get custom extra order
		$custom_extra_order = wpj_get_custom_extra_order( 'order_id', ['id' => $oid], 'row' );

		// Get payment gateway
		if ( ! $payment_gateway ) $payment_gateway = $this->payment_gateway;

		// Get details
		if ( ! $details ) $details = $payment_gateway;

		// Update payment
		wpj_update_payment(
			['payment_status' => $status, 'payment_details' => $details, 'payment_response' => $response],
			['payment_type_id' => $oid, 'payment_type' => 'custom_extra']
		);

		// Update order
		wpj_update_custom_extra_order(
			['payment_status' => $status, 'paid_on' => current_time( 'timestamp', 1 ), 'payment_gateway_transaction_id' => $details, 'payment_response' => $response],
			['id' => $oid]
		);

		// Action
		do_action( 'wpjobster_custom_extra_payment_other', $oid );

		// Redirect
		$this->redirect( $redirect, $custom_extra_order->order_id );
	}

	private function redirect( $redirect = 'yes', $oid = 0 ) {
		if ( $redirect == 'yes' ) {
			if ( isset( $_SERVER['HTTP_REFERER'] ) && strpos( $_SERVER['HTTP_REFERER'], 'page=jobster-orders' ) && strpos( $_SERVER['HTTP_REFERER'], 'admin.php' ) )
				wp_redirect( wpj_get_admin_order_link( 'custom_extra' ) );
			else
				wp_redirect( wpj_get_order_link_by_payment_type( 'custom_extra', $oid ) );

			exit;
		}
	}

}