<?php
/**
 * Class ShipmentTemplatePostTypeMigration
 *
 * @package DhlPolska\ShipmentTemplates
 */

namespace DhlPolska\ShipmentTemplates;

use DhlPolskaVendor\WPDesk\PluginBuilder\Plugin\Hookable;

/**
 * Migrates legacy shipment template post type to the current one.
 */
class ShipmentTemplatePostTypeMigration implements Hookable {
	public const LEGACY_POST_TYPE = 'dpd-polska-template';

	private const MIGRATION_OPTION = 'dhl_polska_shipment_template_post_type_migrated_v1';

	/**
	 * @return void
	 */
	public function hooks() {
		add_action( 'init', [ $this, 'run_migration_once' ] );
	}

	/**
	 * @return void
	 */
	public function run_migration_once(): void {
		if ( $this->is_migration_done() ) {
			return;
		}

		$wpdb = $this->get_wpdb();

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- One-time migration of legacy shipment template post type.
		$result = $wpdb->update(
			$wpdb->posts,
			[ 'post_type' => ShipmentTemplatePostType::POST_TYPE ],
			[ 'post_type' => self::LEGACY_POST_TYPE ],
			[ '%s' ],
			[ '%s' ]
		);

		if ( false === $result ) {
			return;
		}

		$this->mark_migration_done();
	}

	/**
	 * @return bool
	 */
	private function is_migration_done(): bool {
		return 'yes' === $this->get_option( self::MIGRATION_OPTION, 'no' );
	}

	/**
	 * @return void
	 */
	private function mark_migration_done(): void {
		$this->update_option( self::MIGRATION_OPTION, 'yes' );
	}

	/**
	 * @param string $option  .
	 * @param string $default .
	 *
	 * @return string
	 */
	protected function get_option( string $option, string $default ): string {
		return (string) get_option( $option, $default );
	}

	/**
	 * @param string $option .
	 * @param string $value  .
	 *
	 * @return bool
	 */
	protected function update_option( string $option, string $value ): bool {
		return (bool) update_option( $option, $value, false );
	}

	/**
	 * @return \wpdb
	 */
	protected function get_wpdb() {
		global $wpdb;

		return $wpdb;
	}
}
