<?php

declare(strict_types=1);


/**
 * Audit Settings Manager
 * 
 * Manages all audit configuration settings
 * 
 * @package ProRank\SEO\Core
 * @since 1.0.0
 */

namespace ProRank\SEO\Core;

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




class AuditSettings {
    
    /**
     * Get all audit settings with defaults
     */
    public static function get_settings() {
        $defaults = self::get_defaults();
        $saved = get_option('prorank_audit_settings', []);
        
        return wp_parse_args($saved, $defaults);
    }
    
    /**
     * Save audit settings
     */
    public static function save_settings($settings) {
        $defaults = self::get_defaults();
        
        // Validate and sanitize
        $clean_settings = [];
        
        // Basic checks
        foreach (['check_broken_links', 'check_meta_tags', 'check_schema', 'check_performance', 
                  'check_accessibility', 'check_mobile', 'check_security', 'check_ai_content_leaks'] as $key) {
            $clean_settings[$key] = isset($settings[$key]) ? (bool) $settings[$key] : $defaults[$key];
        }
        
        // Advanced checks
        foreach (['check_images', 'check_css', 'check_javascript', 'check_external_links',
                  'follow_non_canonical', 'follow_nofollow', 'execute_javascript',
                  'remove_url_parameters', 'ignore_robots_txt'] as $key) {
            $clean_settings[$key] = isset($settings[$key]) ? (bool) $settings[$key] : $defaults[$key];
        }
        
        // Numeric settings
        $clean_settings['max_pages'] = isset($settings['max_pages']) ? 
            max(1, min(10000, intval($settings['max_pages']))) : $defaults['max_pages'];
            
        $clean_settings['max_depth'] = isset($settings['max_depth']) ? 
            max(1, min(20, intval($settings['max_depth']))) : $defaults['max_depth'];
            
        $clean_settings['max_folder_depth'] = isset($settings['max_folder_depth']) ? 
            max(1, min(50, intval($settings['max_folder_depth']))) : $defaults['max_folder_depth'];
            
        $clean_settings['max_url_length'] = isset($settings['max_url_length']) ? 
            max(100, min(4096, intval($settings['max_url_length']))) : $defaults['max_url_length'];
            
        $clean_settings['max_query_params'] = isset($settings['max_query_params']) ? 
            max(0, min(20, intval($settings['max_query_params']))) : $defaults['max_query_params'];
            
        $clean_settings['max_duration'] = isset($settings['max_duration']) ? 
            max(5, min(180, intval($settings['max_duration']))) : $defaults['max_duration'];
            
        $clean_settings['crawl_speed'] = isset($settings['crawl_speed']) ? 
            max(1, min(60, intval($settings['crawl_speed']))) : $defaults['crawl_speed'];
            
        $clean_settings['concurrent_requests'] = isset($settings['concurrent_requests']) ? 
            max(1, min(10, intval($settings['concurrent_requests']))) : $defaults['concurrent_requests'];
            
        $clean_settings['request_timeout'] = isset($settings['request_timeout']) ? 
            max(1, min(30, intval($settings['request_timeout']))) : $defaults['request_timeout'];
        
        // Text settings
        $clean_settings['include_patterns'] = isset($settings['include_patterns']) ? 
            sanitize_textarea_field($settings['include_patterns']) : '';
            
        $clean_settings['exclude_patterns'] = isset($settings['exclude_patterns']) ? 
            sanitize_textarea_field($settings['exclude_patterns']) : '';
        
        // Audit type
        $clean_settings['audit_type'] = isset($settings['audit_type']) && 
            in_array($settings['audit_type'], ['comprehensive', 'quick', 'custom']) ? 
            $settings['audit_type'] : 'comprehensive';
        
        // Custom headers for crawler
        $clean_settings['custom_headers'] = isset($settings['custom_headers']) && is_array($settings['custom_headers']) ? 
            $settings['custom_headers'] : [];
        
        // Authentication for protected sites
        $clean_settings['auth_type'] = isset($settings['auth_type']) && 
            in_array($settings['auth_type'], ['none', 'basic', 'bearer']) ? 
            $settings['auth_type'] : 'none';
            
        $clean_settings['auth_credentials'] = isset($settings['auth_credentials']) ? 
            sanitize_text_field($settings['auth_credentials']) : '';
        
        update_option('prorank_audit_settings', $clean_settings);
        
        return $clean_settings;
    }
    
    /**
     * Get default settings
     */
    public static function get_defaults() {
        return [
            // Basic checks (always sent to server)
            'check_broken_links' => true,
            'check_meta_tags' => true,
            'check_schema' => true,
            'check_performance' => true,
            'check_accessibility' => true,
            'check_mobile' => true,
            'check_security' => true,
            'check_ai_content_leaks' => true,
            
            // Advanced checks
            'check_images' => true,
            'check_css' => true,
            'check_javascript' => true,
            'check_external_links' => false,
            'follow_non_canonical' => false,
            'follow_nofollow' => false,
            'execute_javascript' => false,
            'remove_url_parameters' => true,
            
            // Crawl settings
            'crawl_speed' => 30, // URLs per minute
            'concurrent_requests' => 5,
            'request_timeout' => 10, // seconds
            
            // Limits
            'max_pages' => 500,
            'max_depth' => 5,
            'max_folder_depth' => 10,
            'max_url_length' => 2048,
            'max_query_params' => 5,
            'max_duration' => 30, // minutes
            
            // Robots
            'ignore_robots_txt' => false,
            
            // URL patterns
            'include_patterns' => '',
            'exclude_patterns' => '/wp-admin/*' . PHP_EOL . '/admin/*' . PHP_EOL . '*.pdf',
            
            // Audit type
            'audit_type' => 'comprehensive',
            
            // Authentication
            'auth_type' => 'none',
            'auth_credentials' => '',
            
            // Custom headers
            'custom_headers' => [],
        ];
    }
    
    /**
     * Get preset configurations
     */
    public static function get_presets() {
        return [
            'fast' => [
                'name' => __('Fast', 'prorank-seo'),
                'description' => __('Quick scan for faster health checks', 'prorank-seo'),
                'settings' => [
                    'audit_type' => 'quick',
                    'crawl_speed' => 60,
                    'concurrent_requests' => 8,
                    'request_timeout' => 5,
                    'max_pages' => 50,
                    'max_duration' => 10,
                    'max_depth' => 3,
                    'check_external_links' => false,
                    'execute_javascript' => false,
                    'check_images' => false,
                    'check_css' => false,
                    'check_javascript' => false,
                ]
            ],
            'balanced' => [
                'name' => __('Balanced', 'prorank-seo'),
                'description' => __('Recommended default for most sites', 'prorank-seo'),
                'settings' => [
                    'audit_type' => 'comprehensive',
                    'crawl_speed' => 30,
                    'concurrent_requests' => 5,
                    'request_timeout' => 10,
                    'max_pages' => 500,
                    'max_duration' => 30,
                    'max_depth' => 5,
                    'check_external_links' => false,
                    'execute_javascript' => false,
                    'check_images' => true,
                    'check_css' => true,
                    'check_javascript' => true,
                ]
            ],
            'deep' => [
                'name' => __('Deep Audit', 'prorank-seo'),
                'description' => __('Comprehensive scan with all checks', 'prorank-seo'),
                'settings' => [
                    'audit_type' => 'comprehensive',
                    'crawl_speed' => 20,
                    'max_pages' => 2000,
                    'max_duration' => 60,
                    'max_depth' => 10,
                    'check_external_links' => true,
                    'execute_javascript' => true,
                    'check_images' => true,
                    'check_css' => true,
                    'check_javascript' => true,
                ]
            ],
            'ecommerce' => [
                'name' => __('E-commerce', 'prorank-seo'),
                'description' => __('Optimized for online stores', 'prorank-seo'),
                'settings' => [
                    'audit_type' => 'custom',
                    'crawl_speed' => 20,
                    'max_pages' => 1000,
                    'max_duration' => 45,
                    'check_schema' => true, // Important for products
                    'check_images' => true, // Product images
                    'include_patterns' => '/product/*' . PHP_EOL . '/category/*' . PHP_EOL . '/shop/*',
                    'exclude_patterns' => '/cart/*' . PHP_EOL . '/checkout/*' . PHP_EOL . '/my-account/*',
                ]
            ],
            'blog' => [
                'name' => __('Blog/Content Site', 'prorank-seo'),
                'description' => __('Optimized for content-heavy sites', 'prorank-seo'),
                'settings' => [
                    'audit_type' => 'custom',
                    'crawl_speed' => 30,
                    'max_pages' => 1000,
                    'max_duration' => 30,
                    'check_meta_tags' => true,
                    'check_schema' => true, // Article schema
                    'include_patterns' => '/blog/*' . PHP_EOL . '/post/*' . PHP_EOL . '/article/*',
                    'exclude_patterns' => '/tag/*' . PHP_EOL . '/author/*' . PHP_EOL . '/page/*/comment-page-*',
                ]
            ],
        ];
    }
    
    /**
     * Apply a preset
     */
    public static function apply_preset($preset_key) {
        $presets = self::get_presets();
        
        if (!isset($presets[$preset_key])) {
            return false;
        }
        
        $current = self::get_settings();
        $preset_settings = $presets[$preset_key]['settings'];
        
        // Merge preset with current settings
        $new_settings = array_merge($current, $preset_settings);
        
        return self::save_settings($new_settings);
    }
    
    /**
     * Prepare settings for API request
     */
    public static function prepare_for_api($args = []) {
        $settings = self::get_settings();
        
        // Override with any passed arguments
        if (!empty($args)) {
            $settings = array_merge($settings, $args);
        }

        if (isset($settings['check_types']) && is_array($settings['check_types']) && array_key_exists('ai_content_leaks', $settings['check_types'])) {
            $settings['check_ai_content_leaks'] = (bool) $settings['check_types']['ai_content_leaks'];
        }
        
        // Format for API
        return [
            'audit_type' => $settings['audit_type'],
            'options' => [
                // Basic checks
                'check_broken_links' => $settings['check_broken_links'],
                'check_meta_tags' => $settings['check_meta_tags'],
                'check_schema' => $settings['check_schema'],
                'check_performance' => $settings['check_performance'],
                'check_accessibility' => $settings['check_accessibility'],
                'check_mobile' => $settings['check_mobile'],
                'check_security' => $settings['check_security'],
                'check_ai_content_leaks' => $settings['check_ai_content_leaks'],
                
                // Advanced checks
                'check_images' => $settings['check_images'],
                'check_css' => $settings['check_css'],
                'check_javascript' => $settings['check_javascript'],
                'check_external_links' => $settings['check_external_links'],
                'follow_non_canonical' => $settings['follow_non_canonical'],
                'follow_nofollow' => $settings['follow_nofollow'],
                'execute_javascript' => $settings['execute_javascript'],
                'remove_url_parameters' => $settings['remove_url_parameters'],
                
                // Limits
                'max_pages' => $settings['max_pages'],
                'max_depth' => $settings['max_depth'],
                'max_folder_depth' => $settings['max_folder_depth'],
                'max_url_length' => $settings['max_url_length'],
                'max_query_params' => $settings['max_query_params'],
                'max_duration' => $settings['max_duration'],
                
                // Crawl settings
                'crawl_speed' => $settings['crawl_speed'],
                'concurrent_requests' => $settings['concurrent_requests'],
                'request_timeout' => $settings['request_timeout'],
                
                // Robots
                'ignore_robots_txt' => $settings['ignore_robots_txt'],
                
                // URL patterns
                'include_patterns' => $settings['include_patterns'],
                'exclude_patterns' => $settings['exclude_patterns'],
                
                // Authentication
                'auth_type' => $settings['auth_type'],
                'auth_credentials' => $settings['auth_credentials'],
                
                // Custom headers
                'custom_headers' => $settings['custom_headers'],
            ]
        ];
    }
}
