<?php
/**
 * Capability registration and helpers.
 *
 * @package MailDoctor
 */

namespace MailDoctor;

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

/**
 * Manage plugin-specific capabilities.
 */
class Capabilities {

	/**
	 * Capability slugs.
	 */
	const MANAGE_SETTINGS = 'mail_doctor_manage_settings';
	const VIEW_LOGS       = 'mail_doctor_view_logs';
	const MANAGE_RETRIES  = 'mail_doctor_manage_retries';
	const VIEW_PII        = 'mail_doctor_view_pii';

	/**
	 * Return full capability list.
	 *
	 * @return array<int, string>
	 */
	public static function all(): array {
		return array(
			self::MANAGE_SETTINGS,
			self::VIEW_LOGS,
			self::MANAGE_RETRIES,
			self::VIEW_PII,
		);
	}

	/**
	 * Assign capabilities to core roles.
	 *
	 * @return void
	 */
	public static function install(): void {
		$roles = array( 'administrator', 'shop_manager' );

		foreach ( $roles as $role_key ) {
			$role = get_role( $role_key );
			if ( ! $role ) {
				continue;
			}

			foreach ( self::all() as $capability ) {
				if ( ! $role->has_cap( $capability ) ) {
					$role->add_cap( $capability );
				}
			}
		}
	}

	/**
	 * Ensure capabilities remain assigned during runtime.
	 *
	 * @return void
	 */
	public static function ensure_role_mappings(): void {
		if ( ! is_admin() ) {
			return;
		}

		static $ensured = false;

		if ( $ensured ) {
			return;
		}

		self::install();
		$ensured = true;
	}

	/**
	 * Helper for capability checks.
	 *
	 * @param string $cap Capability identifier.
	 * @return bool
	 */
	public static function current_user_can( string $cap ): bool {
		if ( empty( $cap ) ) {
			return false;
		}

		return current_user_can( $cap ) || current_user_can( 'manage_woocommerce' ) || current_user_can( 'manage_options' );
	}
}
