<?php
/**
 * Activator Class File
 *
 * This file contains Activator class. If you want to perform some actions
 * in activating of your plugin, you can add your desire methods to it.
 * Actions likes installing separated tables (except WordPress tables),
 * initializing configs for plugin and using update_option, can do with this class.
 */

namespace CarDealerPress\Includes\Init;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use CarDealerPress\Includes\Abstracts\Custom_Taxonomy;
use CarDealerPress\includes\functions\Logger;
use CarDealerPress\Includes\Uninstall\Uninstall;

class Activator {
	use Logger;

	/**
	 * @var Custom_Taxonomy[] $custom_taxonomies
	 */
	private $custom_taxonomies;

	public function cdp_activate( $network_wide ) {
		if ( function_exists( 'is_multisite' ) && is_multisite() && $network_wide ) {
			if ( ! is_super_admin() ) {
				return;
			}
			// @codingStandardsIgnoreStart
			error_log( 'CDP Message: Multisite activation and networkwide' );
			// @codingStandardsIgnoreEnd
			$site_ids = get_sites( array( 'fields' => 'ids' ) );
			foreach ( $site_ids as $site_id ) {
				switch_to_blog( $site_id );
				$this->activate_for_blog( $site_id );
				$custom_taxonomies = null;
				$this->check_taxonomies( $custom_taxonomies );
				restore_current_blog();
			}
		} else {
			if ( ! current_user_can( 'activate_plugins' ) ) {
				return;
			}
			$blog_id = get_current_blog_id();
			$this->activate_for_blog( $blog_id );
		}

	}

	private function activate_for_blog( $blog_id ) {
		$this->append_log( array( 'message' => 'CDP Message: Plugin is activated on site id: ' . $blog_id ) );
		// @codingStandardsIgnoreStart
		error_log( 'CDP Message: Plugin is activated on site id: ' . $blog_id );
		// @codingStandardsIgnoreEnd
	}

	private function check_taxonomies( $custom_taxonomies ) {
		if ( ! is_null( $custom_taxonomies ) ) {
			$this->custom_taxonomies = $this->check_array_by_parent_type( $custom_taxonomies, Custom_Taxonomy::class )['valid'];
			if ( ! is_null( $this->custom_taxonomies ) ) {
				$this->register_plugin_custom_taxonomy();
			}
		}
	}

	/**
	 * Method to register all of needed custom taxonomies and flush rewrite rules
	 *
	 * @access private
	 * @since  1.0.2
	 */
	private function register_plugin_custom_taxonomy() {
		if ( ! is_null( $this->custom_taxonomies ) ) {
			foreach ( $this->custom_taxonomies as $custom_taxonomy ) {
				$custom_taxonomy->add_custom_taxonomy();
			}
			// ATTENTION: This is *only* done during plugin activation hook in this example!
			// You should *NEVER EVER* do this on every page load!!
			flush_rewrite_rules();
			if ( ! get_option( 'has_rewrite_for_plugin_name_new_taxonomies' ) ) {
				flush_rewrite_rules();
				update_option( 'has_rewrite_for_plugin_name_new_taxonomies', true );
			}
		}
	}
}
