<?php
/**
 * Manages roles and permissions for HVAC testing
 */
class HVAC_Role_Manager {
    private static $instance;
    private $created_roles = [];

    private function __construct() {}

    public static function get_instance() {
        if (!isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Create a new role with specified capabilities
     */
    public function create_role($role, $display_name, $capabilities = []) {
        if ($this->role_exists($role)) {
            return false;
        }

        $default_caps = [
            'read' => true,
            'edit_posts' => true
        ];

        $capabilities = array_merge($default_caps, $capabilities);
        add_role($role, $display_name, $capabilities);
        $this->created_roles[] = $role;
        return true;
    }

    /**
     * Check if a role exists
     */
    public function role_exists($role) {
        return wp_roles()->is_role($role);
    }

    /**
     * Delete a role
     */
    public function delete_role($role) {
        if (!$this->role_exists($role)) {
            return false;
        }

        remove_role($role);
        $this->created_roles = array_diff($this->created_roles, [$role]);
        return true;
    }

    /**
     * Add capability to role
     */
    public function add_capability($role, $cap, $grant = true) {
        $wp_roles = wp_roles();
        $wp_roles->add_cap($role, $cap, $grant);
    }

    /**
     * Remove capability from role
     */
    public function remove_capability($role, $cap) {
        $wp_roles = wp_roles();
        $wp_roles->remove_cap($role, $cap);
    }

    /**
     * Clean up all created roles
     */
    public function cleanup() {
        foreach ($this->created_roles as $role) {
            $this->delete_role($role);
        }
        $this->created_roles = [];
    }
}