<?php
/**
 * This file handles Refund Notification
 *
 * @package WkwcAdyen
 * @version 1.2.0
 */
namespace WkwcAdyen\Helper\Adyen\Notifications;

defined( 'ABSPATH' ) || exit; // Exit if access directly.

use Exception;
use WC_Order;

/**
 * Adyen Refund Handler
 */
class Wkwc_Refund_Handler extends Wkwc_Abstract_Handler {
	/**
	 * Notification Request Object
	 *
	 * @param object DataObjects\Wkwc_Adyen_Notification_Request $notification_request .
	 *
	 * @return mixed|void
	 */
	public function handle( $notification_request ) {
		if ( ! $notification_request->success ) {
			return;
		}

		$order = new WC_Order( intval( $notification_request->merchant_reference ) );

		try {
			wc_create_refund(
				array(
					'amount'   => $notification_request->amount->value / 100,
					'reason'   => $notification_request->reason,
					'order_id' => $order->get_id(),
				)
			);
			/* translators: %s: is PSP Reference */
			$order->update_status( 'refunded', sprintf( __( 'Payment was refunded via WooCommerce Adyen Integration (PSP Reference: %s)', 'wkwc-adyen' ), $notification_request->psp_reference ) );
		} catch ( Exception $e ) {
			wkwc_adn_log( $e->getMessage() );
		}
	}
}
