<?php

namespace EasyLinkAutomations\Views;

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

use EasyLinkAutomations\Config;
use EasyLinkAutomations\Hooks\Hooks;
use EasyLinkAutomations\Utils\Capabilities;

/**
 * Registers the admin sidebar menu and enqueues page-level assets.
 */
final class Layout
{
    public function __construct()
    {
        Hooks::addAction('in_admin_header', [$this, 'removeAdminNotices']);
        Hooks::addAction('admin_menu', [$this, 'registerMenus']);
        Hooks::addAction('admin_enqueue_scripts', [new Head(), 'enqueueAssets'], 0);
    }

    /**
     * Register admin menu and submenu items from the Menu definition.
     */
    public function registerMenus(): void
    {
        $menus = Hooks::applyFilter(
            Config::withPrefix('admin_sidebar_menu'),
            Config::get('SIDE_BAR_MENU')
        );

        global $submenu;

        foreach ($menus as $menu) {
            if (!isset($menu['capability']) || !Capabilities::check($menu['capability'])) {
                continue;
            }

            if ($menu['type'] === 'menu') {
                add_menu_page(
                    $menu['title'],
                    $menu['name'],
                    $menu['capability'],
                    $menu['slug'],
                    $menu['callback'],
                    $menu['icon'],
                    $menu['position']
                );
            } else {
                $submenu[$menu['parent']][] = [
                    $menu['name'],
                    $menu['capability'],
                    $menu['url'] ?? 'admin.php?page=' . $menu['slug'],
                ];
            }
        }
    }

    /**
     * Suppress all admin notices on our plugin pages for a clean UI.
     */
    public function removeAdminNotices(): void
    {
        global $plugin_page;

        if (empty($plugin_page) || !str_contains($plugin_page, Config::SLUG)) {
            return;
        }

        remove_all_actions('admin_notices');
        remove_all_actions('all_admin_notices');
    }
}
