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

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

use Adyen\AdyenException;
use Adyen\Util\HmacSignature;

/**
 * Adyen Wkwc_Abstract_Handler Class
 */
abstract class Wkwc_Abstract_Handler {
	/**
	 * Verify Notification Merchant Credential
	 *
	 * @param object Wkwc_Adyen_Notification_Request $notification_item Notification data.
	 * @param string                                 $hmac_key hash-based message authentication code .
	 *
	 * @return bool
	 *
	 * @throws AdyenException .
	 */
	public function verify( $notification_item, $hmac_key ) {
		$hmac     = new HmacSignature();
		$is_valid = $hmac->isValidNotificationHMAC( $hmac_key, $notification_item->to_array() );

		wkwc_adn_log( 'HMAC key for verify: ' . $hmac_key . ' Is valid: ' . $is_valid . ' Notification data: ' . print_r( $notification_item->to_array(), true ) );

		return $is_valid;
	}

	/**
	 * Store Notification
	 *
	 * @param object Wkwc_Adyen_Notification_Request $notification_item Notification item.
	 */
	public function store( $notification_item ) {
		$order = wc_get_order( intval( $notification_item->merchant_reference ) );

		if ( ! $order->get_id() ) {
			return;
		}

		$adyen_notifications = $order->get_meta( '_adyen_notifications', true );

		if ( empty( $adyen_notifications ) ) {
			$adyen_notifications = $notification_item->to_array();
		} else {
			$adyen_notifications[] = $notification_item->to_array();
		}

		$order->update_meta_data( '_adyen_notifications', $adyen_notifications );
		$order->save();
	}

	/**
	 * Define Handler Method
	 *
	 * @param object Wkwc_Adyen_Notification_Request $notification_request Notification request.
	 *
	 * @return mixed
	 */
	abstract public function handle( $notification_request );
}
