<?php
/**
 * Order Handler
 */

namespace WkwcAdyen\Helper\Common;

use WkwcAdyen\Helper\Adyen\Wkwc_Adyen_Helper;

// prevent direct access data leaks
defined( 'ABSPATH' ) || exit;

class Wkwc_Adyen_Order_Handler {

	/**
	 * Wkwc_Adyen_Order_Handler constructor.
	 */
	public function __construct() {

	}

	/**
	 * Sets order according to the payment result.
	 *
	 * @object \WC_Order $order
	 * @param object $response - request response
	 * @return void
	 */
	public static function payment_result( \WC_Order $order, $response ) {
		$result_code = '';
		$statuses    = array(
			'Authorised' => 'complete',
			'Refused'    => 'failed',
			'Error'      => 'failed',
			'Cancelled'  => 'cancelled',
			'Pending'    => 'pending',
			'Received'   => 'on-hold',
		);

		if ( $response->status == 200 ) {
			$body_response  = Wkwc_Adyen_Helper::wkwc_adyen_obj_to_arr( $response->body );
			$result_code    = $body_response['resultCode'];
			$psp_reference  = $body_response['pspReference'];
			$status         = $statuses[ $result_code ];
			$redirect_url   = Wkwc_Adyen_Service_Util::get_return_page_url( $order, $result_code );
			$payment_method = str_replace( 'wkwc_adyen_', '', $order->get_payment_method() );

			if ( 'processing' === $status && Wkwc_Adyen_Service_Util::is_manual_payment( $payment_method ) ) {
				$status = 'on-hold';
			}

			if ( 'complete' === $status ) {

				if ( ! self::is_order_payment_completed( $order->get_id() ) ) {

					self::set_order_payment_completed( $order->get_id() );
					$order->payment_complete( $psp_reference );
					$order->add_order_note( sprintf( __( 'Order completed using %s .', 'wkwc-adyen' ), $order->get_payment_method_title() ) );

				}
			} elseif ( ! empty( $status ) ) {
				$order->set_transaction_id( $psp_reference );
				$order->set_status( $status );
			}

			if ( 'Error' === $result_code || 'Refused' === $result_code ) {

				$refusal_reason = $body_response['refusalReason'];

				if ( ! empty( $refusal_reason ) ) {

					$order->add_order_note( sprintf( __( 'The payment failed due to: %s', 'wkwc-adyen' ), $refusal_reason ) );

				}
			}

			if ( ! empty( $psp_reference ) ) {
				$order->read_meta_data();

				$order_psp_reference = $order->get_meta( '_' . WKWC_ADN_PREFIX . '_payment_pspReference' );

				if ( $order_psp_reference !== $psp_reference ) {

					$order->update_meta_data( '_' . WKWC_ADN_PREFIX . '_payment_pspReference', $psp_reference );

					if ( 'yes' === get_option( '_wkwc_adyen_immediate_capturing_enabled' ) ) {
						$order->update_meta_data( '_wkwc_adyen_payment_captured', 'yes' );
					}
				}
			}
		} else {
			$order->add_order_note( sprintf( __( 'The payment did not succeed. Request response: %s', 'wkwc-adyen' ), json_encode( $response->body ) ) );

			$redirect_url = $order->get_checkout_payment_url();
		}

		$order->save();

		$redirect_url = apply_filters( WKWC_ADN_PREFIX . '\order\payment_result', $redirect_url, $order, $result_code );

		wp_redirect( $redirect_url );
		exit;
	}

	/**
	 * Check if the order payment is completed
	 *
	 * @param $order_id
	 * @return bool
	 */
	public static function is_order_payment_completed( $order_id ) {

		$payment_completed = wp_cache_get( WKWC_ADN_PREFIX . '_order_' . $order_id . '_payment_completed', WKWC_ADN_PREFIX, true );

		if ( empty( $payment_completed ) ) {
			$payment_completed = get_transient( 'order_' . $order_id . '_payment_completed' );
		}

		if ( empty( $payment_completed ) ) {
			return false;
		}

		return is_bool( $payment_completed ) ? $payment_completed : ( 'yes' === strtolower( $payment_completed ) || 1 === $payment_completed || 'true' === strtolower( $payment_completed ) || '1' === $payment_completed );
	}

	/**
	 * Set order payment is completed
	 *
	 * @param $order_id
	 * @return void
	 */
	public static function set_order_payment_completed( $order_id ) {

		wp_cache_set( WKWC_ADN_PREFIX . '_order_' . $order_id . '_payment_completed', 'yes', WKWC_ADN_PREFIX, HOUR_IN_SECONDS );

		set_transient( 'order_' . $order_id . '_payment_completed', 'yes', HOUR_IN_SECONDS );

	}

}
