<?php

namespace DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Action\Loader\Menu;

use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Infrastructure\Menu\Abstraction\MainMenuInterface;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Infrastructure\Menu\Abstraction\SubMenuInterface;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Infrastructure\Service\Listener\Items\Conditional\Conditional;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Infrastructure\Service\Listener\Items\Hookable\Hookable;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Infrastructure\Config\Config;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Action\View\ViewAction;
class AdminMenuLoaderAction implements Hookable, Conditional
{
    private Config $config;
    private ViewAction $view;
    public function __construct(Config $config, ViewAction $view)
    {
        $this->config = $config;
        $this->view = $view;
    }
    public function isActive(): bool
    {
        return is_admin();
    }
    public function hooks()
    {
        add_action('admin_menu', [$this, 'adminMenu'], 10);
    }
    public function adminMenu()
    {
        $menus = $this->config->get_param('menu');
        if ($menus->isArray() && !$menus->isEmpty()) {
            foreach ($menus->get() as $menu) {
                if ($menu instanceof MainMenuInterface) {
                    $this->create_main_menu($menu);
                    foreach ($menu->get_submenus() as $sub) {
                        $this->create_sub_menu($sub);
                    }
                } elseif ($menu instanceof SubMenuInterface) {
                    $this->create_sub_menu($menu);
                }
            }
        }
    }
    private function create_main_menu(MainMenuInterface $menu)
    {
        global $submenu;
        add_menu_page($menu->get_title(), $menu->get_title(), $menu->get_capability(), $menu->get_slug(), [$this->view, 'show'], $menu->get_icon(), $menu->get_position());
        if ($menu->is_hidden()) {
            $submenu[$menu->get_slug()] = [];
            // phpcs:ignore
        }
    }
    private function create_sub_menu(SubMenuInterface $menu)
    {
        add_submenu_page($menu->is_hidden() ? null : $menu->get_parent_slug(), $menu->get_title(), $menu->get_title(), $menu->get_capability(), $menu->get_slug(), [$this->view, 'show'], $menu->get_position());
    }
}
