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

namespace Lpac_DPS\Controllers\Migrations;

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

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

	private const MIGRATIONS_OPTION = 'chwazi_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.4', '<' ) ) {
			$this->migrateV1_5_4();
			update_option( self::MIGRATIONS_OPTION, '1.5.4', true );
			$current = '1.5.4';
		}
	}

	private function migrateV1_5_4(): void {
		$this->migrateOffDays();
	}

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

		$chwazi_options = get_option( 'lpac_dps', array() );

		$pickup_off_days             = $chwazi_options['pickup_off_days__repeater'];
		$new_pickup_option_structure = array();
		foreach ( $pickup_off_days as $pickup_off_day ) {

			// This is only present in new Off Days feature.
			if ( array_key_exists( 'off_days__notice_text', $pickup_off_day ) ) {
				return;
			}

			$new_pickup_option_structure[] = array(
				'off_days__dates'       => array(
					'from' => $pickup_off_day['off_days__date'] . ' ' . '00:00',
					'to'   => $pickup_off_day['off_days__date'] . ' ' . '24:00',
				),
				'off_days__notice_text' => 'We will be closed during that time, please try another date.',
			);
		}
		$chwazi_options['pickup_off_days__repeater'] = $new_pickup_option_structure;

		// ---

		$delivery_off_days             = $chwazi_options['delivery_off_days__repeater'];
		$new_delivery_option_structure = array();
		foreach ( $delivery_off_days as $delivery_off_day ) {

			if ( array_key_exists( 'off_days__notice_text', $delivery_off_day ) ) {
				return;
			}

			$new_delivery_option_structure[] = array(
				'off_days__dates'       => array(
					'from' => $delivery_off_day['off_days__date'] . ' ' . '00:00',
					'to'   => $delivery_off_day['off_days__date'] . ' ' . '24:00',
				),
				'off_days__notice_text' => 'We will be closed during that time, please try another date.',
			);
		}
		$chwazi_options['delivery_off_days__repeater'] = $new_delivery_option_structure;

		update_option( 'lpac_dps', $chwazi_options );
	}
}
