<?php

namespace QodeBadgesForWooCommerce\Database;

if ( ! defined( 'ABSPATH' ) ) {
	// Exit if accessed directly.
	exit;
}
/**
 * Class Qode_Badges_Tables_Setup
 *
 * @package QodeBadgesForWooCommerce\Database
 */
class Qode_Badges_Tables_Setup {
	private static $instance;
	private $tables;

	/**
	 * Private __construct because of singleton pattern
	 */
	private function __construct() {
	}

	/**
	 * Returns current instance of class
	 *
	 * @return Qode_Badges_Tables_Setup
	 */
	public static function get_instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	public function has_tables() {
		return is_array( $this->tables ) && count( $this->tables );
	}

	public function initialize() {

		$this->add_tables();

		add_action( 'qode_badges_for_woocommerce_action_on_activation', array( $this, 'on_activate' ) );
		add_action( 'qode_badges_for_woocommerce_action_on_deactivation', array( $this, 'on_deactivate' ) );

		add_action( 'plugins_loaded', array( $this, 'upgrade' ) );
		add_action( 'plugins_loaded', array( $this, 'call_instances' ) );
	}

	public function initialize_table() {
		Qode_Product_Badge_Relation_Table_Setup::get_instance();
	}

	/**
	 * Goes through all tables and initializes them
	 *
	 * @return bool
	 */
	public function on_activate() {
		if ( ! $this->has_tables() ) {
			return false;
		}

		foreach ( $this->tables as $table ) {
			$this->setup_table( $table );
		}
	}

	public function upgrade() {
		if ( ! $this->has_tables() ) {
			return false;
		}

		foreach ( $this->tables as $table ) {
			if ( ! $table->has_new_version() ) {
				return false;
			}

			$table->upgrade();
		}
	}

	public function call_instances() {
		Qode_Product_Badge_Relation_Table_Setup::get_instance();
	}

	public function on_deactivate() {
		// doesn't have an implementation yet.
	}

	/**
	 * Add all table objects to tables array
	 */
	private function add_tables() {
		$this->add_table( Qode_Product_Badge_Relation_Table_Setup::get_instance() );
	}

	private function add_table( Qode_Badges_Database_Table_Setup $table ) {
		$this->tables[] = $table;
	}
	private function setup_table( Qode_Badges_Database_Table_Setup $table ) {
		return $table->setup();
	}
}
