<?php

/**
 * Menu Configuration
 *
 * @package ArraySubs
 * @since 1.0.0
 */

namespace ArraySubs\Features\MainAdmin\Services;

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

class MenuConfig
{
    /**
     * Normalize a menu item by ensuring visiblity has a default value.
     *
     * @param array<string, mixed> $item Raw menu item.
     * @return array<string, mixed>
     */
    private static function normalizeMenuItem(array $item): array
    {
        $item['visiblity'] = isset($item['visiblity']) ? (int) $item['visiblity'] : 1;

        if (isset($item['children']) && is_array($item['children'])) {
            $item['children'] = array_map([self::class, 'normalizeMenuItem'], $item['children']);
        }

        return $item;
    }

    /**
     * Resolve module visiblity from live boot classes.
     *
     * @param string $moduleClassNamePartial Partial class name to match.
     * @return int
     */
    private static function moduleVisiblity(string $moduleClassNamePartial): int
    {
        return \arraysubs_has_module($moduleClassNamePartial);
    }

    /**
     * Resolve Store Credit runtime visibility from the module and master setting.
     *
     * @return int
     */
    private static function storeCreditEnabledVisibility(): int
    {
        $feature_visibility = self::moduleVisiblity('Features\\StoreCredit\\');

        if (1 !== $feature_visibility) {
            return $feature_visibility;
        }

        $settings = \arraysubs_get_settings();
        $enabled  = (bool) ($settings['store_credit']['enabled'] ?? true);

        return $enabled ? 1 : 0;
    }

    /**
     * Get menu items configuration
     *
     * @return array
     */
    public static function getMenuItems(): array
    {
        $module_visibilities = [
            // Requested modules list.
            'feature_manager' => self::moduleVisiblity('Features\\FeatureManager\\'),
            'store_credit' => self::moduleVisiblity('Features\\StoreCredit\\'),
            'skip_renewal' => self::moduleVisiblity('Features\\SkipRenewal\\'),
            'subscription_shipping' => self::moduleVisiblity('Features\\SubscriptionShipping\\'),
            'analytics' => self::moduleVisiblity('Features\\Analytics\\'),
            'automatic_payments' => self::moduleVisiblity('Features\\AutomaticPayments\\'),
            'member_insight' => self::moduleVisiblity('Features\\MemberInsight\\'),
            'audits' => self::moduleVisiblity('Features\\Audits\\') ?: -1,
            'multi_login_prevention' => self::moduleVisiblity('Features\\MultiLoginPrevention\\'),
            'store_credit_enabled' => self::storeCreditEnabledVisibility(),
        ];

        $items = [
            [
                'id' => 'subscriptions',
                'title' => __('Subscriptions', 'arraysubs'),
                'icon' => 'Repeat',
                'children' => [
                    [
                        'id' => 'all-subscriptions',
                        'title' => __('All Subscriptions', 'arraysubs'),
                        'path' => '/subscriptions',
                    ],
                    [
                        'id' => 'add-subscription',
                        'title' => __('Add new subscription', 'arraysubs'),
                        'path' => '/subscriptions/form',
                    ],
                ],
            ],
            [
                'id' => 'you-may-need',
                'title' => __('You may need', 'arraysubs'),
                'icon' => 'Sparkles',
                'path' => '/you-may-need',
                // Free-plugin only: hidden when ArraySubs Pro is installed and active.
                'visiblity' => defined('ARRAYSUBSPRO_VERSION') ? 0 : 1,
            ],
            [
                'id' => 'manage-members',
                'title' => __('Manage Members', 'arraysubs'),
                'icon' => 'UserSearch',
                'path' => '/manage-members',
                'visiblity' => $module_visibilities['member_insight'],
            ],
            [
                'id' => 'store-credit',
                'title' => __('Store Credit', 'arraysubs'),
                'icon' => 'Wallet',
                'visiblity' => $module_visibilities['store_credit'],
                'children' => [
                    [
                        'id' => 'store-credit-manage',
                        'title' => __('Manage Credits', 'arraysubs'),
                        'path' => '/store-credit',
                        'visiblity' => $module_visibilities['store_credit_enabled'],
                    ],
                    [
                        'id' => 'store-credit-history',
                        'title' => __('Credit History', 'arraysubs'),
                        'path' => '/store-credit/history',
                        'visiblity' => $module_visibilities['store_credit_enabled'],
                    ],
                    [
                        'id' => 'settings-store-credit',
                        'title' => __('Settings', 'arraysubs'),
                        'path' => '/store-credit/settings',
                        'visiblity' => $module_visibilities['store_credit'],
                    ],
                ],
            ],

            [
                'id' => 'retention-flow',
                'title' => __('Retention Flow', 'arraysubs'),
                'icon' => 'HeartHandshake',
                'path' => '/retention-flow',
            ],
            [
                'id' => 'members-access',
                'title' => __('Member Access', 'arraysubs'),
                'icon' => 'Shield',
                'children' => [
                    [
                        'id' => 'members-access-role-mapping',
                        'title' => __('Role Mapping', 'arraysubs'),
                        'path' => '/members-access',
                    ],
                    [
                        'id'    => 'members-access-content-gate',
                        'title' => __('Content Gate', 'arraysubs'),
                        'path'  => '/members-access/content-gate',
                    ],
                    [
                        'id'    => 'members-access-discount-rules',
                        'title' => __('Discount', 'arraysubs'),
                        'path'  => '/members-access/discount-rules',
                    ],
                    [
                        'id'    => 'members-access-ecommerce-rules',
                        'title' => __('Shop Access', 'arraysubs'),
                        'path'  => '/members-access/ecommerce-rules',
                    ],
                    [
                        'id' => 'members-access-url-rules',
                        'title' => __('URL', 'arraysubs'),
                        'path' => '/members-access/url-rules',
                    ],
                    [
                        'id'    => 'members-access-cpt-rules',
                        'title' => __('Post Types', 'arraysubs'),
                        'path' => '/members-access/cpt-rules',
                    ],
                    [
                        'id'    => 'members-access-downloads-rules',
                        'title' => __('Downloads', 'arraysubs'),
                        'path' => '/members-access/downloads-rules',
                    ],
                    [
                        'id'    => 'members-access-conflicts',
                        'title' => __('Conflicts', 'arraysubs'),
                        'path' => '/members-access/conflicts',
                    ],
                    [
                        'id'         => 'members-access-login-limit',
                        'title'      => __('Login Limit', 'arraysubs'),
                        'path'       => '/members-access/login-limit',
                        'visiblity'  => $module_visibilities['multi_login_prevention'],
                    ],
                ],
            ],
            [
                'id' => 'profile-builder',
                'title' => __('Profile Builder', 'arraysubs'),
                'icon' => 'UserCog',
                'children' => [
                    [
                        'id' => 'profile-builder-form',
                        'title' => __('Profile Form', 'arraysubs'),
                        'path' => '/profile-builder/profile-form',
                    ],
                    [
                        'id' => 'profile-builder-my-account',
                        'title' => __('My Account', 'arraysubs'),
                        'path' => '/profile-builder/my-account',
                    ],
                ],
            ],
            [
                'id' => 'reports',
                'title' => __('Reports', 'arraysubs'),
                'icon' => 'BarChart3',
                'path' => '/reports',
            ],
            [
                'id' => 'settings',
                'title' => __('Settings', 'arraysubs'),
                'children' => [
                    [
                        'id' => 'settings-general',
                        'title' => __('General', 'arraysubs'),
                        'path' => '/settings/general',
                    ],
                    [
                        'id' => 'settings-toolkit',
                        'title' => __('Toolkit', 'arraysubs'),
                        'path' => '/settings/toolkit',
                    ],
                    [
                        'id' => 'settings-plan-switching',
                        'title' => __('Plan Switching', 'arraysubs'),
                        'path' => '/settings/plan-switching',
                    ],
                    [
                        'id' => 'settings-refunds',
                        'title' => __('Refunds', 'arraysubs'),
                        'path' => '/settings/refunds',
                    ],
                    [
                        'id' => 'settings-skip-pause',
                        'title' => __('Skip & Pause', 'arraysubs'),
                        'path' => '/settings/skip-pause',
                        'visiblity' => $module_visibilities['skip_renewal'],
                    ],
                    [
                        'id' => 'settings-feature-manager',
                        'title' => __('Feature Manager', 'arraysubs'),
                        'path' => '/settings/feature-manager',
                        'visiblity' => $module_visibilities['feature_manager'],
                    ],
                ],
            ],
            [
                'id' => 'shortcodes',
                'title' => __('Shortcodes', 'arraysubs'),
                'icon' => 'Code',
                'path' => '/shortcodes',
            ],
            [
                'id' => 'audits',
                'title' => __('Audits [beta]', 'arraysubs'),
                'icon' => 'Activity',
                'children' => [
                    [
                        'id' => 'activity-audits',
                        'title' => __('Activity Audits', 'arraysubs'),
                        'path' => '/audits/activity-audits',
                        'visiblity' => $module_visibilities['audits'],
                    ],
                    [
                        'id' => 'gateway-logs',
                        'title' => __('Gateway Logs', 'arraysubs'),
                        'path' => '/settings/gateways',
                        'visiblity' => $module_visibilities['automatic_payments'],
                    ],
                    [
                        'id' => 'renewal-failures',
                        'title' => __('Renewal Failures', 'arraysubs'),
                        'path' => '/audits/renewal-failures',
                        'visiblity' => $module_visibilities['audits'],
                    ],
                    [
                        'id' => 'portal-action-failures',
                        'title' => __('Portal Action Failures', 'arraysubs'),
                        'path' => '/audits/portal-action-failures',
                        'visiblity' => $module_visibilities['audits'],
                    ],
                    [
                        'id' => 'access-rule-conflicts',
                        'title' => __('Access-Rule Conflicts', 'arraysubs'),
                        'path' => '/audits/access-rule-conflicts',
                        'visiblity' => $module_visibilities['audits'],
                    ],
                    [
                        'id' => 'scheduled-job-logs',
                        'title' => __('Scheduled-Job Logs', 'arraysubs'),
                        'path' => '/audits/scheduled-job-logs',
                        'visiblity' => $module_visibilities['audits'],
                    ],
                ],
            ],
            [
                'id' => 'easy-setup',
                'title' => __('Easy Setup', 'arraysubs'),
                'icon' => 'Settings2',
                'path' => '/easy-setup',
            ],
            [
                'id' => 'license',
                'title' => __('License', 'arraysubs'),
                'icon' => 'KeyRound',
                'path' => '/license',
                'visiblity' => defined('ARRAYSUBSPRO_VERSION') ? 1 : 0,
            ],
            [
                'id' => 'help',
                'title' => __('Help', 'arraysubs'),
                'path' => '/help',
            ],
        ];

        $items = apply_filters('arraysubs_main_admin_menu_items', $items);

        return array_map([self::class, 'normalizeMenuItem'], $items);
    }

    /**
     * Get menu items as JSON for JavaScript
     *
     * @return string
     */
    public static function getMenuItemsJson(): string
    {
        return wp_json_encode(self::getMenuItems());
    }
}
