<?php

/**
 * Link Helper
 *
 * Central utility for generating admin deep links to specific plugin sections.
 *
 * @package ProRank\SEO\Core\Helpers
 * @since   0.1.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Core\Helpers;

use ProRank\SEO\Core\MenuRegistry;

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


/**
 * Link Helper class
 */


class LinkHelper {
    
    /**
     * Map of target slugs to their parent pages
     * 
     * @var array
     */
    private static array $page_map = [
        // Dashboard tabs
        'dashboard' => 'prorank-seo',
        'overview' => 'prorank-seo',
        'modules' => 'prorank-seo',
        'notifications' => 'prorank-seo',
        
        // On-Page SEO tabs
        'titles-meta' => 'prorank-on-page-seo',
        'content-analysis' => 'prorank-on-page-seo',
        'schema-markup' => 'prorank-on-page-seo',
        'readability' => 'prorank-on-page-seo',
        'internal-linking' => 'prorank-internal-linking',
        'content-safeguard' => 'prorank-on-page-seo',
        'keyword-optimization' => 'prorank-on-page-seo',
        'image-optimization' => 'prorank-on-page-seo',
        
        // Technical SEO tabs
        'sitemaps' => 'prorank-technical-seo',
        'robots-indexing' => 'prorank-technical-seo',
        'redirects' => 'prorank-technical-seo',
        'url-cleanup' => 'prorank-technical-seo',
        'head-cleanup' => 'prorank-technical-seo',
        'html-sitemap' => 'prorank-technical-seo',
        'special-sitemaps' => 'prorank-technical-seo',
        'headless' => 'prorank-technical-seo',
        
        // Performance tabs
        'core-web-vitals' => 'prorank-performance',
        'lazy-loading' => 'prorank-performance',
        'critical-css' => 'prorank-performance',
        'cdn-optimization' => 'prorank-performance',
        'database-optimization' => 'prorank-performance',
        'minification' => 'prorank-performance',
        'browser-caching' => 'prorank-performance',
        
        // Site Audit tabs
        'seo-health' => 'prorank-site-audit',
        'broken-links' => 'prorank-site-audit',
        'duplicate-content' => 'prorank-site-audit',
        'crawl-errors' => 'prorank-site-audit',
        'security-scan' => 'prorank-site-audit',

        // Support tabs
        'account' => 'prorank-support',
        'documentation' => 'prorank-support',
        'changelog' => 'prorank-support',
        'system-info' => 'prorank-support',
        'advanced-settings' => 'prorank-support',
        
        // Tools under Site Audit
        'import-export' => 'prorank-site-audit',
        
        // Redirects under Technical SEO
        'redirect-manager' => 'prorank-technical-seo',
    ];
    
    /**
     * Generate admin link to a specific plugin section
     *
     * @param string      $target_slug Target module/page slug
     * @param string|null $sub_target  Optional sub-target (tab ID, accordion ID)
     * @return string|null Full admin URL or null if invalid target
     */
    public static function get_admin_link(string $target_slug, ?string $sub_target = null): ?string {
        // Sanitize inputs
        $target_slug = sanitize_key($target_slug);
        $sub_target = $sub_target ? sanitize_key($sub_target) : null;
        
        // Check if target exists in page map
        if (!isset(self::$page_map[$target_slug])) {
            // Try to use the target as the page directly
            $page_slug = 'prorank-' . $target_slug;
        } else {
            $page_slug = self::$page_map[$target_slug];
        }
        
        // Build base URL
        $url = admin_url('admin.php?page=' . $page_slug);
        
        if ('internal-linking' === $target_slug && 'prorank-internal-linking' === $page_slug) {
            if ($sub_target) {
                $url .= '#?tab=' . sanitize_key($sub_target);
            }

            return esc_url($url);
        }

        // Add sub-target as hash if provided
        if ($sub_target) {
            $url .= '#' . $sub_target;
        } elseif ($target_slug !== $page_slug) {
            // If we have a specific tab/section, add it as hash
            $url .= '#' . $target_slug;
        }
        
        return esc_url($url);
    }
    
    /**
     * Generate link to a specific setting within a module
     *
     * @param string $module_slug   Module slug
     * @param string $setting_key   Setting key/ID
     * @param string $section_type  Type of section (tab, accordion, field)
     * @return string|null Full admin URL or null if invalid
     */
    public static function get_setting_link(
        string $module_slug, 
        string $setting_key, 
        string $section_type = 'field'
    ): ?string {
        // Get the base module link
        $base_url = self::get_admin_link($module_slug);
        
        if (!$base_url) {
            return null;
        }
        
        // Add setting-specific hash based on type
        switch ($section_type) {
            case 'tab':
                $hash = 'tab-' . sanitize_key($setting_key);
                break;
            case 'accordion':
                $hash = 'accordion-' . sanitize_key($setting_key);
                break;
            case 'field':
            default:
                $hash = 'setting-' . sanitize_key($setting_key);
                break;
        }
        
        // If URL already has a hash, append with separator
        if (strpos($base_url, '#') !== false) {
            $base_url .= ':' . $hash;
        } else {
            $base_url .= '#' . $hash;
        }
        
        return $base_url;
    }
    
    /**
     * Generate link to dashboard with specific tab
     *
     * @param string $tab_slug Tab slug (overview, modules, notifications)
     * @return string Full admin URL
     */
    public static function get_dashboard_link(string $tab_slug = 'overview'): string {
        return self::get_admin_link('dashboard', $tab_slug) ?? admin_url('admin.php?page=prorank-seo');
    }
    
    /**
     * Generate link to a specific module page
     *
     * @param string      $module_group Module group slug (on-page-seo, technical-seo, etc.)
     * @param string|null $module_slug  Specific module slug
     * @return string|null Full admin URL or null if invalid
     */
    public static function get_module_link(string $module_group, ?string $module_slug = null): ?string {
        $page_slug = 'prorank-' . sanitize_key($module_group);
        $url = admin_url('admin.php?page=' . $page_slug);
        
        if ($module_slug) {
            $url .= '#' . sanitize_key($module_slug);
        }
        
        return esc_url($url);
    }
    
    /**
     * Parse a deep link to extract components
     *
     * @param string $url URL to parse
     * @return array Array with 'page', 'tab', and 'section' keys
     */
    public static function parse_deep_link(string $url): array {
        $parsed = wp_parse_url($url);
        $result = [
            'page' => null,
            'tab' => null,
            'section' => null,
        ];
        
        // Extract page from query string
        if (isset($parsed['query'])) {
            parse_str($parsed['query'], $query_vars);
            if (isset($query_vars['page'])) {
                $result['page'] = $query_vars['page'];
            }
        }
        
        // Extract tab and section from fragment
        if (isset($parsed['fragment'])) {
            $parts = explode(':', $parsed['fragment'], 2);
            $result['tab'] = $parts[0];
            
            if (isset($parts[1])) {
                $result['section'] = $parts[1];
            }
        }
        
        return $result;
    }
}
