<?php class WPJ_Tips {

	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_tips_payment_success', [$this, 'process'], 10, 5 );
		add_action( 'wpjobster_tips_payment_failed',  [$this, 'failed'],  10, 5 );
		add_action( 'wpjobster_tips_payment_other',   [$this, 'other'],   10, 6 );
	}

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

		// Insert tips to database
		$oid = wpj_insert_tips_purchase_order( ['payment_gateway' => $payment_gateway] );

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

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

		// Return
		return $order;
	}

	public function process( $oid, $payment_gateway = '', $details = '', $response = '', $redirect = 'yes' ) {
		// Get current order
		$tips_order = wpj_get_tips_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 = $tips_order->order_id;

		// Start the payment process
		if ( isset( $tips_order->payment_status ) && $tips_order->payment_status != 'completed' ) {
			// Insert notification
			$this_notification = wpj_insert_order_notification( ['uid' => -37, '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  = $tips_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' => 'tips_paid_new',
					'order_id'    => $parent_order_id
				]);

				// Get tips
				$tips = wpj_json_decode( wpj_stripslashes( $parent_order_details->tips ) );
				$tip  = $tips[$tips_order->tips_id];

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

				// Save log for buyer
				$reason = __( 'Tips', 'wpjobster' ) . ': <a href="' . get_permalink( $parent_order_details->pid ) . '">' . $parent_order_details->job_title . $tip->reason . '</a>';

				wpj_add_history_log([
					'tp'        => '0',
					'reason'    => $reason,
					'amount'    => $tip->amount,
					'uid'       => $buyer_id,
					'oid'       => $parent_order_id,
					'rid'       => 24,
					'details'   => $tips_order->tips_id,
					'payed_amt' => $currency . '|' . wpj_number_format_special_exchange( $tip->amount, 1, $currency )
				]);

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

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

					wpj_add_history_log([
						'tp'        => '0',
						'reason'    => $reason,
						'amount'    => $processing_fees,
						'uid'       => $buyer_id,
						'oid'       => $parent_order_id,
						'rid'       => 22,
						'details'   => $tips_order->tips_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( $tip->amount, 0, 0, $processing_fees );

				if ( $tax ) {
					$reason = __( 'Tax for tips', 'wpjobster' ) . ': <a href="' . get_permalink( $parent_order_details->pid ) . '">' . $parent_order_details->job_title . $tip->reason . '</a>';

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

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

				wpj_add_history_log([
					'tp'        => '2',
					'reason'    => $reason,
					'amount'    => $tip->amount,
					'uid'       => $seller_id,
					'oid'       => $parent_order_id,
					'rid'       => 25,
					'details'   => $tips_order->tips_id,
					'payed_amt' => $currency . '|' . wpj_number_format_special_exchange( $tip->amount, 1, $currency )
				]);

				// Send emails
				wpj_notify_user_translated( 'tips_paid_new', $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 ) )
				]);

				// Update custom extra inside order
				$tips[$tips_order->tips_id]->paid = true;

				if ( $processing_fees )
					$tips[$tips_order->tips_id]->processing_fees = $processing_fees;

				if ( $tax )
					$tips[$tips_order->tips_id]->tax = $tax;

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

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

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

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

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

	public function failed( $oid, $payment_gateway = '', $details = '', $response = '', $redirect = 'yes' ) {
		// Get tips order
		$tips_order = wpj_get_tips_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' => 'tips']
		);

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

		// Actions
		do_action( 'wpj_after_order_is_cancelled', $oid, 'tips' );
		do_action( 'wpj_tips_payment_failed', $oid );

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

	public function other( $oid, $payment_gateway = '', $details = '', $response = '', $status = 'processing', $redirect = 'yes' ) {
		// Get tips order
		$tips_order = wpj_get_tips_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' => 'tips']
		);

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

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

		// Redirect
		$this->redirect( $redirect, $tips_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( 'tips' ) );
			else
				wp_redirect( wpj_get_order_link_by_payment_type( 'tips', $oid ) );

			exit;
		}
	}

}