<?php
/**
 * Admin Menu
 *
 * @package _121Digital\Connect
 */

namespace _121Digital\Connect\Admin;

use _121Digital\Connect\Admin\Services\NoticeService;
use _121Digital\Connect\Integration\Matomo;
use _121Digital\Connect\Registration\RegistrationManager;
use _121Digital\Connect\User\UserRoles;

/**
 * Admin Menu Class
 *
 * Handles admin menu and settings page
 */
class AdminMenu
{
    /**
     * Registration Manager instance
     *
     * @var RegistrationManager
     */
    private RegistrationManager $registrationManager;

    /**
     * Matomo instance
     *
     * @var Matomo
     */
    private Matomo $matomo;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->registrationManager = new RegistrationManager();
        $this->matomo = new Matomo();
    }

    /**
     * List of allowed menu slugs (WordPress core + explicitly allowed third-party)
     *
     * @var array<string>
     */
    private array $allowedMenuSlugs = [
        // WordPress Core
        'index.php',                    // Dashboard
        'separator1',                   // Separator
        'edit.php',                     // Posts (Blog Posts)
        'upload.php',                   // Media (Media Library)
        'edit.php?post_type=page',      // Pages
        'edit-comments.php',            // Comments
        'separator2',                   // Separator
        'themes.php',                   // Appearance
        'plugins.php',                  // Plugins
        'users.php',                    // Users
        'profile.php',                  // Account Settings (Profile)
        'tools.php',                    // Tools
        'options-general.php',          // Settings (Site Settings)
        'separator-last',               // Separator

        // Custom Plugin Pages from the menu (ALWAYS VISIBLE - CRITICAL)
        'admin.php?page=sc-contact-requests',  // Contact Requests (full URL)
        'sc-contact-requests',                 // Contact Requests (menu slug)
        'toplevel_page_sc-contact-requests',   // Contact Requests (WordPress ID format)
        'admin.php?page=sc-contact-requests-view', // Contact Requests Detail View
        'sc-contact-requests-view',            // Contact Requests Detail View (slug)
        'admin.php?page=site-theme',           // Site Theme
        'admin.php?page=site-connector',       // 121 Site Connector

        // Elementor - explicitly allowed (multiple variations to ensure compatibility)
        'admin.php?page=elementor',            // Builder Settings (Elementor main)
        'elementor',                           // Builder Settings (short form)
        'toplevel_page_elementor',             // Builder Settings (WordPress ID format)

        // Elementor Templates (multiple variations)
        'edit.php?post_type=elementor_library&tabs_group=library', // Templates (full URL)
        'edit.php?post_type=elementor_library',              // Templates (base URL)
        'menu-posts-elementor_library',                      // Templates (WordPress ID format)
        'elementor_library',                                 // Templates (post type)

        // Site Theme (multiple variations to ensure it works)
        'site-theme',                          // Site Theme (short form)
        'toplevel_page_site-theme',            // Site Theme (WordPress ID format)

        // Google Site Kit - explicitly allowed
        'googlesitekit-dashboard',             // Google Site Kit main
        'toplevel_page_googlesitekit-dashboard', // Google Site Kit (WordPress ID format)
        'google-site-kit',                     // Google Site Kit (alternative slug)
        'admin.php?page=googlesitekit-dashboard', // Google Site Kit (full URL)

        // Yoast SEO - explicitly allowed (multiple possible slugs)
        'wpseo_dashboard',                     // Yoast SEO Dashboard (main)
        'admin.php?page=wpseo_dashboard',      // Yoast SEO Dashboard (full URL)
        'toplevel_page_wpseo_dashboard',       // Yoast SEO Dashboard (WordPress ID format)
        'wpseo_titles',                        // Yoast SEO Search Appearance
        'wpseo_social',                        // Yoast SEO Social
        'wpseo_tools',                         // Yoast SEO Tools
        'wpseo_search_console',                // Yoast SEO Search Console
        'wpseo_redirects',                     // Yoast SEO Redirects (if premium)

        // Alternative Yoast SEO menu slugs (newer versions)
        'admin.php?page=wpseo_titles',         // Search Appearance (full URL)
        'admin.php?page=wpseo_social',         // Social (full URL)
        'admin.php?page=wpseo_tools',          // Tools (full URL)
        'admin.php?page=wpseo_search_console', // Search Console (full URL)
        'admin.php?page=wpseo_redirects',      // Redirects (full URL)

        // Main SEO menu (common in newer versions)
        'wpseo_workouts',                      // SEO Workouts
        'admin.php?page=wpseo_workouts',       // SEO Workouts (full URL)

        // Additional Yoast patterns that might be used
        'seo',                                 // Simple "SEO" menu
        'yoast',                              // Yoast menu
        'yoast-seo',                          // Yoast SEO menu
        'wordpress-seo',                       // WordPress SEO menu

        // Menu separators (WordPress uses these patterns)
        'separator',
        'separator-elementor',        // Note: Royal Addons (wpr-addons) is intentionally EXCLUDED
        // 'admin.php?page=wpr-addons',  // Royal Addons - BLOCKED
    ];

    /**
     * List of allowed submenu pages for third-party plugins
     *
     * @var array<string, array<string>>
     */
    private array $allowedSubmenus = [
        // Elementor submenus (multiple parent variations)
        'admin.php?page=elementor' => [
            'admin.php?page=elementor',
            'admin.php?page=elementor-settings',
            'admin.php?page=elementor-role-manager',
            'admin.php?page=elementor-element-manager',
            'admin.php?page=elementor-tools',
            'admin.php?page=e-form-submissions',
            'admin.php?page=elementor_custom_fonts',
            'admin.php?page=elementor_custom_icons',
            'admin.php?page=elementor_custom_code',
        ],
        'elementor' => [
            'admin.php?page=elementor',
            'admin.php?page=elementor-settings',
            'admin.php?page=elementor-role-manager',
            'admin.php?page=elementor-element-manager',
            'admin.php?page=elementor-tools',
            'admin.php?page=e-form-submissions',
            'admin.php?page=elementor_custom_fonts',
            'admin.php?page=elementor_custom_icons',
            'admin.php?page=elementor_custom_code',
        ],

        // Elementor Templates submenus (multiple parent variations)
        'edit.php?post_type=elementor_library&tabs_group=library' => [
            'edit.php?post_type=elementor_library&tabs_group=library',
            'admin.php?page=elementor-app&ver=3.29.0#site-editor/promotion',
            'edit.php?post_type=elementor_library&page=e-floating-buttons',
            'edit.php?post_type=elementor_library&page=popup_templates',
            'edit.php?post_type=elementor_library#add_new',
        ],
        'edit.php?post_type=elementor_library' => [
            'edit.php?post_type=elementor_library&tabs_group=library',
            'admin.php?page=elementor-app&ver=3.29.0#site-editor/promotion',
            'edit.php?post_type=elementor_library&page=e-floating-buttons',
            'edit.php?post_type=elementor_library&page=popup_templates',
            'edit.php?post_type=elementor_library#add_new',
        ],
        'elementor_library' => [
            'edit.php?post_type=elementor_library&tabs_group=library',
            'admin.php?page=elementor-app&ver=3.29.0#site-editor/promotion',
            'edit.php?post_type=elementor_library&page=e-floating-buttons',
            'edit.php?post_type=elementor_library&page=popup_templates',
            'edit.php?post_type=elementor_library#add_new',
        ],

        // Yoast SEO submenus (multiple parent variations)
        'wpseo_dashboard' => [
            'admin.php?page=wpseo_dashboard',
            'admin.php?page=wpseo_titles',
            'admin.php?page=wpseo_social',
            'admin.php?page=wpseo_tools',
            'admin.php?page=wpseo_search_console',
            'admin.php?page=wpseo_redirects',
            'admin.php?page=wpseo_workouts',
        ],
        'admin.php?page=wpseo_dashboard' => [
            'admin.php?page=wpseo_dashboard',
            'admin.php?page=wpseo_titles',
            'admin.php?page=wpseo_social',
            'admin.php?page=wpseo_tools',
            'admin.php?page=wpseo_search_console',
            'admin.php?page=wpseo_redirects',
            'admin.php?page=wpseo_workouts',
        ],
        'toplevel_page_wpseo_dashboard' => [
            'admin.php?page=wpseo_dashboard',
            'admin.php?page=wpseo_titles',
            'admin.php?page=wpseo_social',
            'admin.php?page=wpseo_tools',
            'admin.php?page=wpseo_search_console',
            'admin.php?page=wpseo_redirects',
            'admin.php?page=wpseo_workouts',
        ],

        // Contact Requests submenus (ALWAYS VISIBLE - CRITICAL)
        'sc-contact-requests' => [
            'sc-contact-requests',
            'admin.php?page=sc-contact-requests',
            'sc-contact-requests-view',
            'admin.php?page=sc-contact-requests-view',
        ],
        'admin.php?page=sc-contact-requests' => [
            'sc-contact-requests',
            'admin.php?page=sc-contact-requests',
            'sc-contact-requests-view',
            'admin.php?page=sc-contact-requests-view',
        ],
        'toplevel_page_sc-contact-requests' => [
            'sc-contact-requests',
            'admin.php?page=sc-contact-requests',
            'sc-contact-requests-view',
            'admin.php?page=sc-contact-requests-view',
        ],

        // Settings submenus
        'options-general.php' => [
            'options-general.php',
            'options-media.php',
            'options-general.php?page=site-connector',
        ],

        // Posts (Blog Posts) submenus
        'edit.php' => [
            'edit.php',
            'post-new.php',
        ],

        // Media Library submenus
        'upload.php' => [
            'upload.php',
            'media-new.php',
        ],

        // Pages submenus
        'edit.php?post_type=page' => [
            'edit.php?post_type=page',
            'post-new.php?post_type=page',
        ],

        // Note: Royal Addons submenus are intentionally EXCLUDED
        // 'admin.php?page=wpr-addons' => [...] // BLOCKED
    ];

    /**
     * Register admin menu
     *
     * @return void
     */
    public function register(): void
    {
        add_action('admin_menu', [$this, 'addMenuPage']);
        add_action('admin_init', [$this, 'renameBlogPostItem']);
        add_action('admin_init', [$this, 'renameMediaItem']);
        add_action('admin_head', [$this, 'removeMySitesFromDashboardItem'], 999);
        add_action('admin_head', [$this, 'maybeRemoveBaseThemeFromAdminMenu'], 999);

        // Reposition Contact Requests menu to top (run before filtering)
        add_action('admin_menu', [$this, 'repositionContactRequestsMenu'], 998);

        // Add third-party menu filtering (run late to catch all plugins)
        add_action('admin_menu', [$this, 'filterThirdPartyMenus'], 999);
    }

    public function maybeRemoveBaseThemeFromAdminMenu(): void
    {
        // do not remove for administrators
        if (UserRoles::isContextAdministrator()) {
            return;
        }

        global $menu;
        foreach ($menu as $key => $value) {
            if (isset($value[0]) && $value[0] === 'Base Theme') {
                unset($menu[$key]);
            }
        }
    }

    public function removeMySitesFromDashboardItem(): void
    {
        if (!\_121Digital\Connect\Core\Environment::isMultisiteNode()) {
            return;
        }

        // remove the my sites menu item
        echo '<style>
            #menu-dashboard .wp-submenu li a[href*="my-sites"] {
                display: none !important;
            }
        </style>';
    }

    /**
     * Reposition Contact Requests menu to appear near the top, after Dashboard and Google Site Kit
     *
     * @return void
     */
    public function repositionContactRequestsMenu(): void
    {
        global $menu;

        // Skip if menu global is not available
        if (!is_array($menu)) {
            return;
        }

        // Find the Contact Requests menu item
        $contactRequestsItem = null;
        $contactRequestsKey = null;

        foreach ($menu as $key => $value) {
            if (isset($value[2]) && strpos($value[2], 'sc-contact-requests') !== false) {
                $contactRequestsItem = $value;
                $contactRequestsKey = $key;
                break;
            }
        }

        // If Contact Requests menu is found, reposition it
        if ($contactRequestsItem && $contactRequestsKey !== null) {
            // Remove from current position
            unset($menu[$contactRequestsKey]);

            // Find a suitable position after Dashboard (2) and before Posts/Pages
            // Dashboard is at position 2
            // We want Contact Requests to be at position 3 or 4, before Posts (5) and Pages (20)
            $targetPosition = 3;

            // Check if position 3 is available, if not try 4, then 5
            $positionsToTry = [3, 4, 5];

            foreach ($positionsToTry as $pos) {
                if (!isset($menu[$pos])) {
                    $targetPosition = $pos;
                    break;
                }
            }

            // If all preferred positions are taken, find the next available slot after Dashboard
            if (isset($menu[$targetPosition])) {
                $targetPosition = 3;
                while (isset($menu[$targetPosition]) && $targetPosition < 10) {
                    $targetPosition++;
                }
            }

            // Insert at the target position
            $menu[$targetPosition] = $contactRequestsItem;

            // Re-sort the menu array to maintain proper order
            ksort($menu);
        }
    }

    public function renameBlogPostItem(): void
    {
        global $menu, $submenu;

        // Skip if menu globals are not available (e.g., during AJAX requests)
        if (!is_array($menu) || !is_array($submenu)) {
            return;
        }

        // Rename top-level "Posts" menu safely
        foreach ($menu as $key => $value) {
            if (isset($menu[$key][2]) && $menu[$key][2] === 'edit.php') {
                $menu[$key][0] = 'Blog Posts';
            }
        }

        // Rename submenu items under "Posts" safely
        if (isset($submenu['edit.php'])) {
            if (isset($submenu['edit.php'][5][0])) {
                $submenu['edit.php'][5][0] = 'All Blog Posts';
            }
            if (isset($submenu['edit.php'][10][0])) {
                $submenu['edit.php'][10][0] = 'Add Blog Post';
            }
            if (isset($submenu['edit.php'][16][0])) {
                $submenu['edit.php'][16][0] = 'Blog Tags';
            }
            if (isset($submenu['edit.php'][15][0])) {
                $submenu['edit.php'][15][0] = 'Blog Categories';
            }
        }
    }

    public function renameMediaItem(): void
    {
        global $menu, $submenu;

        // Skip if menu globals are not available (e.g., during AJAX requests)
        if (!is_array($menu) || !is_array($submenu)) {
            return;
        }

        // Rename top-level "Media" menu safely
        foreach ($menu as $key => $value) {
            if (isset($menu[$key][2]) && $menu[$key][2] === 'upload.php') {
                $menu[$key][0] = 'Media Library';
            }
        }

        // Rename submenu items under "Media" safely
        if (isset($submenu['upload.php'])) {
            if (isset($submenu['upload.php'][5][0])) {
                $submenu['upload.php'][5][0] = 'Library';
            }
            if (isset($submenu['upload.php'][10][0])) {
                $submenu['upload.php'][10][0] = 'Upload Media Item';
            }
        }
    }

    /**
     * Filter out third-party menu items that are not explicitly allowed
     *
     * @return void
     */
    public function filterThirdPartyMenus(): void
    {
        global $menu, $submenu;

        // Skip filtering for administrators
        if (UserRoles::isContextAdministrator()) {
            return;
        }

        // Skip if menu globals are not available
        if (!is_array($menu) || !is_array($submenu)) {
            return;
        }

        // Allow other parts of the system to modify the allowed menus
        $this->allowedMenuSlugs = apply_filters('121_connect_allowed_menu_slugs', $this->allowedMenuSlugs);
        $this->allowedSubmenus = apply_filters('121_connect_allowed_submenus', $this->allowedSubmenus);

        // Filter main menu items
        $this->filterMainMenuItems();

        // Filter submenu items
        $this->filterSubmenuItems();
    }

    /**
     * Filter main menu items
     *
     * @return void
     */
    private function filterMainMenuItems(): void
    {
        global $menu;

        foreach ($menu as $key => $menuItem) {
            if (!isset($menuItem[2])) {
                continue;
            }

            $slug = $menuItem[2];

            // NEVER remove Contact Requests menu - always visible for all users
            if (strpos($slug, 'sc-contact-requests') !== false) {
                continue;
            }

            // Skip if menu item is in allowed list
            if (in_array($slug, $this->allowedMenuSlugs, true)) {
                continue;
            }

            // Skip separators (they don't have real slugs)
            if (strpos($slug, 'separator') === 0) {
                continue;
            }

            // Remove the menu item
            unset($menu[$key]);
        }
    }

    /**
     * Filter submenu items
     *
     * @return void
     */
    private function filterSubmenuItems(): void
    {
        global $submenu;

        foreach ($submenu as $parentSlug => $subMenuItems) {
            // NEVER remove Contact Requests submenus - always visible for all users
            if (strpos($parentSlug, 'sc-contact-requests') !== false) {
                continue;
            }

            // If parent menu is not allowed, remove all submenus
            if (!in_array($parentSlug, $this->allowedMenuSlugs, true)) {
                unset($submenu[$parentSlug]);
                continue;
            }

            // If parent menu is allowed but has specific submenu restrictions
            if (isset($this->allowedSubmenus[$parentSlug])) {
                $allowedSubItems = $this->allowedSubmenus[$parentSlug];

                foreach ($subMenuItems as $subKey => $subMenuItem) {
                    if (!isset($subMenuItem[2])) {
                        continue;
                    }

                    $subSlug = $subMenuItem[2];

                    // NEVER remove Contact Requests submenu items
                    if (strpos($subSlug, 'sc-contact-requests') !== false) {
                        continue;
                    }

                    if (!in_array($subSlug, $allowedSubItems, true)) {
                        unset($submenu[$parentSlug][$subKey]);
                    }
                }
            }
        }
    }

    /**
     * Add a menu slug to the allowed list (for dynamic configuration)
     *
     * @param string $slug The menu slug to allow
     * @return void
     */
    public function allowMenuSlug(string $slug): void
    {
        if (!in_array($slug, $this->allowedMenuSlugs, true)) {
            $this->allowedMenuSlugs[] = $slug;
        }
    }

    /**
     * Remove a menu slug from the allowed list
     *
     * @param string $slug The menu slug to disallow
     * @return void
     */
    public function disallowMenuSlug(string $slug): void
    {
        $key = array_search($slug, $this->allowedMenuSlugs, true);
        if ($key !== false) {
            unset($this->allowedMenuSlugs[$key]);
            $this->allowedMenuSlugs = array_values($this->allowedMenuSlugs); // Re-index array
        }
    }

    /**
     * Get the list of currently allowed menu slugs
     *
     * @return array<string>
     */
    public function getAllowedMenuSlugs(): array
    {
        return $this->allowedMenuSlugs;
    }

    /**
     * Add submenu page
     *
     * @return void
     */
    public function addMenuPage(): void
    {
        add_submenu_page(
            'options-general.php',
            '121 Site Connector',
            '121 Site Connector',
            'manage_options',
            'site-connector',
            [$this, 'renderPage']
        );
    }

    /**
     * Check for plugin updates
     *
     * @return array
     */
    private function checkForUpdates(): array
    {
        if (!current_user_can('update_plugins')) {
            return ['success' => false, 'message' => 'You do not have permission to update plugins.'];
        }

        delete_site_transient('update_plugins');
        wp_update_plugins();

        $pluginFile = '121-site-connector/121-site-connector.php';
        $updatePlugins = get_site_transient('update_plugins');

        if (isset($updatePlugins->response[$pluginFile])) {
            $newVersion = $updatePlugins->response[$pluginFile]->new_version;
            $detailsUrl = self_admin_url('update.php?action=upgrade-plugin&plugin=' . urlencode($pluginFile) . '&_wpnonce=' . wp_create_nonce('upgrade-plugin_' . $pluginFile));

            return [
                'success' => false,
                'message' => "A new version ($newVersion) of Site Connector is available.",
                'update_url' => $detailsUrl,
            ];
        }

        return ['success' => true, 'message' => 'You are using the latest version of the Site Connector plugin.'];
    }

    /**
     * Render the admin page
     *
     * @return void
     */
    public function renderPage(): void
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        $isRegistered = get_option('sc_site_registered');
        $hasRegistrationData = $this->registrationManager->hasRegistrationData();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $result = null;

            if (isset($_POST['sc_connect_confirm']) && !$isRegistered) {
                $result = $this->registrationManager->handleRegistration();
            } elseif (isset($_POST['sc_disconnect_confirm'])) {
                $result = $this->registrationManager->disconnect();
            } elseif (isset($_POST['sc_verify_confirm'])) {
                $result = $this->registrationManager->verify();
            } elseif (isset($_POST['sc_check_updates_confirm']) && check_admin_referer('sc_check_updates_action', 'sc_check_updates_nonce')) {
                $result = $this->checkForUpdates();
            } elseif (isset($_POST['sc_update_matomo_tracking_code'])) {
                $trackingCode = sanitize_textarea_field($_POST['sc_matomo_tracking_code']);
                $this->matomo->setTrackingCode($trackingCode);
                $result = [
                    'success' => true,
                    'message' => 'Matomo tracking code updated successfully.',
                ];
            }

            if (isset($result)) {
                if ($result['success']) {
                    NoticeService::addSuccess($result['message'], true, 'sc-action-result');
                } else {
                    NoticeService::addError($result['message'], true, 'sc-action-result');
                }
            }
        }

        $this->renderPageContent($isRegistered, $hasRegistrationData);
    }

    /**
     * Render page content
     *
     * @param bool $isRegistered
     * @param bool $hasRegistrationData
     * @return void
     */
    private function renderPageContent(bool $isRegistered, bool $hasRegistrationData): void
    {
        ?>
        <div class="wrap">
            <?php $this->renderStatusToolbar(); ?>
            <br>
            <h1><b>Site Connector</b></h1>

            <?php if (!$isRegistered): ?>
                <?php if (!$hasRegistrationData): ?>
                    <form method="post">
                        <input type="hidden" name="sc_connect_confirm" value="1">
                        <p>This will register your site with the backend. This can only be done once.</p>
                        <?php submit_button('Register Site'); ?>
                    </form>
                <?php else: ?>
                    <?php $this->renderRegistrationError(); ?>
                <?php endif; ?>
            <?php else: ?>
                <?php $this->renderRegisteredContent(); ?>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Render status toolbar
     *
     * @return void
     */
    private function renderStatusToolbar(): void
    {
        require_once SC_PLUGIN_PATH . 'partials/StatusToolbar.php';
    }

    /**
     * Render registration error section
     *
     * @return void
     */
    private function renderRegistrationError(): void
    {
        ?>
        <h2>Site Registration Error</h2>
        <p>This site's connection to 121 Digital needs to be re-verified. Use the tool below to do this manually.</p>
        <div class="notice notice-error connect-121-notice">
            <br>
            <b>Last reported error:</b><br>
            <?php echo esc_html(get_option('sc_last_backend_error')); ?>
            <br><hr>
            <b>Suggested fix:</b><br>
            Await the WordPress CRON job to run again, or invoke validation manually using the 'Verify Connection &amp; Keys' tool.
            <br><br>
            <form method="POST">
                <input type="hidden" name="sc_verify_confirm" value="1">
                <?php wp_nonce_field('sc_disconnect_site_action', 'sc_disconnect_nonce'); ?>
                <input type="submit" class="button button-danger" value="Verify Connection">
            </form>
            <br>
        </div>
        <hr>
        <?php $this->renderCronStatus(); ?>
        <hr>
        <h2>Verify Connection &amp; Keys</h2>
        <form method="POST">
            <input type="hidden" name="sc_verify_confirm" value="1">
            <?php wp_nonce_field('sc_disconnect_site_action', 'sc_disconnect_nonce'); ?>
            <input type="submit" class="button button-danger" value="Verify Connection">
        </form>
        <form method="POST">
            <?php wp_nonce_field('sc_disconnect_site_action', 'sc_disconnect_nonce'); ?>
            <input type="submit" name="sc_disconnect_confirm" class="button button-danger" 
                  value="Disconnect Site" onclick="return confirm('Are you sure you want to disconnect this site?');">
        </form>
        <?php
    }

    /**
     * Render registered content section
     *
     * @return void
     */
    private function renderRegisteredContent(): void
    {
        ?>
        <p><strong>✅ This site is registered as site ID <?php echo esc_html(get_option('sc_site_id')); ?>.</strong></p>
        <small>Last backend request: <?php echo esc_html(get_option('sc_last_communication')); ?></small>

        <hr>
        <?php $this->renderCronStatus(); ?>

        <hr>
        <h2>Check for Updates</h2>
        <p>Use this tool to manually check with the backend for any available plugin updates or configuration changes.</p>
        <form method="POST">
            <?php wp_nonce_field('sc_check_updates_action', 'sc_check_updates_nonce'); ?>
            <input type="submit" name="sc_check_updates_confirm" class="button button-secondary" value="Check for Updates">
        </form>

        <hr>
        <h2>Verify Connection &amp; Keys</h2>
        <form method="POST">
            <input type="hidden" name="sc_verify_confirm" value="1">
            <?php wp_nonce_field('sc_disconnect_site_action', 'sc_disconnect_nonce'); ?>
            <input type="submit" class="button button-danger" value="Verify Connection">
        </form>

        <hr>
        <h2>Disconnect Site</h2>
        <form method="POST">
            <?php wp_nonce_field('sc_disconnect_site_action', 'sc_disconnect_nonce'); ?>
            <input type="submit" name="sc_disconnect_confirm" class="button button-danger" 
                  value="Disconnect Site" onclick="return confirm('Are you sure you want to disconnect this site?');">
        </form>

        <hr>
        <h2>Matomo Tracking Code</h2>
        <?php $this->renderMatomoTracking(); ?>
        <?php
    }

    /**
     * Render cron status
     *
     * @return void
     */
    private function renderCronStatus(): void
    {
        $lastRun = get_option('sc_last_cron_execution');
        if ($lastRun) {
            $lastRunTimestamp = strtotime($lastRun);
            $timeDiff = time() - $lastRunTimestamp;

            if ($timeDiff < 600) {
                echo '<p><strong><span class="dashicons dashicons-yes" style="color:green;"></span> The cron was last run ' . esc_html($lastRun) . '</strong></p>';
            } else {
                echo '<p><strong><span style="color:orange;">⚠️</span> Warning: Cron has not run recently. Last run: ' . esc_html($lastRun) . '</strong></p>';
            }
        } else {
            echo '<p><strong><span style="color:red;">❌</span> The cron has not run yet. <i>It might be a good idea to check the cron config.</i></strong></p>';
        }
    }

    /**
     * Render Matomo tracking section
     *
     * @return void
     */
    private function renderMatomoTracking(): void
    {
        if ($this->matomo->hasTrackingCode()) {
            if ($this->matomo->canRenderTrackingCode()) {
                echo '<p><strong>Matomo tracking code is set and valid.</strong></p>';
            } else {
                if (!$this->matomo->trackingCodeEmpty()) {
                    echo '<div class="notice notice-error connect-121-notice">';
                    echo '<p><b>Security Notice:</b> The defined matomo tracking code is potentially unsafe and has been disabled.</p>';
                    echo '</div>';
                }
            }
        }
        ?>
        <form method="POST">
            <textarea disabled name="sc_matomo_tracking_code" rows="15" cols="100"><?php echo esc_html($this->matomo->getTrackingCode()); ?></textarea>
            <br>
            <!-- <input type="submit" name="sc_update_matomo_tracking_code" class="button" 
                  value="Update Tracking Code"> -->
        </form>
        <?php
    }
}
