<?php
/**
 * Activation lifecycle.
 *
 * @package VoidPulse
 */

namespace VoidPulse\Core;

use VoidPulse\Infrastructure\Migrations;
use VoidPulse\Shared\CampaignSchema;

defined( 'ABSPATH' ) || exit;

final class Activator {
	/**
	 * Activate without expensive indexing or publication.
	 *
	 * @param bool $network_wide Network activation.
	 * @return void
	 */
	public static function activate( $network_wide = false ) {
		if ( is_multisite() && $network_wide ) {
			$site_ids = get_sites( array( 'fields' => 'ids' ) );
			foreach ( $site_ids as $site_id ) {
				switch_to_blog( (int) $site_id );
				self::activate_site();
				restore_current_blog();
			}
			return;
		}
		self::activate_site();
	}

	/**
	 * Activate one site.
	 *
	 * @return void
	 */
	private static function activate_site() {
		Migrations::run();
		OwnershipRegistry::register_base();
		self::add_capabilities();
		add_option( 'voidpulse_version', VOIDPULSE_VERSION, '', false );
		add_option( 'voidpulse_defaults', CampaignSchema::defaults(), '', false );
		add_option( 'voidpulse_delete_data_on_uninstall', false, '', false );
		add_option( 'voidpulse_activation_pending', true, '', false );
	}

	/**
	 * Add plugin capabilities.
	 *
	 * @return void
	 */
	public static function add_capabilities() {
		$admin_caps = array(
			'manage_voidpulse',
			'edit_voidpulse_campaigns',
			'publish_voidpulse_campaigns',
			'view_voidpulse_analytics',
			'export_voidpulse_analytics',
			'manage_voidpulse_settings',
		);
		$shop_caps  = array(
			'edit_voidpulse_campaigns',
			'publish_voidpulse_campaigns',
			'view_voidpulse_analytics',
		);

		$administrator = get_role( 'administrator' );
		$shop_manager  = get_role( 'shop_manager' );
		foreach ( $admin_caps as $capability ) {
			if ( $administrator ) {
				$administrator->add_cap( $capability );
			}
		}
		foreach ( $shop_caps as $capability ) {
			if ( $shop_manager ) {
				$shop_manager->add_cap( $capability );
			}
		}
	}
}
