<?php

namespace CodeConfig\EAW\Pages;

defined('ABSPATH') || exit('No direct script access allowed');

class AdminPages
{
    public static function adminMenu()
    {
        // Main menu page
        add_menu_page(
            __('Essential Addons', 'essential-addons-for-woocommerce'),
            __('Essential Addons', 'essential-addons-for-woocommerce'),
            'manage_options',
            CCPEAW_SLUG,
            [self::class, 'settingsPage'],
            CCPEAW_ASSETS . '/images/icons/eaw-logo-20x20.png',
            10
        );

        // Submenu: Settings
        add_submenu_page(
            CCPEAW_SLUG,
            __('Settings - ', 'essential-addons-for-woocommerce') . CCPEAW_NAME,
            __('Settings', 'essential-addons-for-woocommerce'),
            'manage_options',
            CCPEAW_SLUG,
            [self::class, 'settingsPage']
        );

        // Submenu: Recommended Plugins (temporary placeholder, will reorder later)
        add_submenu_page(
            CCPEAW_SLUG,
            __('Recommended Plugins - ', 'essential-addons-for-woocommerce') . CCPEAW_NAME,
            __('Recommended Plugins', 'essential-addons-for-woocommerce'),
            'manage_options',
            'ccpeaw-recommended-plugins',
            [self::class, 'recommended_plugins']
        );

        // Reorder to push "Recommended Plugins" to bottom
        add_action('admin_head', [self::class, 'reorderSubmenu']);
    }

    public static function settingsPage()
    {
        wp_enqueue_style('ccpeaw-admin');
        echo '<div id="eaw-settings" class="eaw-settings cart-manager-top-level-wrapper"></div>';
    }

    public static function recommended_plugins()
    {
        wp_safe_redirect(admin_url('plugin-install.php?s=codeconfig&tab=search&type=author'));
        exit;
    }

    public static function reorderSubmenu()
    {
        global $submenu;

        if (!isset($submenu[CCPEAW_SLUG])) {
            return;
        }

        $reordered   = [];
        $recommended = null;

        foreach ($submenu[CCPEAW_SLUG] as $item) {
            if ($item[2] === 'ccpeaw-recommended-plugins') {
                $recommended = $item;
            } else {
                $reordered[] = $item;
            }
        }

        if ($recommended) {
            $reordered[] = $recommended;
        }

        $submenu[CCPEAW_SLUG] = $reordered;
    }
}
