<?php

defined( 'ABSPATH' ) || exit;

class Wiaas_DB_Update {

	private static $db_updates = array(
		'20180801222206' => 'wiaas_db_update_setup_gravity',
		'20180811134511' => 'wiaas_db_update_enable_orders_access_management',
		'20180911101010' => 'wiaas_db_setup_exclusive_taxonomies',
		'20181003164100' => 'wiaas_db_setup_customer_capabilities',
		'20181012164450' => 'wiaas_db_update_add_user_organization_ui_fields',
		'20181017164550' => 'wiaas_db_update_create_default_roles',
		'20181017174550' => 'wiaas_db_import_aam_role_settings',
		'20181018014550' => 'wiaas_db_update_update_supplier_capabilities',
		'20181018024550' => 'wiaas_db_update_update_admin_capabilities',
		'20181018034550' => 'wiaas_admin_create_role_access_groups',
		'20181018044450' => 'wiaas_db_setup_create_customer_commercial_lead_table',
		'20181018054450' => 'wiaas_db_update_update_commercial_lead_capabilities',
		'20181018064450' => 'wiaas_db_update_add_organization_info_ui_fields',
		'20181019014550' => 'wiaas_db_update_add_general_ui_fields',
		'20181019014650' => 'wiaas_db_update_add_product_properties_ui_fields',
		'20181020014650' => 'wiaas_create_organization_roles_capabilities',
        '20181021162450' => 'wiaas_db_update_update_supplier_order_capabilities',
        '20181102112451' => 'wiaas_disable_processing_order_email_delivery',
		'20181103172850' => 'wiaas_db_update_update_delivery_forms',
		'20181104182856' => 'wiaas_db_update_enable_workflow_inbox_for_roles',
        '20181105133550' => 'wiaas_db_update_add_bundle_properties_ui_field',
		'20181106133553' => 'wiaas_db_update_add_installation_date_delivery_action_form',
		'20181125133553' => 'wiaas_db_update_add_country_settings_ui_fields',
		'20181125143553' => 'wiaas_db_migration_fix_user_profile_addresses', // remove after migration
		'20181125153553' => 'wiaas_db_migration_fix_countries' // remove after migration
	);

	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);
	}
}
