<?php
/**
 * The Upgrade class.
 *
 * @package HBFWC
 */

namespace HBFWC;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use HBFWC\Utils\DB;

/**
 * Manages upgrade tasks.
 */
class Upgrade {
	/**
	 * Instance of database class.
	 *
	 * @var DB
	 */
	private $db;

	/**
	 * The current plugin version number.
	 *
	 * @var string
	 */
	private $current_version;

	/**
	 * The previous plugin version number.
	 *
	 * @var string
	 */
	private $prev_version;

	/**
	 * Class constructor.
	 *
	 * @param string $version Current plugin version.
	 * @param DB     $db      Instance of database class.
	 */
	public function __construct( string $version, DB $db ) {
		$this->db              = $db;
		$this->current_version = $version;
		$this->prev_version    = get_option( 'hbfwc_version', '0.1.0' );
	}

	/**
	 * Run the upgrade functions.
	 */
	public function run() {
		$this->do_site_upgrades();
		$this->update_version();
	}

	/**
	 * Perform upgrades for the current site.
	 */
	private function do_site_upgrades() {
		$table_name = $this->db->table;

		// Do nothing if the plugin has not just been updated or installed.
		if ( ! version_compare( $this->prev_version, $this->current_version, '<' ) ) {
			// Need to make sure, DB table still exists.
			$this->db->create_missing_table( $table_name );
			return;
		}

		$this->db->create_table( $table_name );
	}

	/**
	 * Update version.
	 */
	private function update_version() {
		update_option( 'hbfwc_version', $this->current_version );
	}
}
