<?php
/**
 * Plugin upgrade class.
 *
 * @package flo-checkout
 */

namespace Flo_Checkout;

use Flo_Checkout\Gateways\NMI_Pay;

defined( 'ABSPATH' ) || exit;

/**
 * Plugin upgrade class.
 */
class Plugin_Upgrade {

	/**
	 * Setup shared hooks.
	 *
	 * @param string $service_name_underscored The service name in underscored format.
	 */
	public static function setup_shared_hooks( string $service_name_underscored ): void {
		add_filter(
			'northmill_online_shared_upgrades_' . $service_name_underscored,
			array( self::class, 'get_upgrades' )
		);
	}

	/**
	 * Get all upgrades.
	 * Hooked to Shared filter 'northmill_online_shared_upgrades'.
	 *
	 * @param array $upgrades Current upgrades to filter.
	 *
	 * @return array
	 */
	public static function get_upgrades( array $upgrades ): array {
		$shared = Shared::instance();

		/**
		 * Upgrade to 2.2.0
		 * - Fix spelling of NMI order meta.
		 */
		$upgrades['2.2.0'] = function ( bool $is_new_install ) use ( $shared ) {
			$shared->cron->check_event_statuses();

			if ( $is_new_install ) {
				return;
			}

			/**
			 * Fix spelling of order meta.
			 *
			 * @noinspection SpellCheckingInspection -- It's a spelling fix.
			 */
			$old_meta_key = '_nmi_payment_page_proccess';

			$orders = wc_get_orders( array( 'meta_key' => $old_meta_key ) );
			foreach ( $orders as $order ) {
				$order->update_meta_data( NMI_Pay::ORDER_META_PROCESSED, NMI_Pay::ORDER_META_PROCESSED_VALUE );
				$order->delete_meta_data( $old_meta_key );
				$order->save();
			}
		};

		return $upgrades;
	}
}
