<?php

defined( 'ABSPATH' ) || exit;

class Wiaas_DB_Update {

	private static $db_updates = array(
		'20180728222206' => 'wiaas_db_update_enable_product_by_user_role',
		'20180801222206' => 'wiaas_db_update_setup_gravity',
		'20180802222206' => 'wiaas_db_update_add_delivery_process_forms',
		'20180811134511' => 'wiaas_db_update_enable_orders_access_management',
		'20180813134511' => 'wiaas_db_update_enable_order_numbers',
		'20180826153509' => 'wiaas_create_broker_access_group',
		'20180911101010' => 'wiaas_db_setup_exclusive_taxonomies',
		'20181003164100' => 'wiaas_db_setup_customer_capabilities',
        '201810121644700' => 'wiaas_db_update_add_user_organization_ui_fields',
		'201810171645700' => 'wiaas_db_update_create_default_roles',
		'201810171745700' => 'wiaas_db_import_aam_role_settings',
		'201810180145700' => 'wiaas_db_update_update_supplier_capabilities',
		'201810180245700' => 'wiaas_db_update_update_admin_capabilities',
		'201810180345700' => 'wiaas_create_role_access_groups',
		'201810180444700' => 'wiaas_db_setup_create_customer_commercial_lead_table',
		'201810180544702' => 'wiaas_db_update_update_commercial_lead_capabilities',
		'201810180644703' => 'wiaas_db_update_add_organization_info_ui_fields',
        '201910190145700' => 'wiaas_db_update_add_general_ui_fields',
        '201910190146700' => 'wiaas_db_update_add_product_properties_ui_fields',
		'201810190644704' => 'wiaas_db_update_add_reference_ui_field'
	);

	public static function execute() {
		$pending_db_updates = self::get_pending_db_updates();
		foreach ( $pending_db_updates as $update_callback ) {
			self::execute_update($update_callback);
		}
	}

	public static function get_pending_db_updates() {
		$active_db_version = get_option( 'wiaas_db_version', '0' );
		$pending_db_updates = array();
		foreach (self::$db_updates as $version => $update_callback) {
			if ($active_db_version < $version) {
				$pending_db_updates[] = $update_callback;
			}
		}
		return $pending_db_updates;
	}

	public static function execute_update($update_callback) {
		call_user_func($update_callback);
		$version = array_search($update_callback, self::$db_updates);
		update_option('wiaas_db_version', $version);
	}
}
