<?php
declare(strict_types=1);
/**
 * File responsible for Controller methods that handle migrations.
 *
 * Author: Uriahs Victor
 * Created on: 23/10/2025 (d/m/y)
 *
 * @link    https://uriahsvictor.com
 * @package \MigrationsController
 * @since   1.5.0
 */

namespace Printus\Controllers\Migrations;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class which defines methods that handle migrations.
 *
 * @package \Printus\Controllers\Migrations\MigrationsController
 * @since   1.5.0
 */
final class MigrationsController {

	private const MIGRATIONS_OPTION = 'printus_migrations_version';

	/**
	 * Migrations to perform based on the current migrations version.
	 *
	 * @return void
	 * @since 1.6.0
	 */
	public function performMigrations(): void {

		$current = (string) get_option( self::MIGRATIONS_OPTION, '0.0.0' );

		if ( version_compare( $current, '1.5.0', '<' ) ) {
			$this->migrateV1_5_0();
			update_option( self::MIGRATIONS_OPTION, '1.5.0', true );
			$current = '1.5.0';
		}

		if ( version_compare( $current, '1.6.0', '<' ) ) {
			$this->migrateV1_6_0();
			update_option( self::MIGRATIONS_OPTION, '1.6.0', true );
			$current = '1.6.0';
		}
	}

	private function migrateV1_5_0(): void {
		$this->addProcessPrintImmediatelyOption();
	}

	private function migrateV1_6_0(): void {
		$this->migratePrintTriggers();
	}

	/**
	 * Add the default setting for the "Process Prints Immediately" option.
	 *
	 * @return void
	 * @since 1.5.0
	 */
	private function addProcessPrintImmediatelyOption(): void {

		$printus_options = get_option( 'printus_config_settings', array() );

		// Already set no need to continue.
		if ( array_key_exists( 'general_settings_plugin_settings_section_process-prints-immediately', $printus_options ) ) {
			return;
		}

		$printus_options['general_settings_plugin_settings_section_process-prints-immediately'] = 1;

		update_option( 'printus_config_settings', $printus_options );
	}

	/**
	 * Migrate the print trigger option from the old plugin expected setting to the new one.
	 *
	 * @return void
	 * @since 1.6.0
	 */
	private function migratePrintTriggers(): void {

		$printus_options = get_option( 'printus_config_settings', array() );

		$current_trigger = $printus_options['general_settings_plugin_settings_section_print-trigger'] ?? '';

		if ( empty( $current_trigger ) ) {
			return;
		}

		if ( $current_trigger === 'checkout_complete' ) {
			$printus_options['general_settings_plugin_settings_section_print-trigger'] = 'order_processing';
		} elseif ( $current_trigger === 'payment_complete' ) {
			$printus_options['general_settings_plugin_settings_section_print-trigger'] = 'order_processing';
		}

		update_option( 'printus_config_settings', $printus_options );
	}
}
