<?php

declare(strict_types=1);

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

final class RC_Roles {

	public const CAP_VIEW_INGREDIENTS  = 'rc_view_ingredients';
	public const CAP_VIEW_RECIPES      = 'rc_view_recipes';
	public const CAP_ACCESS_INVENTORY  = 'rc_access_inventory';
	public const CAP_EDIT_INGREDIENTS  = 'rc_edit_ingredients';
	public const CAP_EDIT_RECIPES      = 'rc_edit_recipes';
	public const CAP_MANAGE_SUPPLIERS  = 'rc_manage_suppliers';
	public const CAP_MANAGE_AREAS      = 'rc_manage_areas';
	public const CAP_MANAGE_SETTINGS   = 'rc_manage_settings';
	public const CAP_PRINT             = 'rc_print';
	public const CAP_EMAIL_ORDER       = 'rc_email_order';
	public const CAP_EXPORT            = 'rc_export';
	public const CAP_IMPORT            = 'rc_import';
	public const CAP_MANAGE_USERS      = 'rc_manage_users';

	public const ROLE_USER    = 'rc_user';
	public const ROLE_MANAGER = 'rc_manager';

	public static function all_caps(): array {
		return array(
			self::CAP_VIEW_INGREDIENTS,
			self::CAP_VIEW_RECIPES,
			self::CAP_ACCESS_INVENTORY,
			self::CAP_EDIT_INGREDIENTS,
			self::CAP_EDIT_RECIPES,
			self::CAP_MANAGE_SUPPLIERS,
			self::CAP_MANAGE_AREAS,
			self::CAP_MANAGE_SETTINGS,
			self::CAP_PRINT,
			self::CAP_EMAIL_ORDER,
			self::CAP_EXPORT,
			self::CAP_IMPORT,
			self::CAP_MANAGE_USERS,
		);
	}

	public static function user_caps(): array {
		return array(
			'read',
			self::CAP_VIEW_INGREDIENTS,
			self::CAP_VIEW_RECIPES,
			self::CAP_ACCESS_INVENTORY,
		);
	}

	public static function manager_caps(): array {
		return array_merge(
			array( 'read' ),
			self::all_caps()
		);
	}

	public static function register_roles(): void {
		self::update_or_create_role( self::ROLE_USER, __( 'RC User', 'restaurant-costing' ), self::user_caps() );
		self::update_or_create_role( self::ROLE_MANAGER, __( 'RC Manager', 'restaurant-costing' ), self::manager_caps() );
		self::grant_admin_caps();
	}

	private static function update_or_create_role( string $slug, string $display, array $caps ): void {
		$role = get_role( $slug );
		if ( ! $role ) {
			add_role( $slug, $display, array_combine( $caps, array_fill( 0, count( $caps ), true ) ) );
			return;
		}
		foreach ( $caps as $cap ) {
			$role->add_cap( $cap );
		}
	}

	public static function grant_admin_caps(): void {
		$role = get_role( 'administrator' );
		if ( ! $role ) {
			return;
		}
		foreach ( self::all_caps() as $cap ) {
			$role->add_cap( $cap );
		}
	}

	public static function revoke_admin_caps(): void {
		$role = get_role( 'administrator' );
		if ( ! $role ) {
			return;
		}
		foreach ( self::all_caps() as $cap ) {
			$role->remove_cap( $cap );
		}
	}

	public static function remove_roles(): void {
		remove_role( self::ROLE_USER );
		remove_role( self::ROLE_MANAGER );
	}
}
