<?php
/**
 * Activation routine.
 *
 * @package TextTango
 */

declare( strict_types=1 );

namespace TextTango\Install;

use TextTango\Support\Settings;

defined( 'ABSPATH' ) || exit;

/**
 * Runs on plugin activation: table, capability, default settings.
 */
final class Activator {

	/**
	 * Capability granted to operators of the plugin (spec §12).
	 */
	public const CAPABILITY = 'manage_texttango';

	/**
	 * Entry point for `register_activation_hook`.
	 *
	 * @param bool $network_wide True when network-activated on multisite.
	 */
	public static function activate( bool $network_wide = false ): void {
		if ( is_multisite() && $network_wide ) {
			$site_ids = get_sites(
				array(
					'fields' => 'ids',
					'number' => 0,
				)
			);

			foreach ( $site_ids as $site_id ) {
				switch_to_blog( (int) $site_id );
				self::install_site();
				restore_current_blog();
			}

			return;
		}

		self::install_site();
	}

	/**
	 * Per-site install work.
	 */
	private static function install_site(): void {
		Schema::install();
		Settings::install_defaults();
		self::add_capability();
	}

	/**
	 * Grant the operator capability to administrators.
	 */
	public static function add_capability(): void {
		$role = get_role( 'administrator' );

		if ( $role instanceof \WP_Role ) {
			$role->add_cap( self::CAPABILITY );
		}
	}

	/**
	 * Revoke the operator capability from every role that holds it.
	 */
	public static function remove_capability(): void {
		$roles = wp_roles();

		foreach ( array_keys( $roles->roles ) as $role_name ) {
			$role = get_role( $role_name );

			if ( $role instanceof \WP_Role ) {
				$role->remove_cap( self::CAPABILITY );
			}
		}
	}

	/**
	 * Run pending schema upgrades on load, for sites updated via FTP or WP-CLI
	 * where the activation hook never fires again.
	 */
	public static function maybe_upgrade(): void {
		if ( Schema::needs_upgrade() ) {
			Schema::install();
		}
	}
}
