<?php
namespace QuizPress;

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

use QuizPress\Admin\Settings;

class Migration {

	public static function init() {
		$self = new self();
		add_action( 'admin_init', [ $self, 'run_migration' ] );
	}

	public function run_migration() {
        $quizpress_version = get_option( 'quizpress_version' );
		// Save Version Number, flash role management and save permalink
		if ( QUIZPRESS_VERSION !== $quizpress_version ) {
			// Settings::save_settings();
			update_option( 'quizpress_version', QUIZPRESS_VERSION );
			update_option( 'quizpress_flash_role_management', true );
			update_option( 'quizpress_required_rewrite_flush', Helper::get_time() );
		}
		// Flash Role
		if ( get_option( 'quizpress_flash_role_management' ) ) {
			$Installer = new Installer();
			$Installer->add_role();
			delete_option( 'quizpress_flash_role_management' );
		}
		// migration question_explanation
		$this->migrate_add_question_explanation_column( $quizpress_version );

	}

	public function migrate_add_question_explanation_column( $quizpress_version ) {
		if ( ! version_compare( $quizpress_version, '1.2', '<=' ) ) {
			return;
		}
		global $wpdb;

		$table_name = $wpdb->prefix . 'quizpress_questions';

		// Check if column exists
		$column_exists = $wpdb->get_results(
			$wpdb->prepare(
				"SHOW COLUMNS FROM `$table_name` LIKE %s",
				'question_explanation'
			)
		);

		// If column does not exist → add it
		if ( empty( $column_exists ) ) {
			$wpdb->query(
				"ALTER TABLE `$table_name`
				ADD `question_explanation` LONGTEXT NULL 
				AFTER `question_content`"
			);
		}
	}

}
