<?php

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

final class SPP_Shortcode
{
    public function __construct(private SPP_Permissions $permissions)
    {
    }

    public function register_hooks(): void
    {
        add_shortcode('support_provisioning_portal', [$this, 'render']);
    }

    /**
     * @param array<string, mixed> $atts
     */
    public function render(array $atts = []): string
    {
        if (!is_user_logged_in()) {
            return '<p class="spp-login-required">Please sign in to access the provisioning portal.</p>';
        }

        if (!$this->permissions->current_user_has(SPP_Permissions::VIEW_PORTAL)) {
            return '<p class="spp-login-required">You do not have permission to access the provisioning portal.</p>';
        }

        wp_enqueue_style('spp-portal', SPP_PLUGIN_URL . 'assets/portal.css', [], SPP_VERSION);
        wp_enqueue_script('spp-portal', SPP_PLUGIN_URL . 'assets/portal.js', [], SPP_VERSION, true);

        return sprintf(
            '<div id="spp-portal-root" class="spp-portal" data-rest-url="%s" data-nonce="%s" data-permissions="%s"></div>',
            esc_url_raw(rest_url('support-provisioning/v1')),
            esc_attr(wp_create_nonce('wp_rest')),
            esc_attr((string) wp_json_encode($this->permissions->current_user_permissions()))
        );
    }
}
