<?php
/**
 * Class responsible for database migrations.
 */

namespace BoostsiteAIContentGenerator;

/**
 * Migrations class.
 *
 * @class Migrations single point of entry for database migration
 */
final class Migrations {
	/**
	 * The database charset.
	 *
	 * @var string
	 */
	private $db_charset = 'utf8';

	/**
	 * The database collate.
	 *
	 * @var string
	 */
	private $db_collate = 'utf8_general_ci';

	/**
	 * Run the migration.
	 *
	 * @param  string $prefix          application prefix.
	 * @param  string $current_version the current version.
	 * @return Migrations
	 */
	public function run( $prefix, $current_version ) {
		if ( ! current_user_can( 'activate_plugins' ) ) {
			return;
		}

		// Explicitly set the character set and collation when creating the tables.
		$this->db_charset = ( defined( 'DB_CHARSET' && '' !== DB_CHARSET ) ) ? DB_CHARSET : 'utf8';
		$this->db_collate = ( defined( 'DB_COLLATE' && '' !== DB_COLLATE ) ) ? DB_COLLATE : 'utf8_general_ci';

		$last_version = get_option( $prefix . '_last_migrated_version', '0.0.0' );

		if ( version_compare( $last_version, $current_version, '>=' ) ) {
			return;
		}

		$this->apply_migration( $last_version, '0.0.0', 'migration_0_0_0' );

		update_option( $prefix . '_last_migrated_version', $current_version );

		return $this;
	}

	/**
	 * Function that help apply application migration.
	 *
	 * @param  string $last_version    the migrated version.
	 * @param  string $apply_version   the migration to apply version.
	 * @param  string $migration_func the migration function.
	 * @return void
	 */
	public function apply_migration( $last_version, $apply_version, $migration_func ) {
		if ( version_compare( $last_version, $apply_version, '>=' ) ) {
			return;
		}

		call_user_func( array( $this, $migration_func ) );
	}

	/**
	 * Database cleanup to run during plugin uninstall.
	 *
	 * @param  string $prefix database prefix.
	 * @return void
	 */
	public function clean_up( $prefix ) {
		// remove options.
		delete_option( $prefix . '_last_migrated_version' );
		delete_option( $prefix . '_settings' );
	}

	/**
	 * DB Migration for v0.0.0.
	 *
	 * @return void
	 */
	public function migration_0_0_0() {
		// dummy method to demonstrate migration.
	}
}
