<?php

namespace PluginsNameSpaces\Hooks\Handlers;

use PluginsNameSpaces\App;

/**
 * Registers the plugin's admin menu from config/menu.php.
 */
class AdminMenuHandlers
{
    /**
     * Hook into WordPress.
     *
     * @return void
     */
    public function register()
    {
        add_action('admin_menu', [$this, 'addMenu']);
    }

    /**
     * Register the top-level menu and any submenus.
     *
     * @return void
     */
    public function addMenu()
    {
        $menu = App::config('menu');

        add_menu_page(
            __($menu['page_title'], App::config('app.text_domain')),
            __($menu['menu_title'], App::config('app.text_domain')),
            $menu['capability'],
            $menu['slug'],
            [$this, 'render'],
            $this->icon($menu['icon_svg'] ?? ''),
            $menu['position'] ?? 26
        );

        $this->registerSubmenus($menu);
    }

    /**
     * Register submenu items as deep-links into the SPA.
     *
     * The plugin renders one Vue app on the top-level page; each submenu is
     * a sidebar link to that same page with a URL hash, which the SPA's hash
     * router resolves to the matching screen. Items are appended to the
     * global $submenu so the href can carry a hash (add_submenu_page would
     * URL-encode it). WordPress still enforces the capability in element [1].
     *
     * @param array $menu
     * @return void
     */
    protected function registerSubmenus(array $menu)
    {
        global $submenu;

        $slug = $menu['slug'];
        $td   = App::config('app.text_domain');

        // Rename the auto-created first submenu (a duplicate of the parent).
        if (isset($submenu[$slug][0][0])) {
            $submenu[$slug][0][0] = __($menu['dashboard_label'] ?? 'Dashboard', $td);
        }

        foreach ($menu['submenus'] ?? [] as $item) {
            if (! current_user_can($item['capability'] ?? $menu['capability'])) {
                continue;
            }

            $route = '#' . ltrim($item['route'] ?? '/', '#');

            $submenu[$slug][] = [
                __($item['menu_title'], $td),                    // [0] label
                $item['capability'] ?? $menu['capability'],      // [1] capability
                'admin.php?page=' . $slug . $route,              // [2] href (hash kept)
            ];
        }
    }

    /**
     * Render the dashboard view (Vue mount point).
     *
     * @return void
     */
    public function render()
    {
        __SNAKE_NAME___view('admin-dashboard');
    }

    /**
     * Encode an SVG string into a data URI for the menu icon.
     *
     * @param string $svg
     * @return string
     */
    protected function icon($svg)
    {
        if (! $svg) {
            return 'dashicons-admin-generic';
        }

        return 'data:image/svg+xml;base64,' . base64_encode($svg);
    }
}
