<?php
/**
 * Handles the Apple Pay sale response.
 *
 * @package flo-checkout
 */

namespace Flo_Checkout\Gateways\Apple_Pay\Responses;

use Exception;
use Flo_Checkout\Gateways\Shift4_APM\Responses\Abstract_Response_Gateway_Payment;
use WC_Data_Exception;

defined( 'ABSPATH' ) || exit;

/**
 * Class Apple_Pay_Sale_Response
 */
class Apple_Pay_Sale_Response extends Abstract_Response_Gateway_Payment {

	/**
	 * {@inheritDoc}
	 */
	public function process(): Apple_Pay_Sale_Response {
		parent::process();

		return $this->update_order();
	}


	/**
	 * Update order.
	 *
	 * @return self
	 *
	 * @throws WC_Data_Exception If attempting to set invalid transaction ID.
	 * @throws Exception If the paid amount does not match order total.
	 */
	protected function update_order(): self {
		$this->order->set_transaction_id( $this->payment_response->transaction_id );
		$this->order->add_order_note(
			__( 'Payment processed.', 'flo-checkout-plugin' ) . '<br>' .
			__( 'Payment method', 'flo-checkout-plugin' ) . ': ' . $this->payment_response->payment_method->get_name() . '<br>' .
			__( 'Request ID', 'flo-checkout' ) . ': ' . $this->payment_response->request_id . '<br>' .
			__( 'Transaction ID', 'flo-checkout' ) . ': ' . $this->payment_response->transaction_id . '<br>' .
			__( 'Transaction time', 'flo-checkout' ) . ': ' . $this->payment_response->transaction_time . '<br>' .
			__( 'Card', 'flo-checkout' ) . ': ' . $this->payment_response->payment_details->card_type . ' ' . $this->payment_response->payment_details->pan . ' ' . $this->payment_response->payment_details->cardholder_name . '<br>' .
			__( 'Card holder', 'flo-checkout' ) . ': ' . $this->payment_response->payment_details->cardholder_name . '<br>' .
			__( 'Amount', 'flo-checkout' ) . ': ' . $this->payment_response->amount->get_display_amount()
		);

		/**
		 * Function get_total() actually returns a string, so we need to cast it to float.
		 *
		 * @noinspection PhpCastIsUnnecessaryInspection
		 */
		if ( floatval( $this->order->get_total() ) !== ( $this->payment_response->amount->get_amount() ) ) {
			$this->order->add_order_note(
				sprintf(
				/* translators: %s: paid amount */
					__( 'Order total does not match paid amount. Paid amount: %s.', 'flo-checkout-plugin' ),
					( $this->payment_response->amount->get_display_amount() )
				)
			);
			$this->log_and_throw_error(
				__( "Paid amount doesn't match order total. Please contact us.", 'flo-checkout-plugin' ),
				array(
					'order_total' => $this->order->get_total(),
					'amount'      => $this->payment_response->amount->get_display_amount(),
				)
			);
		}

		$this->order->update_meta_data( self::ORDER_META_RESPONSE, wp_json_encode( $this->payment_response ) );
		$this->order->update_meta_data( self::ORDER_META_REFUND_LINK, $this->payment_response->get_refund_link() );
		$this->order->save();

		return $this;
	}
}
