<?php

/**
 * Audit Fix Handler
 *
 * Handles fixes for issues found by external audit
 *
 * @package ProRank\SEO\Core
 * @since   1.0.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Core;

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


/**
 * AuditFixHandler class
 */


class AuditFixHandler {
    
    /**
     * Apply a fix for an audit issue
     *
     * @param string $fix_type Type of fix to apply
     * @param array  $fix_data Data for the fix
     * @return array Result of the fix attempt
     */
    public function apply_fix(string $fix_type, array $fix_data = []): array {
        switch ($fix_type) {
            case 'missing_meta_description':
                return $this->fix_missing_meta_description($fix_data);
                
            case 'missing_meta_title':
                return $this->fix_missing_meta_title($fix_data);
                
            case 'duplicate_meta':
                return $this->fix_duplicate_meta($fix_data);
                
            case 'missing_alt_text':
                return $this->fix_missing_alt_text($fix_data);
                
            case 'broken_link':
                return $this->fix_broken_link($fix_data);
                
            case 'missing_schema':
                return $this->fix_missing_schema($fix_data);
                
            case 'slow_page_speed':
                return $this->fix_slow_page_speed($fix_data);
                
            case 'missing_sitemap':
                return $this->fix_missing_sitemap($fix_data);
                
            case 'robots_issue':
                return $this->fix_robots_issue($fix_data);
                
            // New comprehensive fix types
            case 'fix_canonical':
                return $this->fix_canonical_issue($fix_data);
                
            case 'fix_robots':
                return $this->fix_robots_meta($fix_data);
                
            case 'add_og_tags':
                return $this->add_og_tags($fix_data);
                
            case 'fix_og_url':
                return $this->fix_og_url($fix_data);
                
            case 'add_twitter_card':
                return $this->add_twitter_card($fix_data);
                
            case 'fix_redirect_type':
                return $this->fix_redirect_type($fix_data);
                
            case 'add_canonical':
                return $this->add_canonical_tag($fix_data);
                
            case 'add_internal_links':
                return $this->suggest_internal_links($fix_data);
                
            case 'create_robots_txt':
                return $this->create_robots_txt($fix_data);
                
            // GSC error fix types
            case 'soft_404':
                return $this->fix_soft_404($fix_data);
                
            case 'robots_blocked':
                return $this->fix_robots_blocked($fix_data);
                
            case 'indexing_issue':
                return $this->fix_indexing_issue($fix_data);
                
            case 'mobile_usability':
                return $this->fix_mobile_usability($fix_data);
                
            case 'sitemap_error':
                return $this->fix_sitemap_error($fix_data);
                
            default:
                return [
                    'success' => false,
                    'message' => __('Unknown fix type', 'prorank-seo'),
                ];
        }
    }
    
    /**
     * Fix missing meta description
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_missing_meta_description(array $data): array {
        $post_id = $data['post_id'] ?? 0;
        
        if (!$post_id) {
            return [
                'success' => false,
                'message' => __('Invalid post ID', 'prorank-seo'),
            ];
        }
        
        $post = get_post($post_id);
        if (!$post) {
            return [
                'success' => false,
                'message' => __('Post not found', 'prorank-seo'),
            ];
        }
        
        // Generate meta description from excerpt or content
        $description = '';
        
        if (!empty($post->post_excerpt)) {
            $description = $post->post_excerpt;
        } else {
            $description = wp_trim_words($post->post_content, 30, '...');
        }
        
        // Clean up description
        $description = wp_strip_all_tags($description);
        $description = str_replace(["\r", "\n", "\t"], ' ', $description);
        $description = trim(preg_replace('/\s+/', ' ', $description));
        
        // Limit to 160 characters
        if (strlen($description) > 160) {
            $description = substr($description, 0, 157) . '...';
        }
        
        // Save meta description
        update_post_meta($post_id, '_prorank_meta_description', $description);
        
        return [
            'success' => true,
            'message' => __('Meta description generated successfully', 'prorank-seo'),
            'data' => ['description' => $description],
        ];
    }
    
    /**
     * Fix missing meta title
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_missing_meta_title(array $data): array {
        $post_id = $data['post_id'] ?? 0;
        
        if (!$post_id) {
            return [
                'success' => false,
                'message' => __('Invalid post ID', 'prorank-seo'),
            ];
        }
        
        $post = get_post($post_id);
        if (!$post) {
            return [
                'success' => false,
                'message' => __('Post not found', 'prorank-seo'),
            ];
        }
        
        // Generate title from post title and site name
        $title = $post->post_title;
        $site_name = get_bloginfo('name');
        
        // Format: "Post Title - Site Name"
        $meta_title = sprintf('%s - %s', $title, $site_name);
        
        // Limit to 60 characters
        if (strlen($meta_title) > 60) {
            $meta_title = substr($title, 0, 57) . '...';
        }
        
        // Save meta title
        update_post_meta($post_id, '_prorank_meta_title', $meta_title);
        
        return [
            'success' => true,
            'message' => __('Meta title generated successfully', 'prorank-seo'),
            'data' => ['title' => $meta_title],
        ];
    }
    
    /**
     * Fix duplicate meta tags
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_duplicate_meta(array $data): array {
        $post_ids = $data['post_ids'] ?? [];
        $fixed = 0;
        
        foreach ($post_ids as $post_id) {
            $post = get_post($post_id);
            if (!$post) continue;
            
            // Add unique identifier to make meta tags unique
            $current_title = get_post_meta($post_id, '_prorank_meta_title', true);
            $current_desc = get_post_meta($post_id, '_prorank_meta_description', true);
            
            // Add post ID or date to make unique
            if ($current_title) {
                $new_title = sprintf('%s (#%d)', $current_title, $post_id);
                if (strlen($new_title) > 60) {
                    $new_title = $current_title;
                }
                update_post_meta($post_id, '_prorank_meta_title', $new_title);
            }
            
            if ($current_desc) {
                $date = get_the_date('M Y', $post_id);
                $new_desc = sprintf('%s - %s', $current_desc, $date);
                if (strlen($new_desc) > 160) {
                    $new_desc = $current_desc;
                }
                update_post_meta($post_id, '_prorank_meta_description', $new_desc);
            }
            
            $fixed++;
        }
        
        return [
            'success' => true,
/* translators: %1$: value */
            'message' => sprintf(__('Fixed duplicate meta tags for %1$d posts', 'prorank-seo'), $fixed),
        ];
    }
    
    /**
     * Fix missing alt text
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_missing_alt_text(array $data): array {
        $attachment_id = $data['attachment_id'] ?? 0;
        
        if (!$attachment_id) {
            return [
                'success' => false,
                'message' => __('Invalid attachment ID', 'prorank-seo'),
            ];
        }
        
        $attachment = get_post($attachment_id);
        if (!$attachment || $attachment->post_type !== 'attachment') {
            return [
                'success' => false,
                'message' => __('Attachment not found', 'prorank-seo'),
            ];
        }
        
        // Generate alt text from filename
        $filename = basename(get_attached_file($attachment_id));
        $alt_text = pathinfo($filename, PATHINFO_FILENAME);
        
        // Clean up filename to make readable alt text
        $alt_text = str_replace(['-', '_'], ' ', $alt_text);
        $alt_text = ucwords($alt_text);
        
        // Update alt text
        update_post_meta($attachment_id, '_wp_attachment_image_alt', $alt_text);
        
        return [
            'success' => true,
            'message' => __('Alt text generated successfully', 'prorank-seo'),
            'data' => ['alt_text' => $alt_text],
        ];
    }
    
    /**
     * Fix broken link
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_broken_link(array $data): array {
        // This would require more complex logic to find and replace links
        // For now, return a message that manual intervention is needed
        
        return [
            'success' => false,
            'message' => __('Broken links require manual fixing. Please update the link in the content editor.', 'prorank-seo'),
            'manual_fix_required' => true,
        ];
    }
    
    /**
     * Fix missing schema
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_missing_schema(array $data): array {
        $post_id = $data['post_id'] ?? 0;
        $schema_type = $data['schema_type'] ?? 'Article';
        
        if (!$post_id) {
            return [
                'success' => false,
                'message' => __('Invalid post ID', 'prorank-seo'),
            ];
        }
        
        // Enable schema for this post
        update_post_meta($post_id, '_prorank_schema_enabled', '1');
        update_post_meta($post_id, '_prorank_schema_type', $schema_type);
        
        return [
            'success' => true,
/* translators: %1$: value */
            'message' => sprintf(__('%1$s schema enabled for this post', 'prorank-seo'), $schema_type),
        ];
    }
    
    /**
     * Fix slow page speed
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_slow_page_speed(array $data): array {
        // Enable performance optimizations
        $settings = get_option('prorank_settings', []);
        
        $settings['performance'] = array_merge($settings['performance'] ?? [], [
            'lazy_load_images' => true,
            'lazy_load_iframes' => true,
            'optimize_css_delivery' => true,
            'defer_javascript' => true,
            'minify_html' => true,
        ]);
        
        update_option('prorank_settings', $settings);
        
        // Clear any caches
        wp_cache_flush();
        
        return [
            'success' => true,
            'message' => __('Performance optimizations enabled. Please test your site speed again.', 'prorank-seo'),
        ];
    }
    
    /**
     * Fix missing sitemap
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_missing_sitemap(array $data): array {
        // Enable sitemap generation
        $settings = get_option('prorank_settings', []);
        
        $settings['sitemaps'] = array_merge($settings['sitemaps'] ?? [], [
            'enabled' => true,
            'include_posts' => true,
            'include_pages' => true,
            'include_categories' => true,
            'include_tags' => true,
        ]);
        
        update_option('prorank_settings', $settings);
        
        // Flush rewrite rules to ensure sitemap URLs work
        flush_rewrite_rules();
        
        return [
            'success' => true,
            'message' => __('XML sitemap enabled. Visit /sitemap_index.xml to view it.', 'prorank-seo'),
            'data' => ['sitemap_url' => home_url('/sitemap_index.xml')],
        ];
    }
    
    /**
     * Fix robots.txt issue
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_robots_issue(array $data): array {
        $issue_type = $data['issue_type'] ?? '';
        
        // Update robots.txt settings
        $settings = get_option('prorank_settings', []);
        
        $settings['robots_txt'] = array_merge($settings['robots_txt'] ?? [], [
            'enabled' => true,
            'sitemap_reference' => true,
            'crawl_delay' => 0,
        ]);
        
        update_option('prorank_settings', $settings);
        
        return [
            'success' => true,
            'message' => __('Robots.txt settings updated successfully', 'prorank-seo'),
        ];
    }
    
    /**
     * Fix canonical issue
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_canonical_issue(array $data): array {
        $post_id = $data['post_id'] ?? 0;
        
        if (!$post_id) {
            return [
                'success' => false,
                'message' => __('Invalid post ID', 'prorank-seo'),
            ];
        }
        
        $post = get_post($post_id);
        if (!$post) {
            return [
                'success' => false,
                'message' => __('Post not found', 'prorank-seo'),
            ];
        }
        
        // Set canonical URL to self-referential
        $canonical_url = get_permalink($post_id);
        update_post_meta($post_id, '_prorank_canonical_url', $canonical_url);
        
        return [
            'success' => true,
            'message' => __('Canonical URL fixed', 'prorank-seo'),
            'data' => ['canonical_url' => $canonical_url],
        ];
    }
    
    /**
     * Fix robots meta tag
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_robots_meta(array $data): array {
        $post_id = $data['post_id'] ?? 0;
        
        if (!$post_id) {
            return [
                'success' => false,
                'message' => __('Invalid post ID', 'prorank-seo'),
            ];
        }
        
        // Set to index,follow by default
        update_post_meta($post_id, '_prorank_robots', 'index,follow');
        
        return [
            'success' => true,
            'message' => __('Robots meta tag updated to index,follow', 'prorank-seo'),
        ];
    }
    
    /**
     * Add Open Graph tags
     *
     * @param array $data Fix data
     * @return array
     */
    private function add_og_tags(array $data): array {
        $post_id = $data['post_id'] ?? 0;
        
        if (!$post_id) {
            return [
                'success' => false,
                'message' => __('Invalid post ID', 'prorank-seo'),
            ];
        }
        
        $post = get_post($post_id);
        if (!$post) {
            return [
                'success' => false,
                'message' => __('Post not found', 'prorank-seo'),
            ];
        }
        
        // Generate Open Graph data
        $og_title = $post->post_title;
        $og_description = get_post_meta($post_id, '_prorank_meta_description', true);
        
        if (empty($og_description)) {
            $og_description = wp_trim_words($post->post_content, 30, '...');
            $og_description = wp_strip_all_tags($og_description);
        }
        
        $og_url = get_permalink($post_id);
        $og_type = ($post->post_type === 'page') ? 'website' : 'article';
        
        // Get featured image if available
        $og_image = '';
        if (has_post_thumbnail($post_id)) {
            $image_src = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), 'large');
            if ($image_src) {
                $og_image = $image_src[0];
            }
        }
        
        // Save Open Graph data
        update_post_meta($post_id, '_prorank_og_title', $og_title);
        update_post_meta($post_id, '_prorank_og_description', $og_description);
        update_post_meta($post_id, '_prorank_og_url', $og_url);
        update_post_meta($post_id, '_prorank_og_type', $og_type);
        update_post_meta($post_id, '_prorank_og_image', $og_image);
        
        return [
            'success' => true,
            'message' => __('Open Graph tags added successfully', 'prorank-seo'),
            'data' => [
                'og_title' => $og_title,
                'og_description' => $og_description,
                'og_url' => $og_url,
                'og_type' => $og_type,
                'og_image' => $og_image,
            ],
        ];
    }
    
    /**
     * Fix Open Graph URL
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_og_url(array $data): array {
        $post_id = $data['post_id'] ?? 0;
        
        if (!$post_id) {
            return [
                'success' => false,
                'message' => __('Invalid post ID', 'prorank-seo'),
            ];
        }
        
        // Get canonical URL
        $canonical_url = get_post_meta($post_id, '_prorank_canonical_url', true);
        if (empty($canonical_url)) {
            $canonical_url = get_permalink($post_id);
        }
        
        // Update OG URL to match canonical
        update_post_meta($post_id, '_prorank_og_url', $canonical_url);
        
        return [
            'success' => true,
            'message' => __('Open Graph URL updated to match canonical URL', 'prorank-seo'),
            'data' => ['og_url' => $canonical_url],
        ];
    }
    
    /**
     * Add Twitter Card tags
     *
     * @param array $data Fix data
     * @return array
     */
    private function add_twitter_card(array $data): array {
        $post_id = $data['post_id'] ?? 0;
        
        if (!$post_id) {
            return [
                'success' => false,
                'message' => __('Invalid post ID', 'prorank-seo'),
            ];
        }
        
        $post = get_post($post_id);
        if (!$post) {
            return [
                'success' => false,
                'message' => __('Post not found', 'prorank-seo'),
            ];
        }
        
        // Get or generate Twitter Card data
        $twitter_title = get_post_meta($post_id, '_prorank_og_title', true);
        if (empty($twitter_title)) {
            $twitter_title = $post->post_title;
        }
        
        $twitter_description = get_post_meta($post_id, '_prorank_og_description', true);
        if (empty($twitter_description)) {
            $twitter_description = wp_trim_words($post->post_content, 30, '...');
            $twitter_description = wp_strip_all_tags($twitter_description);
        }
        
        $twitter_image = get_post_meta($post_id, '_prorank_og_image', true);
        
        // Determine card type
        $twitter_card = $twitter_image ? 'summary_large_image' : 'summary';
        
        // Save Twitter Card data
        update_post_meta($post_id, '_prorank_twitter_card', $twitter_card);
        update_post_meta($post_id, '_prorank_twitter_title', $twitter_title);
        update_post_meta($post_id, '_prorank_twitter_description', $twitter_description);
        update_post_meta($post_id, '_prorank_twitter_image', $twitter_image);
        
        return [
            'success' => true,
            'message' => __('Twitter Card tags added successfully', 'prorank-seo'),
            'data' => [
                'twitter_card' => $twitter_card,
                'twitter_title' => $twitter_title,
                'twitter_description' => $twitter_description,
                'twitter_image' => $twitter_image,
            ],
        ];
    }
    
    /**
     * Fix redirect type
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_redirect_type(array $data): array {
        $redirect_id = $data['redirect_id'] ?? 0;
        $source_url = $data['source_url'] ?? '';
        
        if (!$redirect_id && !$source_url) {
            return [
                'success' => false,
                'message' => __('Invalid redirect data', 'prorank-seo'),
            ];
        }
        
        // Update redirect type to 301
        $settings = get_option('prorank_redirects', []);
        
        foreach ($settings as &$redirect) {
            if (($redirect_id && $redirect['id'] == $redirect_id) || 
                ($source_url && $redirect['source'] == $source_url)) {
                $redirect['type'] = 301;
                update_option('prorank_redirects', $settings);
                
                return [
                    'success' => true,
                    'message' => __('Redirect changed to 301 permanent', 'prorank-seo'),
                ];
            }
        }
        
        return [
            'success' => false,
            'message' => __('Redirect not found', 'prorank-seo'),
        ];
    }
    
    /**
     * Add canonical tag
     *
     * @param array $data Fix data
     * @return array
     */
    private function add_canonical_tag(array $data): array {
        $post_id = $data['post_id'] ?? 0;
        $canonical_url = $data['canonical_url'] ?? '';
        
        if (!$post_id) {
            return [
                'success' => false,
                'message' => __('Invalid post ID', 'prorank-seo'),
            ];
        }
        
        // If no canonical URL provided, use self-referential
        if (empty($canonical_url)) {
            $canonical_url = get_permalink($post_id);
        }
        
        update_post_meta($post_id, '_prorank_canonical_url', $canonical_url);
        
        return [
            'success' => true,
            'message' => __('Canonical tag added successfully', 'prorank-seo'),
            'data' => ['canonical_url' => $canonical_url],
        ];
    }
    
    /**
     * Suggest internal links
     *
     * @param array $data Fix data
     * @return array
     */
    private function suggest_internal_links(array $data): array {
        $post_id = $data['post_id'] ?? 0;
        
        if (!$post_id) {
            return [
                'success' => false,
                'message' => __('Invalid post ID', 'prorank-seo'),
            ];
        }
        
        $post = get_post($post_id);
        if (!$post) {
            return [
                'success' => false,
                'message' => __('Post not found', 'prorank-seo'),
            ];
        }
        
        // Find related posts to link to this orphan page
        $args = [
            'post_type' => $post->post_type,
            'posts_per_page' => 5,
            'post__not_in' => [$post_id],
            'orderby' => 'relevance',
            's' => wp_trim_words($post->post_title, 3),
        ];
        
        $related_posts = get_posts($args);
        $suggestions = [];
        
        foreach ($related_posts as $related) {
            $suggestions[] = [
                'post_id' => $related->ID,
                'title' => $related->post_title,
                'url' => get_permalink($related->ID),
                'relevance' => 'high',
            ];
        }
        
        // Store suggestions for the internal linking module
        update_post_meta($post_id, '_prorank_internal_link_suggestions', $suggestions);
        
        return [
            'success' => true,
            'message' => sprintf(
/* translators: %1$: value */
                __('Found %1$d potential pages to link from', 'prorank-seo'),
                count($suggestions)
            ),
            'data' => ['suggestions' => $suggestions],
        ];
    }
    
    /**
     * Create robots.txt file
     *
     * @param array $data Fix data
     * @return array
     */
    private function create_robots_txt(array $data): array {
        $settings = get_option('prorank_settings', []);
        
        // Enable robots.txt generation
        $settings['robots_txt'] = array_merge($settings['robots_txt'] ?? [], [
            'enabled' => true,
            'content' => "User-agent: *\nAllow: /\n\nSitemap: " . home_url('/sitemap_index.xml'),
        ]);
        
        update_option('prorank_settings', $settings);
        
        // Flush rewrite rules to activate virtual robots.txt
        flush_rewrite_rules();
        
        return [
            'success' => true,
            'message' => __('Robots.txt created successfully', 'prorank-seo'),
            'data' => ['robots_url' => home_url('/robots.txt')],
        ];
    }
    
    /**
     * Fix soft 404 error
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_soft_404(array $data): array {
        $url = $data['url'] ?? '';
        $action = $data['action'] ?? '';
        
        if (empty($url)) {
            return [
                'success' => false,
                'message' => __('URL is required', 'prorank-seo'),
            ];
        }
        
        // Get post ID from URL
        $post_id = url_to_postid($url);
        
        if (!$post_id) {
            return [
                'success' => false,
                'message' => __('Could not find page for this URL', 'prorank-seo'),
            ];
        }
        
        switch ($action) {
            case 'generate_content':
                // Use AI to generate content for soft 404 page
                $post = get_post($post_id);
                if (!$post) {
                    return [
                        'success' => false,
                        'message' => __('Post not found', 'prorank-seo'),
                    ];
                }
                
                try {
                    if (!class_exists('\ProRank\SEO\AI\Manager')) {
                        return [
                            'success' => false,
                            'message' => __('AI content generation requires ProRank Premium with an AI provider configured.', 'prorank-seo'),
                        ];
                    }

                    $plugin = class_exists('\ProRank\SEO\Plugin') ? \ProRank\SEO\Plugin::get_instance() : null;
                    $ai_manager = ($plugin && method_exists($plugin, 'ai')) ? $plugin->ai() : null;
                    if (!$ai_manager || !method_exists($ai_manager, 'generate')) {
                        return [
                            'success' => false,
                            'message' => __('AI content generation requires ProRank Premium with a configured AI provider.', 'prorank-seo'),
                        ];
                    }
                    
                    // Generate content based on page title
                    $prompt = sprintf(
                        'Create engaging SEO-optimized content for a webpage titled "%s". The content should be informative, relevant, and at least 300 words. Include relevant keywords naturally.',
                        $post->post_title
                    );
                    
                    $generated_content = method_exists($ai_manager, 'generate')
                        ? $ai_manager->generate($prompt)
                        : null;
                    
                    if (is_wp_error($generated_content)) {
                        return [
                            'success' => false,
                            'message' => $generated_content->get_error_message(),
                        ];
                    }

                    if (is_string($generated_content) && trim($generated_content) !== '') {
                        // Update post content
                        wp_update_post([
                            'ID' => $post_id,
                            'post_content' => $generated_content,
                        ]);
                        
                        return [
                            'success' => true,
                            'message' => __('Content generated successfully', 'prorank-seo'),
                        ];
                    }
                } catch (\Throwable $e) {
                    return [
                        'success' => false,
/* translators: %1$: value */
                        'message' => sprintf(__('AI generation failed: %1$s', 'prorank-seo'), $e->getMessage()),
                    ];
                }
                
                return [
                    'success' => false,
                    'message' => __('Failed to generate content', 'prorank-seo'),
                ];
                
            case 'set_page_noindex':
                update_post_meta($post_id, '_prorank_robots_noindex', '1');
                return [
                    'success' => true,
                    'message' => __('Page set to noindex', 'prorank-seo'),
                ];
                
            case 'set_410_gone':
                // This would integrate with redirect module
                return [
                    'success' => false,
                    'message' => __('410 status not implemented yet', 'prorank-seo'),
                ];
                
            default:
                return [
                    'success' => false,
                    'message' => __('Unknown action', 'prorank-seo'),
                ];
        }
    }
    
    /**
     * Fix robots blocked error
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_robots_blocked(array $data): array {
        $url = $data['url'] ?? '';
        
        if (empty($url)) {
            return [
                'success' => false,
                'message' => __('URL is required', 'prorank-seo'),
            ];
        }
        
        // Get current robots.txt content
        $robots_content = get_option('prorank_robots_txt', '');
        
        // Extract path from URL
        $url_path = wp_parse_url($url, PHP_URL_PATH);
        
        // Remove disallow rules for this path
        $robots_content = preg_replace(
            '/Disallow:\s*' . preg_quote($url_path, '/') . '\s*$/m',
            '',
            $robots_content
        );
        
        // Save updated robots.txt
        update_option('prorank_robots_txt', trim($robots_content));
        
        return [
            'success' => true,
            'message' => __('Removed blocking rule from robots.txt', 'prorank-seo'),
        ];
    }
    
    /**
     * Fix indexing issue
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_indexing_issue(array $data): array {
        $url = $data['url'] ?? '';
        $action = $data['action'] ?? '';
        
        if (empty($url)) {
            return [
                'success' => false,
                'message' => __('URL is required', 'prorank-seo'),
            ];
        }
        
        switch ($action) {
            case 'request_url_indexing':
                // This would integrate with GSC API to request indexing
                return [
                    'success' => false,
                    'message' => __('GSC indexing API not implemented yet', 'prorank-seo'),
                ];
                
            case 'update_canonical':
                $post_id = url_to_postid($url);
                if ($post_id) {
                    $canonical = $data['canonical_url'] ?? '';
                    if (empty($canonical)) {
                        delete_post_meta($post_id, '_prorank_canonical_url');
                    } else {
                        update_post_meta($post_id, '_prorank_canonical_url', esc_url($canonical));
                    }
                    return [
                        'success' => true,
                        'message' => __('Canonical URL updated', 'prorank-seo'),
                    ];
                }
                break;
                
            case 'include_in_sitemap':
                $post_id = url_to_postid($url);
                if ($post_id) {
                    delete_post_meta($post_id, '_prorank_sitemap_exclude');
                    return [
                        'success' => true,
                        'message' => __('Page included in sitemap', 'prorank-seo'),
                    ];
                }
                break;
        }
        
        return [
            'success' => false,
            'message' => __('Failed to fix indexing issue', 'prorank-seo'),
        ];
    }
    
    /**
     * Fix mobile usability issue
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_mobile_usability(array $data): array {
        $issue = $data['issue'] ?? '';
        $action = $data['action'] ?? '';
        
        switch ($action) {
            case 'generate_page_critical_css':
                // Use Critical CSS Generator Module
                try {
                    $module_manager = new \ProRank\SEO\Core\ModuleManager();
                    $critical_css_module = $module_manager->get_module('critical-css-generator');
                    
                    if (!$critical_css_module) {
                        return [
                            'success' => false,
                            'message' => __('Critical CSS module not available', 'prorank-seo'),
                        ];
                    }
                    
                    // Generate critical CSS for the URL
                    $url = $data['url'] ?? '';
                    if (empty($url)) {
                        return [
                            'success' => false,
                            'message' => __('URL is required for critical CSS generation', 'prorank-seo'),
                        ];
                    }
                    
                    // Trigger generation via the module
                    $result = $critical_css_module->generate_for_url($url);
                    
                    if ($result && !is_wp_error($result)) {
                        return [
                            'success' => true,
                            'message' => __('Critical CSS generation started', 'prorank-seo'),
                        ];
                    }
                    
                    return [
                        'success' => false,
                        'message' => __('Failed to generate critical CSS', 'prorank-seo'),
                    ];
                } catch (\Exception $e) {
                    return [
                        'success' => false,
/* translators: %1$: value */
                        'message' => sprintf(__('Critical CSS generation failed: %1$s', 'prorank-seo'), $e->getMessage()),
                    ];
                }
                
            case 'add_dimension_attributes':
                // Use Image Optimization Module to add dimensions
                try {
                    $url = $data['url'] ?? '';
                    if (empty($url)) {
                        return [
                            'success' => false,
                            'message' => __('URL is required', 'prorank-seo'),
                        ];
                    }
                    
                    $post_id = url_to_postid($url);
                    if (!$post_id) {
                        return [
                            'success' => false,
                            'message' => __('Could not find page', 'prorank-seo'),
                        ];
                    }
                    
                    // Get all images in the post
                    $post = get_post($post_id);
                    if (!$post) {
                        return [
                            'success' => false,
                            'message' => __('Post not found', 'prorank-seo'),
                        ];
                    }
                    
                    // Find images without dimensions
                    $content = $post->post_content;
                    $updated_content = $content;
                    $images_fixed = 0;
                    
                    // Match img tags without width/height attributes
                    preg_match_all('/<img(?![^>]*(?:width|height))[^>]+>/i', $content, $matches);
                    
                    foreach ($matches[0] as $img_tag) {
                        // Extract src
                        if (preg_match('/src=["\']([^"\']+)["\']/', $img_tag, $src_match)) {
                            $image_url = $src_match[1];
                            
                            // Get attachment ID from URL
                            $attachment_id = attachment_url_to_postid($image_url);
                            if ($attachment_id) {
                                $image_meta = wp_get_attachment_metadata($attachment_id);
                                if ($image_meta && isset($image_meta['width']) && isset($image_meta['height'])) {
                                    // Add dimensions to img tag
                                    $new_img_tag = str_replace(
                                        '<img',
                                        sprintf('<img width="%d" height="%d"', $image_meta['width'], $image_meta['height']),
                                        $img_tag
                                    );
                                    $updated_content = str_replace($img_tag, $new_img_tag, $updated_content);
                                    $images_fixed++;
                                }
                            }
                        }
                    }
                    
                    if ($images_fixed > 0) {
                        // Update post content
                        wp_update_post([
                            'ID' => $post_id,
                            'post_content' => $updated_content,
                        ]);
                        
                        return [
                            'success' => true,
/* translators: %1$: value */
                            'message' => sprintf(__('Added dimensions to %1$d images', 'prorank-seo'), $images_fixed),
                        ];
                    }
                    
                    return [
                        'success' => true,
                        'message' => __('No images found without dimensions', 'prorank-seo'),
                    ];
                } catch (\Exception $e) {
                    return [
                        'success' => false,
/* translators: %1$: value */
                        'message' => sprintf(__('Failed to fix image dimensions: %1$s', 'prorank-seo'), $e->getMessage()),
                    ];
                }
                
            case 'defer_non_critical_js':
                // Enable JavaScript deferral for the page
                try {
                    $url = $data['url'] ?? '';
                    if (empty($url)) {
                        return [
                            'success' => false,
                            'message' => __('URL is required', 'prorank-seo'),
                        ];
                    }
                    
                    $post_id = url_to_postid($url);
                    if ($post_id) {
                        // Enable JS deferral for this specific page
                        update_post_meta($post_id, '_prorank_defer_js', '1');
                        
                        // Also ensure global JS optimization is enabled
                        $settings = get_option('prorank_performance_settings', []);
                        if (empty($settings['js_optimization']['defer_js'])) {
                            $settings['js_optimization']['defer_js'] = true;
                            update_option('prorank_performance_settings', $settings);
                        }
                        
                        return [
                            'success' => true,
                            'message' => __('JavaScript deferral enabled for this page', 'prorank-seo'),
                        ];
                    }
                    
                    return [
                        'success' => false,
                        'message' => __('Could not find page to update', 'prorank-seo'),
                    ];
                } catch (\Exception $e) {
                    return [
                        'success' => false,
/* translators: %1$: value */
                        'message' => sprintf(__('Failed to enable JS deferral: %1$s', 'prorank-seo'), $e->getMessage()),
                    ];
                }
                
            case 'add_viewport_meta':
                // Add viewport meta tag
                add_action('wp_head', function() {
                    echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
                });
                return [
                    'success' => true,
                    'message' => __('Viewport meta tag added', 'prorank-seo'),
                ];
                
            default:
                return [
                    'success' => false,
                    'message' => __('Unknown mobile fix action', 'prorank-seo'),
                ];
        }
    }
    
    /**
     * Fix sitemap error
     *
     * @param array $data Fix data
     * @return array
     */
    private function fix_sitemap_error(array $data): array {
        $action = $data['action'] ?? '';
        
        switch ($action) {
            case 'regenerate_xml_sitemap':
                // Trigger sitemap regeneration
                do_action('prorank_regenerate_sitemaps');
                return [
                    'success' => true,
                    'message' => __('Sitemap regenerated successfully', 'prorank-seo'),
                ];
                
            case 'validate_sitemap_urls':
                // This would validate all URLs in sitemap
                return [
                    'success' => false,
                    'message' => __('Sitemap validation not implemented yet', 'prorank-seo'),
                ];
                
            case 'submit_sitemap_to_gsc':
                // This would submit sitemap to GSC
                return [
                    'success' => false,
                    'message' => __('GSC sitemap submission not implemented yet', 'prorank-seo'),
                ];
                
            default:
                return [
                    'success' => false,
                    'message' => __('Unknown sitemap fix action', 'prorank-seo'),
                ];
        }
    }
}
