<?php

namespace BitApps\BTCBI_PRO\Core\Util;

use BitApps\BTCBI_PRO\Core\Database\DB;
use WP_Site;

/**
 * Class handling plugin activation.
 *
 * @since 1.0.0
 */
final class Activation
{
    public function activate()
    {
        add_action('btcbi_pro_activation', [$this, 'install']);
    }

    public function install($network_wide)
    {
        if ($network_wide && \function_exists('is_multisite') && is_multisite()) {
            $sites = Multisite::all_blog_ids();
            foreach ($sites as $site) {
                switch_to_blog($site);
                $this->installAsSingleSite();
                if ($network_wide) {
                    activate_plugin(plugin_basename(BTCBI_PRO_PLUGIN_MAIN_FILE));
                }
                restore_current_blog();
            }
        } else {
            $this->installAsSingleSite();
        }
    }

    public function installAsSingleSite()
    {
        $installed = get_option('btcbi_pro_installed');
        if ($installed) {
            $oldVersion = get_option('btcbi_pro_version');
        }
        if (!$installed || version_compare($oldVersion, BTCBI_PRO_VERSION, '!=')) {
            DB::migrate();
            update_option('btcbi_pro_installed', time());
        }
        update_option('btcbi_pro_version', BTCBI_PRO_VERSION);

        // disable free version if pro version is active
        // if (defined('BTCBI_PLUGIN_MAIN_FILE') && is_plugin_active(plugin_basename(BTCBI_PLUGIN_MAIN_FILE))) {
        //     deactivate_plugins(plugin_basename(BTCBI_PLUGIN_MAIN_FILE));
        // }
    }

    public static function handle_new_site(WP_Site $new_site)
    {
        switch_to_blog($new_site->blog_id);
        $plugin = plugin_basename(BTCBI_PRO_PLUGIN_MAIN_FILE);
        if (is_plugin_active_for_network($plugin)) {
            activate_plugin($plugin);
        } else {
            do_action('btcbi_pro_activation');
        }
        restore_current_blog();
    }
}
