<?php

defined( 'ABSPATH' ) || exit;

if ( !class_exists( 'CommunityAlly_Core_Setup' ) ) :
class CommunityAlly_Core_Setup {
	// <editor-fold defaultstate="collapsed" desc="Add actions">
	public static function add_actions() {
		add_action('communityally_background_convert_legacy_settings', array(__CLASS__, 'convert_legacy_settings'));
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="Background action to convert legacy settings">
	const SETTING_KEY_LEGACY_CONVERSION_COMPLETED = '_communityally_legacy_conversion';
	public static function convert_legacy_settings() {
		$converted_version = get_option(self::SETTING_KEY_LEGACY_CONVERSION_COMPLETED, false);
		if (!empty($converted_version) && version_compare($converted_version, '1.4.0') >= 0) {
			return;
		}
		CommunityAllySettings::validate_special_page_settings();
		CommunityAlly_Groups_Setup::convert_legacy_groups_to_custom_posts();
		update_option(self::SETTING_KEY_LEGACY_CONVERSION_COMPLETED, '1.4.0', 'no');
	}
	// </editor-fold>

	const SETTING_KEY_DATABASE_VERSION = '_communityally_database_version';
	private static function get_database_version() {
		$version = get_transient(self::SETTING_KEY_DATABASE_VERSION);

		if (!$version) {
			$version = get_option(self::SETTING_KEY_DATABASE_VERSION, false);
		}
		if (empty($version)) {
			return '0.0.0';
		}
		return $version;
	}
	private static function update_database_version() {
		set_transient(self::SETTING_KEY_DATABASE_VERSION, CommunityAllyUpdater::VERSION, 86400);
		update_option(self::SETTING_KEY_DATABASE_VERSION, CommunityAllyUpdater::VERSION);
	}
	public static function upgrade_database() {
		/* must be called first because the database version will be updated by the other initialize_defaults calls */
		$database_version = self::get_database_version();
		if (CommunityAllyUpdater::VERSION !== $database_version) {
			bp_version_updater();
			self::update_database_version();

			// Convert groups to use custom post
			if (version_compare($database_version, '1.4.0') < 0) {
				wp_schedule_single_event(time() + 5, 'communityally_background_convert_legacy_settings');
			}
		}
	}
}
endif; // CommunityAlly_Core_Setup.