<?php

class Database {
	public function __construct () {
		$this->update();
	}

	public function update_error_notice () {
		?>
			<div class="notice notice-error is-dismissible">
				<p><?php _e( 'Database Update Error', 'bw-survey' ); ?></p>
				<pre><?php echo htmlspecialchars($this->error); ?></pre>
			</div>
		<?php
	}

	// check for and apply any database updates
	private function update () {
		$current_version = bw_survey_get_option('database_version');

		foreach ( $this->get_updates($current_version) as $update ) {
			if ($error = $this->apply_update($update)) break;
			bw_survey_update_option('database_version', $update['version']);
		}
	}

	private function apply_update ($update) {
		$error = include dirname( BW_SURVEY_PLUGIN_FILE ) . 'includes/database/schema/' . $update['file'];
		if ($error) {
			$this->error = $error;
			add_action('admin_notices', array( $this, 'update_error_notice' ), 10, 0);
		}
		return $error;
	}

	// lists database updates ascending order
	private function get_updates ($current_version) {
		return array_filter([
			[
				'version' => '1.0.0',
				'file' => '100.php'
			]
		], function ($val) use ($current_version) {
			return version_compare($val['version'], $current_version, 'gt');
		});
	}
}
