<?php

declare(strict_types=1);


/**
 * Audit Settings Admin Page
 * 
 * Provides comprehensive audit configuration interface
 * 
 * @package ProRank\SEO\Admin\Pages
 * @since 1.0.0
 */

namespace ProRank\SEO\Admin\Pages;

use ProRank\SEO\Core\AuditSettings as CoreAuditSettings;

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




class AuditSettings {
    
    /**
     * Initialize the settings page
     */
    public function init() {
        add_action('admin_menu', [$this, 'add_settings_page']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_action('wp_ajax_prorank_save_audit_settings', [$this, 'ajax_save_settings']);
        add_action('wp_ajax_prorank_apply_preset', [$this, 'ajax_apply_preset']);
    }
    
    /**
     * Add settings page to admin menu
     */
    public function add_settings_page() {
        add_submenu_page(
            'prorank-seo',
            __('Audit Settings', 'prorank-seo'),
            __('Audit Settings', 'prorank-seo'),
            'manage_options',
            'prorank-audit-settings',
            [$this, 'render_settings_page']
        );
    }
    
    /**
     * Register settings
     */
    public function register_settings() {
        register_setting('prorank_audit_settings', 'prorank_audit_settings', [
            'sanitize_callback' => [$this, 'sanitize_settings']
        ]);
    }
    
    /**
     * Enqueue scripts and styles
     */
    public function enqueue_scripts($hook) {
        if ($hook !== 'prorank-seo_page_prorank-audit-settings') {
            return;
        }
        
        wp_enqueue_script(
            'prorank-audit-settings',
            PRORANK_SEO_URL . 'assets/js/audit-settings.js',
            ['jquery', 'wp-element', 'wp-components', 'wp-i18n'],
            PRORANK_SEO_VERSION,
            true
        );
        
        wp_localize_script('prorank-audit-settings', 'prorankAuditSettings', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('prorank_audit_settings'),
            'currentSettings' => CoreAuditSettings::get_settings(),
            'presets' => CoreAuditSettings::get_presets(),
            'strings' => [
                'saved' => __('Settings saved successfully!', 'prorank-seo'),
                'error' => __('Failed to save settings.', 'prorank-seo'),
                'presetApplied' => __('Preset applied successfully!', 'prorank-seo'),
            ]
        ]);
        
        wp_enqueue_style(
            'prorank-audit-settings',
            PRORANK_SEO_URL . 'assets/css/audit-settings.css',
            [],
            PRORANK_SEO_VERSION
        );
    }
    
    /**
     * Render settings page
     */
    public function render_settings_page() {
        $settings = CoreAuditSettings::get_settings();
        $presets = CoreAuditSettings::get_presets();
        ?>
        <div class="wrap prorank-audit-settings-wrap">
            <h1><?php esc_html_e('Site Audit Settings', 'prorank-seo'); ?></h1>
            
            <div class="prorank-settings-container">
                <form method="post" action="options.php" id="audit-settings-form">
                    <?php settings_fields('prorank_audit_settings'); ?>
                    
                    <!-- Preset Selector -->
                    <div class="card">
                        <h2><?php esc_html_e('Quick Presets', 'prorank-seo'); ?></h2>
                        <p class="description">
                            <?php esc_html_e('Apply a preset configuration optimized for different scenarios.', 'prorank-seo'); ?>
                        </p>
                        <div class="preset-buttons">
                            <?php foreach ($presets as $key => $preset): ?>
                                <button type="button" class="button button-secondary apply-preset" data-preset="<?php echo esc_attr($key); ?>">
                                    <strong><?php echo esc_html($preset['name']); ?></strong><br>
                                    <small><?php echo esc_html($preset['description']); ?></small>
                                </button>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    
                    <!-- Basic Checks -->
                    <div class="card">
                        <h2><?php esc_html_e('Basic Checks', 'prorank-seo'); ?></h2>
                        <table class="form-table">
                            <tr>
                                <th scope="row"><?php esc_html_e('SEO Checks', 'prorank-seo'); ?></th>
                                <td>
                                    <fieldset>
                                        <label>
                                            <input type="checkbox" name="prorank_audit_settings[check_broken_links]" 
                                                   value="1" <?php checked($settings['check_broken_links'], true); ?>>
                                            <?php esc_html_e('Check for broken links', 'prorank-seo'); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="prorank_audit_settings[check_meta_tags]" 
                                                   value="1" <?php checked($settings['check_meta_tags'], true); ?>>
                                            <?php esc_html_e('Check meta tags', 'prorank-seo'); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="prorank_audit_settings[check_schema]" 
                                                   value="1" <?php checked($settings['check_schema'], true); ?>>
                                            <?php esc_html_e('Check structured data', 'prorank-seo'); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="prorank_audit_settings[check_performance]" 
                                                   value="1" <?php checked($settings['check_performance'], true); ?>>
                                            <?php esc_html_e('Check performance', 'prorank-seo'); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="prorank_audit_settings[check_accessibility]" 
                                                   value="1" <?php checked($settings['check_accessibility'], true); ?>>
                                            <?php esc_html_e('Check accessibility', 'prorank-seo'); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="prorank_audit_settings[check_mobile]" 
                                                   value="1" <?php checked($settings['check_mobile'], true); ?>>
                                            <?php esc_html_e('Check mobile friendliness', 'prorank-seo'); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="prorank_audit_settings[check_security]" 
                                                   value="1" <?php checked($settings['check_security'], true); ?>>
                                            <?php esc_html_e('Check security', 'prorank-seo'); ?>
                                        </label>
                                    </fieldset>
                                </td>
                            </tr>
                        </table>
                    </div>
                    
                    <!-- Advanced Checks -->
                    <div class="card">
                        <h2><?php esc_html_e('Advanced Checks', 'prorank-seo'); ?></h2>
                        <table class="form-table">
                            <tr>
                                <th scope="row"><?php esc_html_e('Resource Checks', 'prorank-seo'); ?></th>
                                <td>
                                    <fieldset>
                                        <label>
                                            <input type="checkbox" name="prorank_audit_settings[check_images]" 
                                                   value="1" <?php checked($settings['check_images'], true); ?>>
                                            <?php esc_html_e('Check images (alt text, optimization)', 'prorank-seo'); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="prorank_audit_settings[check_css]" 
                                                   value="1" <?php checked($settings['check_css'], true); ?>>
                                            <?php esc_html_e('Check CSS files', 'prorank-seo'); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="prorank_audit_settings[check_javascript]" 
                                                   value="1" <?php checked($settings['check_javascript'], true); ?>>
                                            <?php esc_html_e('Check JavaScript files', 'prorank-seo'); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="prorank_audit_settings[check_external_links]" 
                                                   value="1" <?php checked($settings['check_external_links'], true); ?>>
                                            <?php esc_html_e('Check external links status', 'prorank-seo'); ?>
                                            <span class="description"><?php esc_html_e('(May increase audit time)', 'prorank-seo'); ?></span>
                                        </label>
                                    </fieldset>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Crawl Behavior', 'prorank-seo'); ?></th>
                                <td>
                                    <fieldset>
                                        <label>
                                            <input type="checkbox" name="prorank_audit_settings[follow_non_canonical]" 
                                                   value="1" <?php checked($settings['follow_non_canonical'], true); ?>>
                                            <?php esc_html_e('Follow links on non-canonical pages', 'prorank-seo'); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="prorank_audit_settings[follow_nofollow]" 
                                                   value="1" <?php checked($settings['follow_nofollow'], true); ?>>
                                            <?php esc_html_e('Follow nofollow links', 'prorank-seo'); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="prorank_audit_settings[execute_javascript]" 
                                                   value="1" <?php checked($settings['execute_javascript'], true); ?>>
                                            <?php esc_html_e('Execute JavaScript (render pages)', 'prorank-seo'); ?>
                                            <span class="description"><?php esc_html_e('(Significantly slower)', 'prorank-seo'); ?></span>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="prorank_audit_settings[remove_url_parameters]" 
                                                   value="1" <?php checked($settings['remove_url_parameters'], true); ?>>
                                            <?php esc_html_e('Remove URL parameters', 'prorank-seo'); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="prorank_audit_settings[ignore_robots_txt]" 
                                                   value="1" <?php checked($settings['ignore_robots_txt'], true); ?>>
                                            <?php esc_html_e('Ignore robots.txt', 'prorank-seo'); ?>
                                            <span class="description"><?php esc_html_e('(Not recommended)', 'prorank-seo'); ?></span>
                                        </label>
                                    </fieldset>
                                </td>
                            </tr>
                        </table>
                    </div>
                    
                    <!-- Crawl Speed -->
                    <div class="card">
                        <h2><?php esc_html_e('Crawl Speed', 'prorank-seo'); ?></h2>
                        <table class="form-table">
                            <tr>
                                <th scope="row">
                                    <label for="crawl_speed"><?php esc_html_e('URLs per minute', 'prorank-seo'); ?></label>
                                </th>
                                <td>
                                    <input type="range" id="crawl_speed" name="prorank_audit_settings[crawl_speed]" 
                                           value="<?php echo esc_attr($settings['crawl_speed']); ?>" 
                                           min="1" max="60" step="1">
                                    <span id="crawl_speed_value"><?php echo esc_html($settings['crawl_speed']); ?></span>
                                    <p class="description">
                                        <?php esc_html_e('Higher speeds may impact server performance. Start low and increase gradually.', 'prorank-seo'); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="concurrent_requests"><?php esc_html_e('Concurrent requests', 'prorank-seo'); ?></label>
                                </th>
                                <td>
                                    <input type="number" id="concurrent_requests" name="prorank_audit_settings[concurrent_requests]" 
                                           value="<?php echo esc_attr($settings['concurrent_requests']); ?>" 
                                           min="1" max="10" step="1" class="small-text">
                                    <p class="description">
                                        <?php esc_html_e('Number of simultaneous requests. Higher values speed up crawling but use more resources.', 'prorank-seo'); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="request_timeout"><?php esc_html_e('Request timeout', 'prorank-seo'); ?></label>
                                </th>
                                <td>
                                    <input type="number" id="request_timeout" name="prorank_audit_settings[request_timeout]" 
                                           value="<?php echo esc_attr($settings['request_timeout']); ?>" 
                                           min="1" max="30" step="1" class="small-text">
                                    <?php esc_html_e('seconds', 'prorank-seo'); ?>
                                    <p class="description">
                                        <?php esc_html_e('Maximum time to wait for a page response.', 'prorank-seo'); ?>
                                    </p>
                                </td>
                            </tr>
                        </table>
                    </div>
                    
                    <!-- Crawl Limits -->
                    <div class="card">
                        <h2><?php esc_html_e('Crawl Limits', 'prorank-seo'); ?></h2>
                        <table class="form-table">
                            <tr>
                                <th scope="row">
                                    <label for="max_pages"><?php esc_html_e('Maximum pages', 'prorank-seo'); ?></label>
                                </th>
                                <td>
                                    <input type="number" id="max_pages" name="prorank_audit_settings[max_pages]" 
                                           value="<?php echo esc_attr($settings['max_pages']); ?>" 
                                           min="10" max="10000" step="10" class="regular-text">
                                    <p class="description">
                                        <?php esc_html_e('Stop crawling after this many pages.', 'prorank-seo'); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="max_duration"><?php esc_html_e('Maximum duration', 'prorank-seo'); ?></label>
                                </th>
                                <td>
                                    <input type="number" id="max_duration" name="prorank_audit_settings[max_duration]" 
                                           value="<?php echo esc_attr($settings['max_duration']); ?>" 
                                           min="5" max="180" step="5" class="small-text">
                                    <?php esc_html_e('minutes', 'prorank-seo'); ?>
                                    <p class="description">
                                        <?php esc_html_e('Stop crawling after this duration.', 'prorank-seo'); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="max_depth"><?php esc_html_e('Maximum depth', 'prorank-seo'); ?></label>
                                </th>
                                <td>
                                    <input type="number" id="max_depth" name="prorank_audit_settings[max_depth]" 
                                           value="<?php echo esc_attr($settings['max_depth']); ?>" 
                                           min="1" max="20" step="1" class="small-text">
                                    <p class="description">
                                        <?php esc_html_e('Maximum clicks from homepage.', 'prorank-seo'); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="max_folder_depth"><?php esc_html_e('Maximum folder depth', 'prorank-seo'); ?></label>
                                </th>
                                <td>
                                    <input type="number" id="max_folder_depth" name="prorank_audit_settings[max_folder_depth]" 
                                           value="<?php echo esc_attr($settings['max_folder_depth']); ?>" 
                                           min="1" max="50" step="1" class="small-text">
                                    <p class="description">
                                        <?php esc_html_e('Maximum folder levels in URL path.', 'prorank-seo'); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="max_url_length"><?php esc_html_e('Maximum URL length', 'prorank-seo'); ?></label>
                                </th>
                                <td>
                                    <input type="number" id="max_url_length" name="prorank_audit_settings[max_url_length]" 
                                           value="<?php echo esc_attr($settings['max_url_length']); ?>" 
                                           min="100" max="4096" step="100" class="regular-text">
                                    <?php esc_html_e('characters', 'prorank-seo'); ?>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="max_query_params"><?php esc_html_e('Maximum query parameters', 'prorank-seo'); ?></label>
                                </th>
                                <td>
                                    <input type="number" id="max_query_params" name="prorank_audit_settings[max_query_params]" 
                                           value="<?php echo esc_attr($settings['max_query_params']); ?>" 
                                           min="0" max="20" step="1" class="small-text">
                                    <p class="description">
                                        <?php esc_html_e('Skip URLs with more than this many query parameters.', 'prorank-seo'); ?>
                                    </p>
                                </td>
                            </tr>
                        </table>
                    </div>
                    
                    <!-- URL Patterns -->
                    <div class="card">
                        <h2><?php esc_html_e('URL Patterns', 'prorank-seo'); ?></h2>
                        <table class="form-table">
                            <tr>
                                <th scope="row">
                                    <label for="include_patterns"><?php esc_html_e('Include patterns', 'prorank-seo'); ?></label>
                                </th>
                                <td>
                                    <textarea id="include_patterns" name="prorank_audit_settings[include_patterns]" 
                                              rows="5" class="large-text code"><?php echo esc_textarea($settings['include_patterns']); ?></textarea>
                                    <p class="description">
                                        <?php esc_html_e('Only crawl URLs matching these patterns (one per line). Use * for wildcards.', 'prorank-seo'); ?><br>
                                        <?php esc_html_e('Examples: /blog/*, /products/*, *.html', 'prorank-seo'); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="exclude_patterns"><?php esc_html_e('Exclude patterns', 'prorank-seo'); ?></label>
                                </th>
                                <td>
                                    <textarea id="exclude_patterns" name="prorank_audit_settings[exclude_patterns]" 
                                              rows="5" class="large-text code"><?php echo esc_textarea($settings['exclude_patterns']); ?></textarea>
                                    <p class="description">
                                        <?php esc_html_e('Skip URLs matching these patterns (one per line).', 'prorank-seo'); ?><br>
                                        <?php esc_html_e('Examples: /admin/*, /wp-admin/*, *.pdf, /tag/*', 'prorank-seo'); ?>
                                    </p>
                                </td>
                            </tr>
                        </table>
                    </div>
                    
                    <!-- Authentication (for protected sites) -->
                    <div class="card">
                        <h2><?php esc_html_e('Authentication', 'prorank-seo'); ?></h2>
                        <p class="description">
                            <?php esc_html_e('Configure authentication if your site is password protected.', 'prorank-seo'); ?>
                        </p>
                        <table class="form-table">
                            <tr>
                                <th scope="row">
                                    <label for="auth_type"><?php esc_html_e('Authentication type', 'prorank-seo'); ?></label>
                                </th>
                                <td>
                                    <select id="auth_type" name="prorank_audit_settings[auth_type]">
                                        <option value="none" <?php selected($settings['auth_type'], 'none'); ?>>
                                            <?php esc_html_e('None', 'prorank-seo'); ?>
                                        </option>
                                        <option value="basic" <?php selected($settings['auth_type'], 'basic'); ?>>
                                            <?php esc_html_e('Basic Authentication', 'prorank-seo'); ?>
                                        </option>
                                        <option value="bearer" <?php selected($settings['auth_type'], 'bearer'); ?>>
                                            <?php esc_html_e('Bearer Token', 'prorank-seo'); ?>
                                        </option>
                                    </select>
                                </td>
                            </tr>
                            <tr class="auth-credentials" <?php echo $settings['auth_type'] === 'none' ? 'style="display:none;"' : ''; ?>>
                                <th scope="row">
                                    <label for="auth_credentials"><?php esc_html_e('Credentials', 'prorank-seo'); ?></label>
                                </th>
                                <td>
                                    <input type="text" id="auth_credentials" name="prorank_audit_settings[auth_credentials]" 
                                           value="<?php echo esc_attr($settings['auth_credentials']); ?>" 
                                           class="regular-text">
                                    <p class="description">
                                        <span class="auth-basic" <?php echo $settings['auth_type'] !== 'basic' ? 'style="display:none;"' : ''; ?>>
                                            <?php esc_html_e('Format: username:password', 'prorank-seo'); ?>
                                        </span>
                                        <span class="auth-bearer" <?php echo $settings['auth_type'] !== 'bearer' ? 'style="display:none;"' : ''; ?>>
                                            <?php esc_html_e('Enter the bearer token', 'prorank-seo'); ?>
                                        </span>
                                    </p>
                                </td>
                            </tr>
                        </table>
                    </div>
                    
                    <?php submit_button(__('Save Settings', 'prorank-seo')); ?>
                </form>
            </div>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            // Update range display
            $('#crawl_speed').on('input', function() {
                $('#crawl_speed_value').text($(this).val());
            });
            
            // Toggle authentication fields
            $('#auth_type').on('change', function() {
                if ($(this).val() === 'none') {
                    $('.auth-credentials').hide();
                } else {
                    $('.auth-credentials').show();
                    $('.auth-basic, .auth-bearer').hide();
                    $('.auth-' + $(this).val()).show();
                }
            });
            
            // Apply preset
            $('.apply-preset').on('click', function() {
                var preset = $(this).data('preset');
                if (confirm('<?php echo esc_js( __( 'Apply this preset? Current settings will be overwritten.', 'prorank-seo' ) ); ?>')) {
                    $.post(prorankAuditSettings.ajaxUrl, {
                        action: 'prorank_apply_preset',
                        preset: preset,
                        nonce: prorankAuditSettings.nonce
                    }, function(response) {
                        if (response.success) {
                            alert(prorankAuditSettings.strings.presetApplied);
                            location.reload();
                        }
                    });
                }
            });
        });
        </script>
        <?php
    }
    
    /**
     * Sanitize settings
     */
    public function sanitize_settings($input) {
        return CoreAuditSettings::save_settings($input);
    }
    
    /**
     * AJAX save settings
     */
    public function ajax_save_settings() {
        check_ajax_referer('prorank_audit_settings', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die(-1);
        }
        
        $settings = $_POST['settings'] ?? [];
        $saved = CoreAuditSettings::save_settings($settings);
        
        wp_send_json_success([
            'message' => __('Settings saved successfully!', 'prorank-seo'),
            'settings' => $saved
        ]);
    }
    
    /**
     * AJAX apply preset
     */
    public function ajax_apply_preset() {
        check_ajax_referer('prorank_audit_settings', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die(-1);
        }
        
        $preset = sanitize_text_field($_POST['preset'] ?? '');
        $result = CoreAuditSettings::apply_preset($preset);
        
        if ($result) {
            wp_send_json_success([
                'message' => __('Preset applied successfully!', 'prorank-seo'),
                'settings' => $result
            ]);
        } else {
            wp_send_json_error([
                'message' => __('Invalid preset.', 'prorank-seo')
            ]);
        }
    }
}
