<?php

namespace GriffinForms\Admin;

class Menu extends \GriffinForms\Admin\Format
{   
    public const PRO_ACTIVATION_SUCCESS_META_KEY = 'griffinforms_pro_activation_success_modal';

    protected $pages;
    protected $admin_slug;
    protected $package_state_resolver;
    protected $menu_provider_registry;
    
    protected function setPages()
    {
        $this->pages = Pages::getInstance();
    }

    protected function setPackageStateResolver()
    {
        $this->package_state_resolver = \GriffinForms\Includes\Packages\PackageStateResolver::getInstance();
    }

    protected function setMenuProviderRegistry()
    {
        $this->menu_provider_registry = \GriffinForms\Includes\Menus\MenuProviderRegistry::getInstance();
    }

    protected function getPackageState(string $package_id = 'pro'): array
    {
        $state = $this->package_state_resolver->getState();
        $packages = is_array($state['packages'] ?? null) ? $state['packages'] : [];

        return is_array($packages[$package_id] ?? null) ? $packages[$package_id] : [];
    }

    protected function getMenuIconFile(): string
    {
        return $this->config->getRootPath() . 'admin/images/griffinforms-icon.svg';
    }

    public static function isProEnabled(): bool
    {
        return (bool) \GriffinForms\Config::PRO_ENABLED;
    }

    protected function isProMenuStateActive(): bool
    {
        $pro_state = $this->getPackageState('pro');

        return !empty($pro_state['is_present'])
            && !empty($pro_state['is_active'])
            && (($pro_state['approval_status'] ?? '') === 'approved')
            && (($pro_state['compatibility_state'] ?? '') === 'compatible');
    }

    protected function getTopMenuLabel(string $page): string
    {
        $label = esc_html($this->lang->getText($page, 'menu'));

        if (self::isProEnabled() && $this->isProMenuStateActive()) {
            return esc_html__('GriffinForms Pro', 'griffinforms-form-builder');
        }

        return $label;
    }

    protected function isPluginPage(): bool
    {
        $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
        return $page && strncmp($page, $this->config::PREFIX, strlen($this->config::PREFIX)) === 0;
    }

    protected function isSettingsPage(): bool
    {
        $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
        $settings_prefix = $this->config::PREFIX . '-settings';
        return $page && strncmp($page, $settings_prefix, strlen($settings_prefix)) === 0;
    }

    protected function isPluginNonSettingsPage(): bool
    {
        return $this->isPluginPage() && !$this->isSettingsPage();
    }

    public function suppressThirdPartyNotices(): void
    {
        if (!$this->isPluginPage()) {
            return;
        }

        remove_all_actions('admin_notices');

        add_action('admin_notices', array($this, 'renderProWarningLayer'));
        add_action('admin_notices', array($this, 'renderProPromoLayer'));
    }

    protected function getProPageUrl(): string
    {
        return admin_url('admin.php?page=' . $this->config::PREFIX . '-pro');
    }

    protected function getDiagnosticsPageUrl(): string
    {
        return admin_url('admin.php?page=' . $this->config::PREFIX . '-diagnostics');
    }

    protected function getProBadgeHtml(string $variant = 'light'): string
    {
        $badge = new \GriffinForms\Admin\Html\Elements\ProBadge('Pro', $variant);
        ob_start();
        $badge->html();

        return (string) ob_get_clean();
    }

    protected function getCurrentPageSlug(): string
    {
        return isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
    }

    public static function storeProActivationSuccessRecord(array $record = []): void
    {
        $user_id = max(0, absint($record['updated_by'] ?? 0));
        if ($user_id <= 0) {
            $user_id = get_current_user_id();
        }

        if ($user_id <= 0) {
            return;
        }

        update_user_meta($user_id, self::PRO_ACTIVATION_SUCCESS_META_KEY, [
            'event' => 'activation_success',
            'source' => sanitize_key((string) ($record['source'] ?? 'pro_shell')),
            'updated_at' => sanitize_text_field((string) ($record['updated_at'] ?? gmdate('c'))),
            'updated_by' => $user_id,
        ]);
    }

    public static function clearProActivationSuccessRecord(int $user_id = 0): void
    {
        $user_id = max(0, $user_id);
        if ($user_id <= 0) {
            $user_id = get_current_user_id();
        }

        if ($user_id <= 0) {
            return;
        }

        delete_user_meta($user_id, self::PRO_ACTIVATION_SUCCESS_META_KEY);
    }

    protected function getPendingProActivationSuccessRecord(): array
    {
        $user_id = get_current_user_id();
        if ($user_id <= 0) {
            return [];
        }

        $record = get_user_meta($user_id, self::PRO_ACTIVATION_SUCCESS_META_KEY, true);
        return is_array($record) ? $record : [];
    }

    protected function clearPendingProActivationSuccessRecord(): void
    {
        self::clearProActivationSuccessRecord(get_current_user_id());
    }

    protected function shouldRenderProActivationSuccessModal(): bool
    {
        if (!$this->isPluginNonSettingsPage()) {
            return false;
        }

        $record = $this->getPendingProActivationSuccessRecord();
        if (empty($record)) {
            return false;
        }

        $pro_state = $this->getPackageState('pro');
        return !empty($pro_state['is_present'])
            && !empty($pro_state['is_active'])
            && (($pro_state['approval_status'] ?? '') === 'approved')
            && (($pro_state['compatibility_state'] ?? '') === 'compatible')
            && (($pro_state['entitlement_state'] ?? '') === 'verified_active');
    }

    protected function resolveProNoticeModel(): ?array
    {
        $pro_state = $this->getPackageState('pro');
        if (empty($pro_state)) {
            return null;
        }

        $compatibility_state = (string) ($pro_state['compatibility_state'] ?? 'unknown');
        $entitlement_state = (string) ($pro_state['entitlement_state'] ?? 'not_applicable');
        $recommended_action = (string) ($pro_state['recommended_user_action'] ?? '');

        if (!empty($pro_state['is_present']) && !empty($pro_state['is_active']) && $compatibility_state !== 'compatible' && $compatibility_state !== 'unknown') {
            return [
                'type' => 'warning',
                'title' => __('GriffinForms Pro needs attention', 'griffinforms-form-builder'),
                'message' => $this->getCompatibilityNoticeMessage($compatibility_state),
                'cta_label' => __('Open Pro Status', 'griffinforms-form-builder'),
                'cta_url' => $this->getProPageUrl(),
                'secondary_label' => __('View Diagnostics', 'griffinforms-form-builder'),
                'secondary_url' => $this->getDiagnosticsPageUrl(),
            ];
        }

        if (!empty($pro_state['is_present']) && !empty($pro_state['is_active'])) {
            if ($entitlement_state === 'key_not_entered') {
                return [
                    'type' => 'warning',
                    'title' => __('Activate GriffinForms Pro', 'griffinforms-form-builder'),
                    'message' => __('GriffinForms Pro is installed and compatible, but no license key has been entered yet. Enter or reactivate a key to unlock entitled Pro behavior.', 'griffinforms-form-builder'),
                    'cta_label' => __('Open Pro Page', 'griffinforms-form-builder'),
                    'cta_url' => $this->getProPageUrl(),
                    'secondary_label' => __('View Diagnostics', 'griffinforms-form-builder'),
                    'secondary_url' => $this->getDiagnosticsPageUrl(),
                ];
            }

            if ($entitlement_state === 'verified_inactive_or_expired') {
                return [
                    'type' => 'warning',
                    'title' => __('GriffinForms Pro license is inactive', 'griffinforms-form-builder'),
                    'message' => __('Your current GriffinForms Pro license is inactive or expired. Pro-dependent behavior will stay gated until the license is reactivated.', 'griffinforms-form-builder'),
                    'cta_label' => __('Review Pro Status', 'griffinforms-form-builder'),
                    'cta_url' => $this->getProPageUrl(),
                    'secondary_label' => __('View Diagnostics', 'griffinforms-form-builder'),
                    'secondary_url' => $this->getDiagnosticsPageUrl(),
                ];
            }

            if ($entitlement_state === 'unverified_connection_issue') {
                return [
                    'type' => 'warning',
                    'title' => __('GriffinForms Pro verification problem', 'griffinforms-form-builder'),
                    'message' => __('GriffinForms could not verify the Pro license recently. This is treated as a connection issue, not as an expired license.', 'griffinforms-form-builder'),
                    'cta_label' => __('Open Pro Status', 'griffinforms-form-builder'),
                    'cta_url' => $this->getProPageUrl(),
                    'secondary_label' => __('View Diagnostics', 'griffinforms-form-builder'),
                    'secondary_url' => $this->getDiagnosticsPageUrl(),
                ];
            }

            if ($entitlement_state === 'grace_period') {
                $grace_expires_at = trim((string) ($pro_state['grace_expires_at'] ?? ''));
                $message = __('GriffinForms Pro is temporarily running in a grace period because license verification could not be completed recently.', 'griffinforms-form-builder');
                if ($grace_expires_at !== '') {
                    $message .= ' ' . sprintf(
                        /* translators: %s is an ISO-like timestamp */
                        __('Current grace expiry: %s.', 'griffinforms-form-builder'),
                        $grace_expires_at
                    );
                }

                return [
                    'type' => 'warning',
                    'title' => __('GriffinForms Pro is in grace period', 'griffinforms-form-builder'),
                    'message' => $message,
                    'cta_label' => __('Review Pro Status', 'griffinforms-form-builder'),
                    'cta_url' => $this->getProPageUrl(),
                    'secondary_label' => __('View Diagnostics', 'griffinforms-form-builder'),
                    'secondary_url' => $this->getDiagnosticsPageUrl(),
                ];
            }
        }

        if ($recommended_action === 'install_pro' || $recommended_action === 'activate_pro') {
            return null;
        }

        return null;
    }

    protected function getCompatibilityNoticeMessage(string $compatibility_state): string
    {
        if ($compatibility_state === 'incompatible_core_too_old') {
            return __('The installed GriffinForms Pro package requires a newer Core foundation state. Update Core before attempting Pro activation or entitlement recovery.', 'griffinforms-form-builder');
        }

        if ($compatibility_state === 'incompatible_package_too_old') {
            return __('The installed GriffinForms Pro package appears too old for the current GriffinForms Core foundation. Update Pro or replace the test package before continuing.', 'griffinforms-form-builder');
        }

        if ($compatibility_state === 'missing_required_core') {
            return __('GriffinForms Pro cannot operate because the required Core runtime is missing or unavailable.', 'griffinforms-form-builder');
        }

        return __('GriffinForms Pro is currently incompatible with this GriffinForms installation.', 'griffinforms-form-builder');
    }

    protected function resolveProPromoModel(): ?array
    {
        if (!$this->isPluginNonSettingsPage()) {
            return null;
        }

        if (is_array($this->resolveProNoticeModel())) {
            return null;
        }

        $page = $this->getCurrentPageSlug();
        if ($page !== $this->config::PREFIX . '-forms') {
            return null;
        }

        $pro_state = $this->getPackageState('pro');
        if (empty($pro_state)) {
            return null;
        }

        if (empty($pro_state['is_present'])) {
            return null;
        }

        if (empty($pro_state['is_active'])) {
            return [
                'type' => 'info',
                'eyebrow' => __('Core Preview', 'griffinforms-form-builder'),
                'title' => __('GriffinForms Pro is installed but not active', 'griffinforms-form-builder'),
                'message' => __('Core can already see the Pro package on this site. Activate it when you want to continue package, entitlement, and UI contract testing.', 'griffinforms-form-builder'),
                'cta_label' => __('Open Pro Status', 'griffinforms-form-builder'),
                'cta_url' => $this->getProPageUrl(),
            ];
        }

        return null;
    }

    public function renderProWarningLayer(): void
    {
        if (!self::isProEnabled() || !$this->isPluginPage()) {
            return;
        }

        $notice = $this->resolveProNoticeModel();
        if (!is_array($notice)) {
            return;
        }

        $type = sanitize_html_class((string) ($notice['type'] ?? 'warning'));
        $title = (string) ($notice['title'] ?? '');
        $message = (string) ($notice['message'] ?? '');
        $cta_label = (string) ($notice['cta_label'] ?? '');
        $cta_url = (string) ($notice['cta_url'] ?? '');
        $secondary_label = (string) ($notice['secondary_label'] ?? '');
        $secondary_url = (string) ($notice['secondary_url'] ?? '');

        echo '<div class="notice notice-' . esc_attr($type) . ' gf-pro-warning-layer">';
        echo '<p><strong>' . esc_html($title) . '</strong></p>';
        echo '<p>' . esc_html($message) . '</p>';

        if ($cta_label !== '' && $cta_url !== '') {
            echo '<p><a class="button button-primary" href="' . esc_url($cta_url) . '">' . esc_html($cta_label) . '</a>';
            if ($secondary_label !== '' && $secondary_url !== '') {
                echo ' <a class="button button-secondary" href="' . esc_url($secondary_url) . '">' . esc_html($secondary_label) . '</a>';
            }
            echo '</p>';
        }

        echo '</div>';
    }

    public function renderProPromoLayer(): void
    {
        if (!self::isProEnabled()) {
            return;
        }

        $promo = $this->resolveProPromoModel();
        if (!is_array($promo)) {
            return;
        }

        $type = sanitize_html_class((string) ($promo['type'] ?? 'info'));
        $eyebrow = (string) ($promo['eyebrow'] ?? '');
        $title = (string) ($promo['title'] ?? '');
        $message = (string) ($promo['message'] ?? '');
        $cta_label = (string) ($promo['cta_label'] ?? '');
        $cta_url = (string) ($promo['cta_url'] ?? '');

        echo '<div class="notice notice-' . esc_attr($type) . ' gf-pro-promo-layer" style="border-left-color:#111827;">';
        if ($eyebrow !== '') {
            echo '<p style="margin-bottom:6px;display:flex;align-items:center;gap:8px;flex-wrap:wrap;">';
            echo wp_kses_post($this->getProBadgeHtml('dark'));
            echo '<span style="display:inline-flex;align-items:center;border-radius:999px;padding:3px 10px;background:#111827;color:#fff;font-size:11px;font-weight:600;letter-spacing:.02em;text-transform:uppercase;">' . esc_html($eyebrow) . '</span>';
            echo '</p>';
        }
        echo '<p><strong>' . esc_html($title) . '</strong></p>';
        echo '<p>' . esc_html($message) . '</p>';

        if ($cta_label !== '' && $cta_url !== '') {
            echo '<p><a class="button button-secondary" href="' . esc_url($cta_url) . '">' . esc_html($cta_label) . '</a></p>';
        }

        echo '</div>';
    }

    public function renderProActivationSuccessModal(): void
    {
        if (!self::isProEnabled() || !$this->shouldRenderProActivationSuccessModal()) {
            return;
        }

        $record = $this->getPendingProActivationSuccessRecord();
        $source = sanitize_key((string) ($record['source'] ?? 'pro_shell'));
        $updated_at = sanitize_text_field((string) ($record['updated_at'] ?? ''));

        echo '<div class="modal fade" id="griffinforms-pro-activation-success-modal" tabindex="-1" aria-labelledby="griffinforms-pro-activation-success-title" aria-hidden="true">';
        echo '<div class="modal-dialog modal-dialog-centered">';
        echo '<div class="modal-content border-0 rounded-3 shadow-sm">';
        echo '<div class="modal-header border-bottom-0 pb-0">';
        echo '<h5 class="modal-title" id="griffinforms-pro-activation-success-title">' . esc_html__('GriffinForms Pro is active', 'griffinforms-form-builder') . '</h5>';
        echo '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="' . esc_attr__('Close', 'griffinforms-form-builder') . '"></button>';
        echo '</div>';
        echo '<div class="modal-body pt-2">';
        echo '<p class="mb-2">' . esc_html__('GriffinForms Pro is now verified and ready to use.', 'griffinforms-form-builder') . '</p>';
        echo '<p class="text-muted small mb-0">' . esc_html(sprintf(
            /* translators: 1: source key, 2: ISO timestamp */
            __('Activation source: %1$s. Recorded at: %2$s.', 'griffinforms-form-builder'),
            $source !== '' ? $source : 'pro_shell',
            $updated_at !== '' ? $updated_at : gmdate('c')
        )) . '</p>';
        echo '</div>';
        echo '<div class="modal-footer border-top-0">';
        echo '<a class="button button-secondary" href="' . esc_url($this->getDiagnosticsPageUrl()) . '">' . esc_html__('View Diagnostics', 'griffinforms-form-builder') . '</a>';
        echo '<a class="button button-primary" href="' . esc_url($this->getProPageUrl()) . '">' . esc_html__('Open Pro Status', 'griffinforms-form-builder') . '</a>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
        echo '<script>';
        echo '(function(){';
        echo 'var modalElement=document.getElementById("griffinforms-pro-activation-success-modal");';
        echo 'if(!modalElement||typeof window.bootstrap==="undefined"||typeof window.bootstrap.Modal==="undefined"){return;}';
        echo 'window.setTimeout(function(){';
        echo 'var instance=window.bootstrap.Modal.getOrCreateInstance(modalElement);';
        echo 'instance.show();';
        echo '},180);';
        echo '}());';
        echo '</script>';

        $this->clearPendingProActivationSuccessRecord();
    }
    
    private function topMenu()
    {
        $raw_page = $this->pages->menu_pages[1];
        $page = sanitize_title($raw_page);

        $this->admin_slug = $this->config::PREFIX . '-' . $page;
        add_menu_page(
            esc_html($this->lang->getText($page, 'title')),
            $this->getTopMenuLabel($page),
            'manage_options',
            $this->admin_slug,
            function() use ($page) {
                $file = plugin_dir_path(__FILE__) . 'views/1_' . $page . '.php';
                echo '<div class="griffinforms-container container-fluid" style="opacity:0">';
                if (file_exists($file)) {
                    include_once($file);
                } else {
                    echo '<div class="notice notice-error"><p>' . esc_html__('Admin page not found.', 'griffinforms-form-builder') . '</p></div>';
                }
                echo '</div>';
            },
            'data:image/svg+xml;base64,' . base64_encode(file_get_contents($this->getMenuIconFile())),
            50
        );
    }
    
    private function subMenu()
    {   
        foreach ($this->pages->menu_pages as $index => $raw_page)
        {
            if ($index != 1) {
                $page = sanitize_title($raw_page);
                $view_file = $index . '_' . $page . '.php';

                add_submenu_page(
                    $this->admin_slug,
                    esc_html($this->lang->getText($page, 'title')),
                    esc_html($this->lang->getText($page, 'menu')),
                    'manage_options',
                    $this->config::PREFIX . '-' . $page,
                    function() use ($view_file) {
                        $file = plugin_dir_path(__FILE__) . 'views/' . $view_file;
                        echo '<div class="griffinforms-container container-fluid" style="opacity:0">';
                        if (file_exists($file)) {
                            include_once($file);
                        } else {
                            echo '<div class="notice notice-error"><p>' . esc_html__('Admin page not found.', 'griffinforms-form-builder') . '</p></div>';
                        }
                        echo '</div>';
                    }
                );
            }
        }
    }
    
    private function internalPages()
    {
        foreach ($this->pages->internal_pages as $page)
        {
            $clean_slug = sanitize_title(str_replace('.php', '', $page));

            if (!self::isProEnabled() && in_array($clean_slug, ['pro', 'libraries'], true)) {
                continue;
            }

            $menu_slug = $this->config::PREFIX . '-' . $clean_slug;
    
            $hook_suffix = add_submenu_page(
                $this->admin_slug,
                $this->lang->getText($clean_slug, 'title'),
                '', // No menu title
                'manage_options',
                $menu_slug,
                function() use ($clean_slug) {
                    $this->includePage($clean_slug . '.php');
                }
            );

            if ($clean_slug === 'onboarding' && is_string($hook_suffix) && $hook_suffix !== '') {
                add_action('load-' . $hook_suffix, array($this, 'prepareOnboardingPageMode'));
            }
        }
    }

    public function prepareOnboardingPageMode()
    {
        add_filter('admin_body_class', array($this, 'addOnboardingAdminBodyClass'));
        add_action('admin_head', array($this, 'printOnboardingPageHeadBootstrap'), 1);
    }

    public function addOnboardingAdminBodyClass($classes)
    {
        $classes = is_string($classes) ? trim($classes) : '';

        return trim($classes . ' gf-onboarding-page');
    }

    public function printOnboardingPageHeadBootstrap()
    {
        echo '<style id="gf-onboarding-page-bootstrap">';
        echo 'html.gf-onboarding-page{margin-top:0!important;padding-top:0!important;min-height:100%;background-color:#fffdfc;background-image:radial-gradient(circle at 18% 14%, rgba(246,109,109,.14) 0, rgba(246,109,109,.05) 22%, rgba(255,255,255,0) 48%),radial-gradient(circle at 82% 22%, rgba(246,109,109,.10) 0, rgba(246,109,109,.04) 20%, rgba(255,255,255,0) 44%),radial-gradient(circle at 56% 78%, rgba(232,90,90,.07) 0, rgba(232,90,90,.025) 18%, rgba(255,255,255,0) 40%),radial-gradient(rgba(246,109,109,.10) .6px, transparent .7px),radial-gradient(rgba(29,36,51,.04) .5px, transparent .6px);background-position:0 0,0 0,0 0,0 0,14px 11px;background-size:auto,auto,auto,19px 19px,23px 23px;background-repeat:repeat;}';
        echo 'body.gf-onboarding-page{min-height:100%;background-color:#fffdfc;background-image:radial-gradient(circle at 18% 14%, rgba(246,109,109,.14) 0, rgba(246,109,109,.05) 22%, rgba(255,255,255,0) 48%),radial-gradient(circle at 82% 22%, rgba(246,109,109,.10) 0, rgba(246,109,109,.04) 20%, rgba(255,255,255,0) 44%),radial-gradient(circle at 56% 78%, rgba(232,90,90,.07) 0, rgba(232,90,90,.025) 18%, rgba(255,255,255,0) 40%),radial-gradient(rgba(246,109,109,.10) .6px, transparent .7px),radial-gradient(rgba(29,36,51,.04) .5px, transparent .6px);background-position:0 0,0 0,0 0,0 0,14px 11px;background-size:auto,auto,auto,19px 19px,23px 23px;background-repeat:repeat;}';
        echo 'body.gf-onboarding-page #wpwrap,body.gf-onboarding-page #wpcontent,body.gf-onboarding-page #wpbody,body.gf-onboarding-page #wpbody-content{background:transparent!important;}';
        echo 'body.gf-onboarding-page #wpwrap{position:relative;min-height:100vh;background-color:#fffdfc;background-image:radial-gradient(circle at 18% 14%, rgba(246,109,109,.14) 0, rgba(246,109,109,.05) 22%, rgba(255,255,255,0) 48%),radial-gradient(circle at 82% 22%, rgba(246,109,109,.10) 0, rgba(246,109,109,.04) 20%, rgba(255,255,255,0) 44%),radial-gradient(circle at 56% 78%, rgba(232,90,90,.07) 0, rgba(232,90,90,.025) 18%, rgba(255,255,255,0) 40%),radial-gradient(rgba(246,109,109,.10) .6px, transparent .7px),radial-gradient(rgba(29,36,51,.04) .5px, transparent .6px);background-position:0 0,0 0,0 0,0 0,14px 11px;background-size:auto,auto,auto,19px 19px,23px 23px;}';
        echo 'body.gf-onboarding-page #wpadminbar,body.gf-onboarding-page #adminmenumain,body.gf-onboarding-page #screen-meta-links,body.gf-onboarding-page .update-nag,body.gf-onboarding-page .notice:not(.gf-onboarding-error-notice),body.gf-onboarding-page .is-dismissible:not(.gf-onboarding-error-notice),body.gf-onboarding-page #wpfooter{display:none!important;}';
        echo 'body.gf-onboarding-page #wpcontent,body.gf-onboarding-page #wpbody-content{margin-left:0!important;padding-left:0!important;}';
        echo 'body.gf-onboarding-page #wpbody{padding-top:0!important;}';
        echo 'body.gf-onboarding-page #wpbody-content>.griffinforms-container{max-width:none;padding:0;min-height:100vh;display:flex;align-items:flex-start;justify-content:center;position:relative;z-index:1;}';
        echo 'body.gf-onboarding-page #wpbody-content .wrap.gf-onboarding-wrap{margin:0;padding:40px 32px 48px;width:min(1280px,100%);display:flex;flex-direction:column;justify-content:flex-start;}';
        echo '</style>';
        echo '<script>document.documentElement.classList.add("gf-onboarding-page");</script>';
    }

    private function settingsPages()
    {
        foreach ($this->pages->settings_pages as $index => $page)
        {
            $clean_slug = sanitize_title(str_replace('.php', '', $page));
            $menu_slug = $this->config::PREFIX . '-settings-' . $clean_slug;
    
            if ($index === 0) {
                // First one is visible in menu
                add_submenu_page(
                    $this->admin_slug,
                    $this->lang->getText($clean_slug, 'title'),
                    $this->lang->getText('settings', 'menu'),
                    'manage_options',
                    $menu_slug,
                    function() use ($clean_slug) {
                        $this->includeSettingsPage($clean_slug . '.php');
                    }
                );
            } else {
                // Hidden pages, still accessible by URL
                add_submenu_page(
                    $this->admin_slug,
                    $this->lang->getText($clean_slug, 'title'),
                    '', // No menu title = hidden in UI
                    'manage_options',
                    $menu_slug,
                    function() use ($clean_slug) {
                        $this->includeSettingsPage($clean_slug . '.php');
                    }
                );
            }
        }
    }

    private function providerPages()
    {
        $providers = $this->menu_provider_registry->getAll();
        if (empty($providers)) {
            return;
        }

        uasort($providers, static function (array $left, array $right) {
            return ((int) ($left['position'] ?? 0)) <=> ((int) ($right['position'] ?? 0));
        });

        foreach ($providers as $provider) {
            $parent_slug = (string) ($provider['parent_slug'] ?? $this->admin_slug);
            $page_title = (string) ($provider['page_title'] ?? '');
            $menu_title = (string) ($provider['menu_title'] ?? '');
            $capability = (string) ($provider['capability'] ?? 'manage_options');
            $page_slug = (string) ($provider['page_slug'] ?? '');
            $visibility = (string) ($provider['visibility'] ?? 'submenu');
            $render_callback = $provider['render_callback'] ?? null;

            if ($page_slug === '' || !is_callable($render_callback)) {
                continue;
            }

            add_submenu_page(
                $parent_slug !== '' ? $parent_slug : $this->admin_slug,
                $page_title,
                $visibility === 'submenu' ? $menu_title : '',
                $capability !== '' ? $capability : 'manage_options',
                $page_slug,
                function () use ($render_callback) {
                    call_user_func($render_callback);
                }
            );
        }
    }
    
    private function includePage($page)
    {
        echo '<div class="griffinforms-container container-fluid" style="opacity:0">';
        include_once(plugin_dir_path(__FILE__) . 'views/' . $page);
        echo '</div>';
    }
    
    private function includeSettingsPage($page)
    {
        echo '<div class="wrap">'; 
        include_once(plugin_dir_path(__FILE__) . 'views/settings/' . $page);
        echo '</div>';
    }
    
    public function addPages()
    {
        $this->topMenu();
        $this->subMenu();
        $this->internalPages();
        $this->settingsPages();
        $this->providerPages();
    }
    
    public function renameFirstSubmenuItem()
    {
        global $submenu;

        if (isset($submenu['griffinforms-forms'][0])) {
            $submenu['griffinforms-forms'][0][0] = esc_html__('Forms', 'griffinforms-form-builder');
        }
    }

    public function setSubmissionsMenuBadge()
    {
        global $submenu, $wpdb;

        if (empty($submenu[$this->admin_slug])) {
            return;
        }

        $table = $this->config->getTable('submission');
        $count = (int) $wpdb->get_var(
            $wpdb->prepare("SELECT COUNT(*) FROM %i WHERE is_read = %d", $table, 0)
        );

        if ($count <= 0) {
            return;
        }

        $label = $count > 999 ? '999+' : (string) $count;

        $badge = ' <span class="update-plugins count-' . absint($count) . '">'
               . '<span class="plugin-count">' . esc_html($label) . '</span>'
               . '</span>';

        $submissions_slug = $this->config::PREFIX . '-submissions';

        foreach ($submenu[$this->admin_slug] as &$item) {
            if (isset($item[2]) && $item[2] === $submissions_slug) {
                $item[0] = esc_html__('Submissions', 'griffinforms-form-builder') . $badge;
                break;
            }
        }
        unset($item);
    }
    
    private function isAdminFooterPage(): bool
    {
        if (!$this->isPluginPage()) {
            return false;
        }

        $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
        $excluded = [
            $this->config::PREFIX . '-onboarding',
            $this->config::PREFIX . '-form',
        ];

        return !in_array($page, $excluded, true);
    }

    public function filterAdminFooterText(string $text): string
    {
        if (!$this->isAdminFooterPage()) {
            return $text;
        }

        $links = [
            __('Docs', 'griffinforms-form-builder')      => 'https://griffinforms.com/docs/',
            __('Support', 'griffinforms-form-builder')   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            __('Changelog', 'griffinforms-form-builder') => 'https://griffinforms.com/releases/',
            __('Feedback', 'griffinforms-form-builder')  => 'https://griffinforms.com/contact.php',
        ];

        $parts = [];
        foreach ($links as $label => $url) {
            $parts[] = '<a href="' . esc_url($url) . '" target="_blank" rel="noopener noreferrer">' . esc_html($label) . '</a>';
        }

        $review_url  = 'https://wordpress.org/support/plugin/griffinforms-form-builder/reviews/#new-post';
        $review_link = '<a href="' . esc_url($review_url) . '" target="_blank" rel="noopener noreferrer">&#9733;&nbsp;' . esc_html__('Leave a review', 'griffinforms-form-builder') . '</a>';

        $griffin_path = 'M61.52,59.726c0.052,2.946 1.394,5.223 2.948,7.387c2.213,3.083 4.982,5.667 7.678,8.305c6.051,5.922 8.549,13.308 9.073,21.551c0.101,1.594 -0.454,2.187 -2.103,2.17c-6.705,-0.066 -13.425,0.264 -20.113,-0.079c-11.43,-0.587 -21.638,-4.493 -29.968,-12.562c-3.166,-3.067 -5.062,-6.998 -6.549,-11.118c-0.338,-0.934 -0.475,-1.972 -1.28,-2.783c-0.877,0.227 -1.142,1.009 -1.524,1.659c-1.798,3.055 -3.397,6.245 -6.031,8.721c-0.369,0.347 -0.713,0.725 -1.106,1.043c-1.461,1.182 -2.194,1.049 -3.018,-0.598c-1.552,-3.097 -2.526,-6.396 -2.905,-9.817c-0.941,-8.486 0.212,-16.802 2.337,-25.013c0.211,-0.813 0.558,-1.591 0.844,-2.384c0.259,-0.716 0.521,-1.43 0.878,-2.407c-0.815,0.316 -1.328,0.509 -1.837,0.714c-1.814,0.729 -2.447,0.358 -2.569,-1.633c-0.087,-1.412 0.259,-2.791 0.569,-4.159c1.591,-7.034 5.155,-12.782 11.109,-16.962c0.415,-0.292 0.805,-0.621 1.233,-0.891c1.098,-0.694 1.113,-1.358 0.135,-2.238c-2.846,-2.562 -4.709,-5.727 -5.464,-9.494c-0.455,-2.268 -0.264,-4.481 0.877,-6.551c1.175,-2.133 2.538,-2.335 4.334,-0.823c5.472,4.605 11.825,7.353 18.841,8.509c8.137,1.341 16.374,2.13 24.335,4.424c3.726,1.074 7.463,2.091 10.587,4.63c2.795,2.272 4.131,5.101 3.795,8.752c3.717,0.523 7.063,1.542 10.019,3.66c6.746,4.834 8.613,12.819 5.889,20.1c-0.149,0.398 -0.232,0.918 -0.831,0.93c-0.508,0.009 -0.602,-0.45 -0.809,-0.762c-2.036,-3.075 -5.07,-4.385 -8.582,-4.633c-5.148,-0.365 -10.075,0.974 -14.852,2.606c-4.388,1.498 -6.059,5.091 -5.94,9.746m1.432,-27.299c0.57,-0.473 1.02,-1.04 1.346,-1.708c0.783,-1.605 0.478,-2.207 -1.28,-2.245c-2.752,-0.06 -5.506,-0.032 -8.259,-0.031c-0.447,-0 -0.951,-0.019 -1.157,0.491c-0.217,0.536 0.215,0.857 0.559,1.109c0.86,0.629 1.722,1.273 2.656,1.778c1.861,1.006 3.797,1.718 6.135,0.606Z';

        $icon = '<svg class="gf-admin-footer__icon" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="' . $griffin_path . '" fill="#bbb" fill-rule="nonzero"/></svg>';

        $wordmark_file = plugin_dir_path(dirname(__FILE__)) . 'admin/images/wordmark.svg';
        $wordmark_raw  = file_get_contents($wordmark_file);
        $wordmark      = preg_replace('/<svg\b[^>]*>/', '<svg class="gf-admin-footer__wordmark" viewBox="0 0 4185 310" xmlns="http://www.w3.org/2000/svg" aria-label="GriffinForms" role="img" focusable="false">', $wordmark_raw, 1);

        $version = '<span class="gf-admin-footer__version">v' . esc_html($this->config::VERSION) . '</span>';

        $pro_badge = $this->isProMenuStateActive()
            ? '<a href="' . esc_url(admin_url('admin.php?page=griffinforms-settings-license')) . '" class="gf-admin-footer__pro-badge"><span class="gf-admin-footer__pro-badge__text">' . esc_html__('Pro', 'griffinforms-form-builder') . '</span></a>'
            : '';

        return '<span class="gf-admin-footer__brand">' . $icon . $wordmark . $pro_badge . $version . '</span>'
            . '<span class="gf-admin-footer__sep">|</span>'
            . implode(' &middot; ', $parts)
            . '<span class="gf-admin-footer__sep">|</span>'
            . $review_link;
    }

    public function filterUpdateFooter(string $text): string
    {
        if (!$this->isAdminFooterPage()) {
            return $text;
        }

        return '';
    }

    public function addPluginPageBodyClass(string $classes): string
    {
        if ($this->isAdminFooterPage()) {
            $classes = trim($classes . ' gf-is-plugin-page');
        }

        return $classes;
    }

    public function __construct()
    {
        $this->setAll();
        add_action('admin_menu', array($this, 'addPages'));
        add_action('admin_menu', array($this, 'renameFirstSubmenuItem'));
        add_action('admin_menu', array($this, 'setSubmissionsMenuBadge'), 20);
        add_action('current_screen', array($this, 'suppressThirdPartyNotices'));
        add_action('admin_notices', array($this, 'renderProWarningLayer'));
        add_action('admin_notices', array($this, 'renderProPromoLayer'));
        add_action('admin_footer', array($this, 'renderProActivationSuccessModal'));
        add_filter('admin_footer_text', array($this, 'filterAdminFooterText'));
        add_filter('update_footer', array($this, 'filterUpdateFooter'), 11);
        add_filter('admin_body_class', array($this, 'addPluginPageBodyClass'));
    }
}
