<?php
/**
 * Plugin activation routine.
 *
 * Creates the custom tables, registers the custom roles and capabilities, and
 * records the schema version. All steps are idempotent so re-activating a
 * already-installed plugin is safe.
 *
 * @package WrenchPress
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class WrenchPress_Activator
 */
class WrenchPress_Activator {

	/**
	 * Run on plugin activation.
	 *
	 * @return void
	 */
	public static function activate() {
		WrenchPress_Schema::create_tables();
		self::register_roles_and_caps();

		update_option( WRENCHPRESS_DB_VERSION_OPTION, WRENCHPRESS_DB_VERSION );
	}

	/**
	 * Register the custom roles and grant every wrenchpress_* capability to the
	 * administrator role (ROLE-03).
	 *
	 * The add_role() call returns null when the role already exists, which is
	 * acceptable on re-activation. To keep the cap set current on re-activation,
	 * existing roles have their capability set re-applied from the matrix.
	 *
	 * @return void
	 */
	public static function register_roles_and_caps() {
		foreach ( WrenchPress_Capabilities::role_matrix() as $role_slug => $config ) {
			$role = get_role( $role_slug );

			if ( null === $role ) {
				add_role( $role_slug, $config['display_name'], $config['capabilities'] );
				continue;
			}

			// Role already exists (re-activation): ensure its caps match the
			// matrix without disturbing any caps WordPress core may have added.
			foreach ( $config['capabilities'] as $cap => $granted ) {
				if ( $granted ) {
					$role->add_cap( $cap );
				}
			}
		}

		$admin = get_role( 'administrator' );

		if ( $admin instanceof WP_Role ) {
			foreach ( WrenchPress_Capabilities::all_capabilities() as $cap ) {
				$admin->add_cap( $cap );
			}
		}
	}
}
