<?php

namespace IntentDeep\VirtualFiles\Controllers;

use IntentDeep\VirtualFiles\Core\Option;
use IntentDeep\VirtualFiles\Core\Cache;
use IntentDeep\VirtualFiles\Core\Request;
use IntentDeep\VirtualFiles\Core\RewriteRulesTrait;
use IntentDeep\VirtualFiles\Traits\SettingHelper;
use IntentDeep\VirtualFiles\Traits\FileStatsHelper;
use IntentDeep\VirtualFiles\Traits\ContentSanitizationHelper;
use IntentDeep\VirtualFiles\Traits\ImportExportHelper;
use IntentDeep\VirtualFiles\Traits\PluginDataCleanup;
/**
 * Custom exception for duplicate files to handle them gracefully
 */
class DuplicateFileException extends \Exception {
    public function __construct( $message = "", $code = 0, Exception $previous = null ) {
        parent::__construct( $message, $code, $previous );
    }

}

class SettingsController {
    use SettingHelper;
    use RewriteRulesTrait;
    use FileStatsHelper;
    use ContentSanitizationHelper;
    use ImportExportHelper;
    use PluginDataCleanup;
    private const PLUGIN_PAGE = 'virtual-files';

    private const ERROR_PREFIX = 'Virtual Files';

    public function __construct() {
        // Hook for migration notice - premium only
        if ( function_exists( 'intentdeep_vf_fs' ) && intentdeep_vf_fs()->is__premium_only() ) {
            add_action( 'admin_notices', [$this, 'show_migration_notice__premium_only'] );
            // AJAX handler for migration
            add_action( 'wp_ajax_intentdeep_vf_migrate_posts', [$this, 'migrate_old_posts__premium_only'] );
            add_action( 'wp_ajax_intentdeep_vf_dismiss_migration', [$this, 'dismiss_migration_notice__premium_only'] );
        }
    }

    /**
     * Helper method to mask API keys for display
     */
    private function get_masked_api_key( ?string $key ) : string {
        if ( empty( $key ) ) {
            return '';
        }
        $length = strlen( $key );
        if ( $length <= 8 ) {
            return str_repeat( '•', 8 );
            // Too short to safely show parts
        }
        // Show first 4 and last 4 chars, mask the rest
        return substr( $key, 0, 4 ) . str_repeat( '•', 12 ) . substr( $key, -4 );
    }

    /**
     * Add admin page to WordPress menu
     */
    public function add_page() : void {
        // Add settings submenu under the existing Virtual Files CPT menu
        add_submenu_page(
            'edit.php?post_type=idep_virtual_file',
            __( 'Settings', 'intentdeep-virtual-files' ),
            __( 'Settings', 'intentdeep-virtual-files' ),
            'manage_options',
            'intentdeep_vf_settings',
            [$this, 'render_page']
        );
    }

    /**
     * Render the main settings page
     */
    public function render_page() : void {
        // Get plugin options
        $options = ( Option::all() ?: [] );
        // Prepare frontend data
        $frontend_data = $this->prepare_frontend_data();
        // Enqueue styles and scripts
        $css_ver = ( file_exists( dirname( __FILE__ ) . '/../assets/css/settings.css' ) ? filemtime( dirname( __FILE__ ) . '/../assets/css/settings.css' ) : '1.0.0' );
        $js_ver = ( file_exists( dirname( __FILE__ ) . '/../assets/js/settings.js' ) ? filemtime( dirname( __FILE__ ) . '/../assets/js/settings.js' ) : '1.0.0' );
        wp_enqueue_style(
            'intentdeep_vf_settings-styles',
            plugin_dir_url( dirname( __FILE__ ) ) . 'assets/css/settings.css',
            [],
            $css_ver
        );
        wp_enqueue_script(
            'intentdeep_vf_settings',
            plugin_dir_url( dirname( __FILE__ ) ) . 'assets/js/settings.js',
            ['jquery'],
            $js_ver,
            true
        );
        // Localize script with data
        wp_localize_script( 'intentdeep_vf_settings', 'intentdeepVfData', $frontend_data );
        // Render the settings page
        $this->render_settings_view( $options );
    }

    /**
     * Render the settings page view
     */
    private function render_settings_view( array $options ) : void {
        ?>
        <div class="wrap virtual-files-settings">
            <h1><?php 
        echo esc_html( get_admin_page_title() );
        ?></h1>

            <?php 
        settings_errors();
        ?>

            <div class="vf-settings-layout">
                <div class="vf-settings-main">
                    <form id="virtual-files-settings-form" method="post">
                        <?php 
        wp_nonce_field( 'intentdeep_vf_settings', 'vf-settings-nonce' );
        ?>

                <div class="vf-settings-section basic">
                    <h3><?php 
        esc_html_e( 'Basic Settings', 'intentdeep-virtual-files' );
        ?></h3>
                    <div class="inside">
                        <table class="form-table" role="presentation">
                            <tbody>
                                <tr>
                                    <th scope="row">
                                        <label for="vf-routing-enabled">
                                            <?php 
        esc_html_e( 'Enable Virtual Files', 'intentdeep-virtual-files' );
        ?>
                                        </label>
                                    </th>
                                    <td>
                                        <div style="display: flex; align-items: center; gap: 3px;">
                                            <input type="checkbox" id="vf-routing-enabled" name="routing_enabled" value="1" <?php 
        checked( $options['routing_enabled'] ?? true );
        ?>>
                                            <label for="vf-routing-enabled" class="description" style="margin: 0;">
                                                <?php 
        esc_html_e( 'Enable virtual files to work with clean URLs (e.g., example.com/robots.txt)', 'intentdeep-virtual-files' );
        ?>
                                            </label>
                                        </div>
                                        <input type="hidden" name="routing_enabled_unchecked" value="0">
                                        <div class="notice notice-warning inline" style="margin: 12px 0 0 0; padding: 10px 12px;">
                                            <p style="margin: 0;">
                                                <strong><?php 
        esc_html_e( '⚠️ Warning:', 'intentdeep-virtual-files' );
        ?></strong>
                                                <?php 
        esc_html_e( 'Disabling this option will immediately stop all virtual files from working. Your virtual file URLs will return 404 errors until you re-enable this setting.', 'intentdeep-virtual-files' );
        ?>
                                            </p>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="vf-settings-section ai-integration">
                    <h3><?php 
        esc_html_e( 'AI Settings', 'intentdeep-virtual-files' );
        ?></h3>
                    <div class="inside">
                        <table class="form-table" role="presentation">
                            <tbody>
                                <tr>
                                    <th scope="row">
                                        <label for="vf-ai-provider"><?php 
        esc_html_e( 'AI Provider', 'intentdeep-virtual-files' );
        ?></label>
                                    </th>
                                    <td>
                                        <select id="vf-ai-provider" name="ai_provider" class="regular-text">
                                            <option value="openrouter" <?php 
        selected( $options['ai_provider'] ?? 'openrouter', 'openrouter' );
        ?>>OpenRouter (Default)</option>
                                            <option value="openai" <?php 
        selected( $options['ai_provider'] ?? '', 'openai' );
        ?>>OpenAI</option>
                                            <option value="anthropic" <?php 
        selected( $options['ai_provider'] ?? '', 'anthropic' );
        ?>>Anthropic</option>
                                            <option value="google" <?php 
        selected( $options['ai_provider'] ?? '', 'google' );
        ?>>Google Gemini</option>
                                        </select>
                                    </td>
                                </tr>

                                <!-- OpenRouter Key -->
                                <tr class="vf-api-key-row" data-provider="openrouter">
                                    <th scope="row">
                                        <label for="vf-ai-api-key-openrouter"><?php 
        esc_html_e( 'OpenRouter API Key', 'intentdeep-virtual-files' );
        ?></label>
                                    </th>
                                    <td>
                                        <div class="vf-password-wrapper">
                                            <input type="text" id="vf-ai-api-key-openrouter" name="ai_api_key_openrouter" value="<?php 
        echo esc_attr( $this->get_masked_api_key( $options['ai_api_key_openrouter'] ?? $options['ai_api_key'] ?? '' ) );
        ?>" class="regular-text" placeholder="<?php 
        esc_attr_e( 'Leave blank to keep current key', 'intentdeep-virtual-files' );
        ?>">
                                        </div>
                                        <p class="description">
                                            <a href="https://openrouter.ai/keys" target="_blank"><?php 
        esc_html_e( 'Get OpenRouter Key', 'intentdeep-virtual-files' );
        ?></a>
                                        </p>
                                    </td>
                                </tr>

                                <!-- OpenAI Key -->
                                <tr class="vf-api-key-row" data-provider="openai" style="display:none;">
                                    <th scope="row">
                                        <label for="vf-ai-api-key-openai"><?php 
        esc_html_e( 'OpenAI API Key', 'intentdeep-virtual-files' );
        ?></label>
                                    </th>
                                    <td>
                                        <div class="vf-password-wrapper">
                                            <input type="text" id="vf-ai-api-key-openai" name="ai_api_key_openai" value="<?php 
        echo esc_attr( $this->get_masked_api_key( $options['ai_api_key_openai'] ?? '' ) );
        ?>" class="regular-text" placeholder="<?php 
        esc_attr_e( 'Leave blank to keep current key', 'intentdeep-virtual-files' );
        ?>">
                                        </div>
                                        <p class="description">
                                            <a href="https://platform.openai.com/api-keys" target="_blank"><?php 
        esc_html_e( 'Get OpenAI Key', 'intentdeep-virtual-files' );
        ?></a>
                                        </p>
                                    </td>
                                </tr>

                                <!-- Anthropic Key -->
                                <tr class="vf-api-key-row" data-provider="anthropic" style="display:none;">
                                    <th scope="row">
                                        <label for="vf-ai-api-key-anthropic"><?php 
        esc_html_e( 'Anthropic API Key', 'intentdeep-virtual-files' );
        ?></label>
                                    </th>
                                    <td>
                                        <div class="vf-password-wrapper">
                                            <input type="text" id="vf-ai-api-key-anthropic" name="ai_api_key_anthropic" value="<?php 
        echo esc_attr( $this->get_masked_api_key( $options['ai_api_key_anthropic'] ?? '' ) );
        ?>" class="regular-text" placeholder="<?php 
        esc_attr_e( 'Leave blank to keep current key', 'intentdeep-virtual-files' );
        ?>">
                                        </div>
                                        <p class="description">
                                            <a href="https://console.anthropic.com/settings/keys" target="_blank"><?php 
        esc_html_e( 'Get Anthropic Key', 'intentdeep-virtual-files' );
        ?></a>
                                        </p>
                                    </td>
                                </tr>

                                <!-- Google Key -->
                                <tr class="vf-api-key-row" data-provider="google" style="display:none;">
                                    <th scope="row">
                                        <label for="vf-ai-api-key-google"><?php 
        esc_html_e( 'Google Gemini API Key', 'intentdeep-virtual-files' );
        ?></label>
                                    </th>
                                    <td>
                                        <div class="vf-password-wrapper">
                                            <input type="text" id="vf-ai-api-key-google" name="ai_api_key_google" value="<?php 
        echo esc_attr( $this->get_masked_api_key( $options['ai_api_key_google'] ?? '' ) );
        ?>" class="regular-text" placeholder="<?php 
        esc_attr_e( 'Leave blank to keep current key', 'intentdeep-virtual-files' );
        ?>">
                                        </div>
                                        <p class="description">
                                            <a href="https://aistudio.google.com/app/apikey" target="_blank"><?php 
        esc_html_e( 'Get Gemini Key', 'intentdeep-virtual-files' );
        ?></a>
                                        </p>
                                    </td>
                                </tr>

                                <tr>
                                    <th scope="row">
                                        <label for="vf-ai-model"><?php 
        esc_html_e( 'AI Model', 'intentdeep-virtual-files' );
        ?></label>
                                    </th>
                                    <td>
                                        <select id="vf-ai-model" name="ai_model" class="regular-text" data-current="<?php 
        echo esc_attr( $options['ai_model'] ?? 'google/gemini-2.5-flash-lite' );
        ?>">
                                            <!-- Populated via JS -->
                                        </select>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="vf-settings-section files">
                    <h3><?php 
        esc_html_e( 'File Types', 'intentdeep-virtual-files' );
        ?></h3>
                    <div class="inside">
                        <table class="form-table" role="presentation">
                            <tbody>
                                <tr>
                                    <th scope="row">
                                        <label><?php 
        esc_html_e( 'Allowed Extensions', 'intentdeep-virtual-files' );
        ?></label>
                                    </th>
                                    <td>
                                        <div class="vf-file-extensions-container">
                                            <div class="vf-extensions-selector">
                                                <?php 
        // Define all available extensions
        $all_extensions = [
            'txt'    => [
                'name'  => 'Text Files',
                'desc'  => 'Plain text files',
                'color' => '#10b981',
            ],
            'md'     => [
                'name'  => 'Markdown',
                'desc'  => 'Markdown documents',
                'color' => '#8b5cf6',
            ],
            'json'   => [
                'name'  => 'JSON',
                'desc'  => 'JSON data files',
                'color' => '#f59e0b',
            ],
            'jsonld' => [
                'name'  => 'JSON-LD',
                'desc'  => 'JSON-LD structured data',
                'color' => '#14b8a6',
            ],
            'xml'    => [
                'name'  => 'XML',
                'desc'  => 'XML documents',
                'color' => '#ef4444',
            ],
            'csv'    => [
                'name'  => 'CSV',
                'desc'  => 'Comma-separated values',
                'color' => '#3b82f6',
            ],
            'yml'    => [
                'name'  => 'YAML',
                'desc'  => 'YAML configuration files (.yml, .yaml)',
                'color' => '#ec4899',
            ],
            'log'    => [
                'name'  => 'Log Files',
                'desc'  => 'Log files',
                'color' => '#6b7280',
            ],
            'rss'    => [
                'name'  => 'RSS Feed',
                'desc'  => 'RSS feed files',
                'color' => '#f97316',
            ],
        ];
        $free_extensions = ['txt', 'md', 'json'];
        $pro_extensions = [
            'jsonld',
            'xml',
            'csv',
            'yml',
            'log',
            'rss'
        ];
        // Check if user is Pro
        $is_pro_user = function_exists( 'intentdeep_vf_fs' ) && intentdeep_vf_fs()->can_use_premium_code__premium_only();
        // Render ALL extension chips (show all to both free and pro users)
        foreach ( $all_extensions as $ext => $info ) {
            $is_free_extension = in_array( $ext, $free_extensions );
            $is_pro_extension = in_array( $ext, $pro_extensions );
            // Determine if extension is enabled for current user
            $is_enabled = $is_pro_user || $is_free_extension;
            // Determine chip state
            $chip_class = ( $is_enabled ? 'allowed' : 'disabled' );
            ?>
                                                    <div class="vf-extension-chip <?php 
            echo esc_attr( $chip_class );
            ?>"
                                                         data-extension="<?php 
            echo esc_attr( $ext );
            ?>"
                                                         data-name="<?php 
            echo esc_attr( $info['name'] );
            ?>"
                                                         data-description="<?php 
            echo esc_attr( $info['desc'] );
            ?>"
                                                         style="--chip-color: <?php 
            echo esc_attr( $info['color'] );
            ?>;">
                                                        <span class="chip-ext"><?php 
            echo esc_html( $ext );
            ?></span>
                                                        <span class="chip-name"><?php 
            echo esc_html( $info['name'] );
            ?></span>
                                                        <div class="chip-checkbox">
                                                            <input type="checkbox"
                                                                   id="ext-<?php 
            echo esc_attr( $ext );
            ?>"
                                                                   name="allowed_extensions_display[]"
                                                                   value="<?php 
            echo esc_attr( $ext );
            ?>"
                                                                   <?php 
            checked( $is_enabled );
            ?>
                                                                   disabled>
                                                            <label for="ext-<?php 
            echo esc_attr( $ext );
            ?>"></label>
                                                        </div>
                                                    </div>
                                                    <?php 
        }
        ?>
                                            </div>

                                            <?php 
        if ( !$is_pro_user ) {
            ?>
                                            <div class="vf-pro-upgrade-banner">
                                                <div class="vf-banner-icon">🚀</div>
                                                <div class="vf-banner-content">
                                                    <h4 class="vf-banner-title">
                                                        <?php 
            esc_html_e( 'Unlock 6 More File Types with Pro', 'intentdeep-virtual-files' );
            ?>
                                                    </h4>
                                                    <p class="vf-banner-description">
                                                        <?php 
            esc_html_e( 'Get access to JSON-LD, XML, CSV, YAML, Log files, and RSS feeds. Plus unlimited files, advanced caching, analytics, and more.', 'intentdeep-virtual-files' );
            ?>
                                                    </p>
                                                </div>
                                                <a href="<?php 
            echo esc_url( admin_url( 'edit.php?post_type=idep_virtual_file&page=intentdeep_vf_settings-pricing' ) );
            ?>"
                                                   class="vf-banner-button button button-primary">
                                                    <?php 
            esc_html_e( 'Upgrade to Pro', 'intentdeep-virtual-files' );
            ?> →
                                                </a>
                                            </div>
                                            <?php 
        } else {
            ?>
                                            <div class="vf-extension-details">
                                                <div class="extension-details-content">
                                                    <div class="detail-icon">✓</div>
                                                    <div class="detail-text">
                                                        <strong style="color: #2271b1;"><?php 
            esc_html_e( 'All File Types Available', 'intentdeep-virtual-files' );
            ?></strong>
                                                        <p><?php 
            esc_html_e( 'Your Pro license includes access to all file types. Create virtual files with any of the supported extensions.', 'intentdeep-virtual-files' );
            ?></p>
                                                    </div>
                                                </div>
                                            </div>
                                            <?php 
        }
        ?>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <?php 
        if ( function_exists( 'intentdeep_vf_fs' ) && intentdeep_vf_fs()->can_use_premium_code__premium_only() ) {
            ?>
                <div class="vf-settings-section performance">
                    <h3><?php 
            esc_html_e( 'Performance & Caching', 'intentdeep-virtual-files' );
            ?></h3>
                    <div class="inside">
                        <table class="form-table" role="presentation">
                            <tbody>
                                <tr>
                                    <th scope="row">
                                        <label for="vf-cache-enabled">
                                            <?php 
            esc_html_e( 'Enable File Caching', 'intentdeep-virtual-files' );
            ?>
                                        </label>
                                    </th>
                                    <td>
                                        <input type="checkbox" id="vf-cache-enabled" name="cache_enabled" value="1" <?php 
            checked( $options['cache_enabled'] ?? false );
            ?>>
                                        <input type="hidden" name="cache_enabled_unchecked" value="0">
                                        <p class="description">
                                            <?php 
            esc_html_e( 'Cache virtual file content for better performance. Cached files are served much faster than uncached files.', 'intentdeep-virtual-files' );
            ?>
                                        </p>
                                    </td>
                                </tr>

                                <tr>
                                    <th scope="row">
                                        <label for="vf-cache-expiration">
                                            <?php 
            esc_html_e( 'Cache Expiration', 'intentdeep-virtual-files' );
            ?>
                                        </label>
                                    </th>
                                    <td>
                                        <select id="vf-cache-expiration" name="cache_expiration">
                                            <?php 
            $expiration_options = [
                300   => __( '5 minutes', 'intentdeep-virtual-files' ),
                900   => __( '15 minutes', 'intentdeep-virtual-files' ),
                1800  => __( '30 minutes', 'intentdeep-virtual-files' ),
                3600  => __( '1 hour', 'intentdeep-virtual-files' ),
                7200  => __( '2 hours', 'intentdeep-virtual-files' ),
                14400 => __( '4 hours', 'intentdeep-virtual-files' ),
                28800 => __( '8 hours', 'intentdeep-virtual-files' ),
                86400 => __( '24 hours', 'intentdeep-virtual-files' ),
            ];
            $current_expiration = intval( $options['cache_expiration'] ?? 3600 );
            foreach ( $expiration_options as $seconds => $label ) {
                echo '<option value="' . esc_attr( $seconds ) . '" ' . selected( $current_expiration, $seconds, false ) . '>' . esc_html( $label ) . '</option>';
            }
            ?>
                                        </select>
                                        <p class="description">
                                            <?php 
            esc_html_e( 'How long to keep cached files before refreshing. Shorter times ensure fresh content, longer times improve performance.', 'intentdeep-virtual-files' );
            ?>
                                        </p>
                                    </td>
                                </tr>

                                <tr>
                                    <th scope="row">
                                        <?php 
            esc_html_e( 'Cache Statistics', 'intentdeep-virtual-files' );
            ?>
                                    </th>
                                    <td>
                                        <div class="vf-cache-stats">
                                            <div class="vf-stats-wrapper">
                                                <div class="vf-stat-row">
                                                    <span class="vf-stat-label"><?php 
            esc_html_e( 'Cached Files:', 'intentdeep-virtual-files' );
            ?></span>
                                                    <span class="vf-stat-value" id="vf-cached-files">-</span>
                                                </div>
                                                <div class="vf-stat-row">
                                                    <span class="vf-stat-label"><?php 
            esc_html_e( 'Cache Size:', 'intentdeep-virtual-files' );
            ?></span>
                                                    <span class="vf-stat-value" id="vf-cache-size">-</span>
                                                </div>
                                            </div>
                                            <div class="vf-cache-actions">
                                                <button type="button" id="vf-warm-up-cache" class="button button-secondary">
                                                    <?php 
            esc_html_e( 'Warm Up Cache', 'intentdeep-virtual-files' );
            ?>
                                                </button>
                                                <button type="button" id="vf-clear-cache" class="button button-secondary">
                                                    <?php 
            esc_html_e( 'Clear All Cache', 'intentdeep-virtual-files' );
            ?>
                                                </button>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <?php 
        }
        ?>

                <?php 
        if ( !function_exists( 'intentdeep_vf_fs' ) || !intentdeep_vf_fs()->can_use_premium_code__premium_only() ) {
            ?>
                <div class="vf-pro-feature">
                    <div class="vf-pro-header">
                        <span class="vf-pro-icon">✨</span>
                        <h3><?php 
            esc_html_e( 'Unlock Pro Features', 'intentdeep-virtual-files' );
            ?></h3>
                    </div>
                    <div class="vf-pro-features-grid">
                        <div class="vf-pro-feature-item">
                            <span class="vf-feature-icon">🚀</span>
                            <div>
                                <strong><?php 
            esc_html_e( 'Unlimited Files', 'intentdeep-virtual-files' );
            ?></strong>
                                <span class="vf-feature-desc"><?php 
            esc_html_e( 'No file limits', 'intentdeep-virtual-files' );
            ?></span>
                            </div>
                        </div>
                        <div class="vf-pro-feature-item">
                            <span class="vf-feature-icon">📄</span>
                            <div>
                                <strong><?php 
            esc_html_e( 'Premium File Types', 'intentdeep-virtual-files' );
            ?></strong>
                                <span class="vf-feature-desc"><?php 
            esc_html_e( 'JSON-LD, XML, CSV, YAML, Log, RSS', 'intentdeep-virtual-files' );
            ?></span>
                            </div>
                        </div>
                        <div class="vf-pro-feature-item">
                            <span class="vf-feature-icon">💻</span>
                            <div>
                                <strong><?php 
            esc_html_e( 'Code Editor', 'intentdeep-virtual-files' );
            ?></strong>
                                <span class="vf-feature-desc"><?php 
            esc_html_e( 'Syntax highlighting', 'intentdeep-virtual-files' );
            ?></span>
                            </div>
                        </div>
                        <div class="vf-pro-feature-item">
                            <span class="vf-feature-icon">📊</span>
                            <div>
                                <strong><?php 
            esc_html_e( 'Analytics', 'intentdeep-virtual-files' );
            ?></strong>
                                <span class="vf-feature-desc"><?php 
            esc_html_e( 'Track file access', 'intentdeep-virtual-files' );
            ?></span>
                            </div>
                        </div>
                        <div class="vf-pro-feature-item">
                            <span class="vf-feature-icon">📦</span>
                            <div>
                                <strong><?php 
            esc_html_e( 'Import/Export', 'intentdeep-virtual-files' );
            ?></strong>
                                <span class="vf-feature-desc"><?php 
            esc_html_e( 'Backup & restore', 'intentdeep-virtual-files' );
            ?></span>
                            </div>
                        </div>
                        <div class="vf-pro-feature-item">
                            <span class="vf-feature-icon">⚡</span>
                            <div>
                                <strong><?php 
            esc_html_e( 'File Caching', 'intentdeep-virtual-files' );
            ?></strong>
                                <span class="vf-feature-desc"><?php 
            esc_html_e( 'Better performance', 'intentdeep-virtual-files' );
            ?></span>
                            </div>
                        </div>
                    </div>
                    <a href="<?php 
            echo esc_url( admin_url( 'edit.php?post_type=idep_virtual_file&page=intentdeep_vf_settings-pricing' ) );
            ?>" class="vf-upgrade-button">
                        <?php 
            esc_html_e( 'Upgrade to Pro', 'intentdeep-virtual-files' );
            ?> → →
                    </a>
                </div>
                <?php 
        }
        ?>

                <div class="vf-settings-section data-management">
                    <h3><?php 
        esc_html_e( 'Data Management', 'intentdeep-virtual-files' );
        ?></h3>
                    <div class="inside">
                        <table class="form-table" role="presentation">
                            <tbody>
                                <tr>
                                    <th scope="row">
                                        <label for="vf-remove-data-uninstall">
                                            <?php 
        esc_html_e( 'Data Retention', 'intentdeep-virtual-files' );
        ?>
                                        </label>
                                    </th>
                                    <td>
                                        <div style="display: flex; align-items: center; gap: 8px;">
                                            <input type="checkbox" id="vf-remove-data-uninstall" name="remove_data_on_uninstall" value="1" <?php 
        checked( $options['remove_data_on_uninstall'] ?? false );
        ?>>
                                            <label for="vf-remove-data-uninstall" style="margin: 0;">
                                                <?php 
        esc_html_e( 'Remove all plugin data when uninstalling', 'intentdeep-virtual-files' );
        ?>
                                            </label>
                                        </div>
                                        <p class="description" style="margin-top: 8px;">
                                            <?php 
        esc_html_e( 'If checked, all virtual files, settings, and cache will be permanently deleted when you uninstall this plugin. If unchecked, your data will be preserved.', 'intentdeep-virtual-files' );
        ?>
                                        </p>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row">
                                        <?php 
        esc_html_e( 'Reset Plugin Data', 'intentdeep-virtual-files' );
        ?>
                                    </th>
                                    <td>
                                        <button type="button" id="vf-reset-plugin-data" class="button" style="background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%); border-color: #b91c1c; color: white; font-weight: 600; box-shadow: 0 2px 6px rgba(220, 38, 38, 0.3);">
                                            <?php 
        esc_html_e( 'Reset Plugin Data', 'intentdeep-virtual-files' );
        ?>
                                        </button>
                                        <p class="description" style="margin-top: 8px; color: #dc2626; font-weight: 500;">
                                            <strong>⚠️</strong> <?php 
        esc_html_e( 'Delete all virtual files, settings, and plugin data. This action cannot be undone.', 'intentdeep-virtual-files' );
        ?>
                                        </p>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <p class="submit">
                    <button type="submit" class="button button-primary"><?php 
        esc_html_e( 'Save Settings', 'intentdeep-virtual-files' );
        ?></button>
                    <button type="button" id="vf-flush-rewrite" class="button"><?php 
        esc_html_e( 'Flush Rewrite Rules', 'intentdeep-virtual-files' );
        ?></button>
                </p>
            </form>
        </div>

        <div class="vf-settings-sidebar">
            <div class="vf-sidebar-section vf-stats-widget">
                <h3><?php 
        esc_html_e( 'Statistics', 'intentdeep-virtual-files' );
        ?></h3>
                <div class="vf-stats-cards">
                    <div class="vf-stat-card vf-stat-active">
                        <div class="vf-stat-icon">
                            <span class="dashicons dashicons-yes-alt"></span>
                        </div>
                        <div class="vf-stat-content">
                            <div class="vf-stat-number vf-stat-active-files"><?php 
        echo esc_html( $this->getActiveFileCount() );
        ?></div>
                            <div class="vf-stat-label"><?php 
        esc_html_e( 'Active Files', 'intentdeep-virtual-files' );
        ?></div>
                        </div>
                    </div>
                    <div class="vf-stat-card vf-stat-total">
                        <div class="vf-stat-icon">
                            <span class="dashicons dashicons-media-document"></span>
                        </div>
                        <div class="vf-stat-content">
                            <div class="vf-stat-number vf-stat-total-files"><?php 
        echo esc_html( $this->getTotalFileCount() );
        ?></div>
                            <div class="vf-stat-label"><?php 
        esc_html_e( 'Total Files', 'intentdeep-virtual-files' );
        ?></div>
                        </div>
                    </div>
                    <div class="vf-stat-card vf-stat-max">
                        <div class="vf-stat-icon">
                            <span class="dashicons dashicons-admin-network"></span>
                        </div>
                        <div class="vf-stat-content">
                            <div class="vf-stat-number vf-stat-max-files" data-unlimited="<?php 
        echo esc_attr( ( function_exists( 'intentdeep_vf_fs' ) && intentdeep_vf_fs()->can_use_premium_code__premium_only() ? 'true' : 'false' ) );
        ?>"><?php 
        echo esc_html( $this->getMaxFilesDisplay() );
        ?></div>
                            <div class="vf-stat-label"><?php 
        esc_html_e( 'Max Allowed', 'intentdeep-virtual-files' );
        ?></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="vf-sidebar-section vf-backup-restore-widget">
                <h3><?php 
        esc_html_e( 'Backup & Restore', 'intentdeep-virtual-files' );
        ?></h3>
                <?php 
        $is_pro = function_exists( 'intentdeep_vf_fs' ) && intentdeep_vf_fs()->can_use_premium_code__premium_only();
        if ( $is_pro ) {
            ?>
                    <div class="vf-backup-restore">
                        <div class="vf-backup-box">
                            <div class="vf-backup-header">
                                <span class="dashicons dashicons-download"></span>
                                <h4><?php 
            esc_html_e( 'Create Backup', 'intentdeep-virtual-files' );
            ?></h4>
                            </div>
                            <p><?php 
            esc_html_e( 'Download all your virtual files as a JSON backup file. Use this to migrate to another site or keep as a backup.', 'intentdeep-virtual-files' );
            ?></p>
                            <button type="button" id="vf-export-files" class="button button-secondary"><?php 
            esc_html_e( 'Download Backup', 'intentdeep-virtual-files' );
            ?></button>
                        </div>
                        <div class="vf-backup-box">
                            <div class="vf-backup-header">
                                <span class="dashicons dashicons-upload"></span>
                                <h4><?php 
            esc_html_e( 'Restore Backup', 'intentdeep-virtual-files' );
            ?></h4>
                            </div>
                            <p><?php 
            esc_html_e( 'Upload a backup file to restore virtual files from a previous export. Existing files with the same name will be skipped.', 'intentdeep-virtual-files' );
            ?></p>
                            <div class="vf-file-upload">
                                <input type="file" id="vf-import-files" name="import_file" accept=".json,.zip,.txt" class="hidden">
                                <button type="button" id="vf-import-files-button" class="button button-secondary"><?php 
            esc_html_e( 'Choose Backup File', 'intentdeep-virtual-files' );
            ?></button>
                                <span class="vf-file-selected" style="display: none; margin-left: 10px; color: #2271b1; font-weight: 500;"></span>
                            </div>
                        </div>
                    </div>
                <?php 
        } else {
            ?>
                    <div class="vf-backup-restore vf-backup-restore-free">
                        <div class="vf-pro-notice">
                            <span class="dashicons dashicons-lock"></span>
                            <p><?php 
            esc_html_e( 'Backup & Restore is a Pro feature. Upgrade to create and restore backups of your virtual files.', 'intentdeep-virtual-files' );
            ?></p>
                            <a href="<?php 
            echo esc_url( admin_url( 'edit.php?post_type=idep_virtual_file&page=intentdeep_vf_settings-pricing' ) );
            ?>" class="button button-primary button-small"><?php 
            esc_html_e( 'Upgrade to Pro', 'intentdeep-virtual-files' );
            ?></a>
                        </div>
                        <div class="vf-backup-box vf-backup-box-disabled">
                            <div class="vf-backup-header">
                                <span class="dashicons dashicons-download"></span>
                                <h4><?php 
            esc_html_e( 'Create Backup', 'intentdeep-virtual-files' );
            ?> <span class="vf-pro-badge">PRO</span></h4>
                            </div>
                            <p><?php 
            esc_html_e( 'Download all your virtual files as a JSON backup file.', 'intentdeep-virtual-files' );
            ?></p>
                            <button type="button" class="button button-secondary" disabled><?php 
            esc_html_e( 'Download Backup', 'intentdeep-virtual-files' );
            ?></button>
                        </div>
                        <div class="vf-backup-box vf-backup-box-disabled">
                            <div class="vf-backup-header">
                                <span class="dashicons dashicons-upload"></span>
                                <h4><?php 
            esc_html_e( 'Restore Backup', 'intentdeep-virtual-files' );
            ?> <span class="vf-pro-badge">PRO</span></h4>
                            </div>
                            <p><?php 
            esc_html_e( 'Upload a backup file to restore virtual files.', 'intentdeep-virtual-files' );
            ?></p>
                            <button type="button" class="button button-secondary" disabled><?php 
            esc_html_e( 'Choose Backup File', 'intentdeep-virtual-files' );
            ?></button>
                        </div>
                    </div>
                <?php 
        }
        ?>
            </div>
        </div>
    </div>
        </div>
        <?php 
    }

    /**
     * Save plugin options via AJAX
     */
    public function save_options() : void {
        // Check nonce
        if ( !check_ajax_referer( 'intentdeep_vf_settings', 'nonce', false ) ) {
            wp_send_json_error( "Invalid nonce", 419 );
        }
        if ( !current_user_can( 'manage_options' ) ) {
            wp_send_json_error( "Unauthorized user", 403 );
        }
        // Sanitize and save options
        try {
            // Get current settings for comparison
            $current_settings = $this->getSettings();
            // Extract only expected fields to avoid processing entire $_POST array
            $expected_fields = [
                'routing_enabled',
                'cache_enabled',
                'remove_data_on_uninstall',
                'cache_expiration',
                'ai_provider',
                'ai_model',
                'ai_api_key_openrouter',
                'ai_api_key_openai',
                'ai_api_key_anthropic',
                'ai_api_key_google',
                'nonce',
                'action'
            ];
            $filtered_post = Request::only( $expected_fields );
            $options = $this->sanitize_options( $filtered_post );
            // Strip out any masked API keys so they are not saved over existing ones
            $api_key_fields = [
                'ai_api_key_openrouter',
                'ai_api_key_openai',
                'ai_api_key_anthropic',
                'ai_api_key_google',
                'ai_api_key'
            ];
            foreach ( $api_key_fields as $field ) {
                if ( isset( $options[$field] ) && (strpos( $options[$field], '••••••••' ) !== false || empty( $options[$field] )) ) {
                    // Revert to current setting to prevent overwriting with dots or erasing existing keys
                    $options[$field] = $current_settings[$field] ?? '';
                }
            }
            // Check if Option class method exists
            if ( method_exists( 'IntentDeep\\VirtualFiles\\Core\\Option', 'normalize_option_types' ) ) {
                $normalized_options = Option::normalize_option_types( $options );
            } else {
                // Fallback to sanitized options directly
                $normalized_options = $options;
            }
            $result = update_option( 'intentdeep_vf_settings', $normalized_options );
            // ALWAYS check if routing_enabled changed, regardless of $result
            // (update_option returns false if value hasn't changed, but we still need to flush if routing changed)
            if ( isset( $normalized_options['routing_enabled'] ) ) {
                $this->handleRoutingChange( $current_settings['routing_enabled'] ?? true, $normalized_options['routing_enabled'] );
            }
            // update_option returns false when value hasn't changed (which is not an error)
            // The try-catch block above will catch actual database errors
            wp_send_json_success( [
                'options' => $normalized_options,
                'message' => __( "Settings saved successfully", 'intentdeep-virtual-files' ),
                'stats'   => [
                    'active_files' => $this->getActiveFileCount(),
                    'total_files'  => $this->getTotalFileCount(),
                    'max_files'    => $this->getMaxFilesDisplay(),
                ],
            ] );
        } catch ( Exception $e ) {
            wp_send_json_error( [
                'message' => __( "Error processing settings: ", 'intentdeep-virtual-files' ) . $e->getMessage(),
            ] );
        }
    }

    /**
     * Flush rewrite rules via AJAX
     */
    public function flushRewriteRules() : void {
        // Check nonce
        if ( !check_ajax_referer( 'intentdeep_vf_settings', 'nonce', false ) ) {
            wp_send_json_error( "Invalid nonce", 419 );
        }
        if ( !current_user_can( 'manage_options' ) ) {
            wp_send_json_error( "Unauthorized user", 403 );
        }
        flush_rewrite_rules();
        wp_send_json_success( [
            'message' => __( "Rewrite rules flushed successfully", 'intentdeep-virtual-files' ),
        ] );
    }

    /**
     * Save user preference via AJAX
     */
    public function savePreference() : void {
        // Check nonce
        if ( !check_ajax_referer( 'intentdeep_vf_settings', 'nonce', false ) ) {
            wp_send_json_error( "Invalid nonce", 419 );
        }
        if ( !current_user_can( 'manage_options' ) ) {
            wp_send_json_error( "Unauthorized user", 403 );
        }
        $preference = ( isset( $_POST['preference'] ) ? sanitize_text_field( $_POST['preference'] ) : '' );
        $value = ( isset( $_POST['value'] ) ? sanitize_text_field( $_POST['value'] ) : '' );
        if ( empty( $preference ) ) {
            wp_send_json_error( "Missing preference name", 400 );
        }
        // Get current settings
        $settings = ( Option::all() ?: [] );
        // Save preference in user preferences array
        if ( !isset( $settings['user_preferences'] ) ) {
            $settings['user_preferences'] = [];
        }
        $settings['user_preferences'][$preference] = $value;
        // Save back to database
        update_option( 'intentdeep_vf_settings', $settings );
        wp_send_json_success( [
            'message' => __( "Preference saved successfully", 'intentdeep-virtual-files' ),
        ] );
    }

    /**
     * Prepare data for frontend
     */
    private function prepare_frontend_data() : array {
        $options = ( Option::all() ?: [] );
        return [
            'nonce'   => wp_create_nonce( 'intentdeep_vf_settings' ),
            'isPro'   => function_exists( 'intentdeep_vf_fs' ) && intentdeep_vf_fs()->can_use_premium_code__premium_only(),
            'ajaxUrl' => admin_url( 'admin-ajax.php' ),
            'options' => Option::normalize_option_types( $options ),
            'strings' => [
                'confirmDangerous' => __( 'Are you sure you want to perform this action?', 'intentdeep-virtual-files' ),
                'confirmReset'     => __( 'This will reset all settings to their default values. This action cannot be undone.', 'intentdeep-virtual-files' ),
                'upgradeRequired'  => __( 'This is a Pro feature. Would you like to upgrade?', 'intentdeep-virtual-files' ),
                'cacheWarmingUp'   => __( 'Warming up cache...', 'intentdeep-virtual-files' ),
                'cacheClearing'    => __( 'Clearing cache...', 'intentdeep-virtual-files' ),
                'cacheLoading'     => __( 'Loading cache stats...', 'intentdeep-virtual-files' ),
            ],
        ];
    }

    /**
     * Sanitize settings options
     */
    private function sanitize_options( $raw_options ) : array {
        $sanitized = [];
        // Debug: Log what we're receiving
        intentdeep_vf_log( 'Virtual Files sanitize_options called with: ' . print_r( $raw_options, true ) );
        // Sanitize routing_enabled - handle checkbox properly
        if ( isset( $raw_options['routing_enabled'] ) && $raw_options['routing_enabled'] === '1' ) {
            // Checkbox is checked
            $sanitized['routing_enabled'] = true;
        } else {
            // Checkbox is unchecked
            $sanitized['routing_enabled'] = false;
        }
        // Debug: Log routing_enabled value
        intentdeep_vf_log( 'Virtual Files routing_enabled set to: ' . (( $sanitized['routing_enabled'] ? 'true' : 'false' )) );
        // Sanitize cache_enabled - handle checkbox properly
        if ( isset( $raw_options['cache_enabled'] ) && $raw_options['cache_enabled'] === '1' ) {
            // Checkbox is checked
            $sanitized['cache_enabled'] = true;
        } else {
            // Checkbox is unchecked
            $sanitized['cache_enabled'] = false;
        }
        // Sanitize remove_data_on_uninstall
        if ( isset( $raw_options['remove_data_on_uninstall'] ) && $raw_options['remove_data_on_uninstall'] === '1' ) {
            $sanitized['remove_data_on_uninstall'] = true;
        } else {
            $sanitized['remove_data_on_uninstall'] = false;
        }
        // Sanitize cache_expiration
        if ( isset( $raw_options['cache_expiration'] ) ) {
            $sanitized['cache_expiration'] = intval( $raw_options['cache_expiration'] );
            $sanitized['cache_expiration'] = max( 60, min( 86400, $sanitized['cache_expiration'] ) );
            // Between 1 minute - 24 hours
        }
        // Sanitize AI settings
        $sanitized['ai_provider'] = ( isset( $raw_options['ai_provider'] ) ? sanitize_text_field( $raw_options['ai_provider'] ) : 'openrouter' );
        $sanitized['ai_model'] = ( isset( $raw_options['ai_model'] ) ? sanitize_text_field( $raw_options['ai_model'] ) : 'google/gemini-2.5-flash-lite' );
        $providers = [
            'openrouter',
            'openai',
            'anthropic',
            'google'
        ];
        foreach ( $providers as $provider ) {
            $key = 'ai_api_key_' . $provider;
            if ( isset( $raw_options[$key] ) ) {
                $sanitized[$key] = sanitize_text_field( $raw_options[$key] );
            }
        }
        // Set allowed_extensions based on user type (display-only, not configurable)
        $is_pro_user = function_exists( 'intentdeep_vf_fs' ) && intentdeep_vf_fs()->can_use_premium_code__premium_only();
        $all_possible_extensions = [
            'txt',
            'md',
            'json',
            'jsonld',
            'xml',
            'rss',
            'csv',
            'yml',
            'log'
        ];
        // Fixed allowed extensions based on user type
        $sanitized['allowed_extensions'] = ( $is_pro_user ? $all_possible_extensions : ['txt', 'md', 'json'] );
        // Set defaults for missing values
        $defaults = [
            'routing_enabled'          => true,
            'cache_enabled'            => true,
            'cache_expiration'         => 3600,
            'remove_data_on_uninstall' => false,
        ];
        return array_merge( $defaults, $sanitized );
    }

    /**
     * Get cache statistics via AJAX
     */
    public function getCacheStats() : void {
        // Check if user is pro
        if ( !function_exists( 'intentdeep_vf_fs' ) || !intentdeep_vf_fs()->can_use_premium_code__premium_only() ) {
            wp_send_json_error( [
                'message' => __( 'This feature is only available in Pro version', 'intentdeep-virtual-files' ),
            ] );
        }
        // Check nonce
        if ( !check_ajax_referer( 'intentdeep_vf_settings', 'nonce', false ) ) {
            wp_send_json_error( "Invalid nonce", 419 );
        }
        if ( !current_user_can( 'manage_options' ) ) {
            wp_send_json_error( "Unauthorized user", 403 );
        }
        $cache = new Cache();
        $stats = $cache->get_cache_stats();
        wp_send_json_success( [
            'stats'   => $stats,
            'message' => __( "Cache statistics retrieved successfully", 'intentdeep-virtual-files' ),
        ] );
    }

    /**
     * Warm up cache via AJAX
     */
    public function warmUpCache() : void {
        // Check if user is pro
        if ( !function_exists( 'intentdeep_vf_fs' ) || !intentdeep_vf_fs()->can_use_premium_code__premium_only() ) {
            wp_send_json_error( [
                'message' => __( 'This feature is only available in Pro version', 'intentdeep-virtual-files' ),
            ] );
        }
        // Check nonce
        if ( !check_ajax_referer( 'intentdeep_vf_settings', 'nonce', false ) ) {
            wp_send_json_error( "Invalid nonce", 419 );
        }
        if ( !current_user_can( 'manage_options' ) ) {
            wp_send_json_error( "Unauthorized user", 403 );
        }
        $cache = new Cache();
        $warmed_count = $cache->warm_up_cache();
        wp_send_json_success( [
            'warmed_count' => $warmed_count,
            'message'      => sprintf( 
                /* translators: %d: number of files cache warmed for */
                __( 'Cache warmed up successfully for %d files', 'intentdeep-virtual-files' ),
                $warmed_count
             ),
        ] );
    }

    /**
     * Clear all cache via AJAX
     */
    public function clearCache() : void {
        // Check if user is pro
        if ( !function_exists( 'intentdeep_vf_fs' ) || !intentdeep_vf_fs()->can_use_premium_code__premium_only() ) {
            wp_send_json_error( [
                'message' => __( 'This feature is only available in Pro version', 'intentdeep-virtual-files' ),
            ] );
        }
        // Check nonce
        if ( !check_ajax_referer( 'intentdeep_vf_settings', 'nonce', false ) ) {
            wp_send_json_error( "Invalid nonce", 419 );
        }
        if ( !current_user_can( 'manage_options' ) ) {
            wp_send_json_error( "Unauthorized user", 403 );
        }
        $cache = new Cache();
        $cleared_count = $cache->clear_all_caches();
        wp_send_json_success( [
            'cleared_count' => $cleared_count,
            'message'       => sprintf( 
                /* translators: %d: number of files cache cleared for */
                __( 'Cache cleared successfully for %d files', 'intentdeep-virtual-files' ),
                $cleared_count
             ),
        ] );
    }

    /**
     * Export virtual files (Pro feature)
     */
    public function exportFiles() : void {
        // Check if user is pro
        if ( !function_exists( 'intentdeep_vf_fs' ) || !intentdeep_vf_fs()->can_use_premium_code__premium_only() ) {
            wp_die( esc_html__( 'Export is only available in Pro version.', 'intentdeep-virtual-files' ), 403 );
        }
        // Check nonce
        if ( !check_ajax_referer( 'intentdeep_vf_settings', 'nonce', false ) ) {
            wp_die( esc_html__( 'Security check failed.', 'intentdeep-virtual-files' ), 419 );
        }
        if ( !current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have permission to export files.', 'intentdeep-virtual-files' ), 403 );
        }
        // Get all virtual files
        // Note: Only export from new post type 'idep_virtual_file'
        // Import supports both 'idep_virtual_file' and legacy 'virtual_file' for backward compatibility
        $files = get_posts( [
            'post_type'      => 'idep_virtual_file',
            'posts_per_page' => -1,
            'post_status'    => 'any',
        ] );
        if ( empty( $files ) ) {
            wp_die( esc_html__( 'No virtual files found to export.', 'intentdeep-virtual-files' ) );
        }
        // Prepare export data
        $export_data = [
            'version'     => '1.0',
            'export_date' => current_time( 'mysql' ),
            'site_url'    => get_site_url(),
            'files'       => [],
        ];
        foreach ( $files as $file ) {
            $file_data = [
                'id'          => $file->ID,
                'title'       => $file->post_title,
                'slug'        => $file->post_name,
                'status'      => $file->post_status,
                'created_at'  => $file->post_date,
                'updated_at'  => $file->post_modified,
                'filename'    => get_post_meta( $file->ID, '_vf_filename', true ),
                'content'     => get_post_meta( $file->ID, '_vf_content', true ),
                'mime_type'   => get_post_meta( $file->ID, '_vf_mime_type', true ),
                'status_meta' => get_post_meta( $file->ID, '_vf_status', true ),
                'modified'    => get_post_meta( $file->ID, '_vf_modified', true ),
            ];
            // Only include files with actual content
            if ( !empty( $file_data['filename'] ) && !empty( $file_data['content'] ) ) {
                $export_data['files'][] = $file_data;
            }
        }
        if ( empty( $export_data['files'] ) ) {
            wp_die( esc_html__( 'No valid virtual files found to export.', 'intentdeep-virtual-files' ) );
        }
        // Generate filename
        $filename = 'virtual-files-export-' . gmdate( 'Y-m-d-H-i-s' ) . '.json';
        // Prepare JSON output with consistent flags
        $json_output = json_encode( $export_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE );
        // Clean any output buffers to prevent interference
        if ( ob_get_level() ) {
            ob_end_clean();
        }
        // Set headers for file download
        header( 'Content-Type: application/json; charset=utf-8' );
        header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
        header( 'Content-Length: ' . strlen( $json_output ) );
        header( 'Cache-Control: no-cache, must-revalidate' );
        header( 'Pragma: no-cache' );
        header( 'Expires: 0' );
        // Output JSON
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- JSON export file output. Content is generated via json_encode() which properly escapes data. Only admins with manage_options capability can export.
        echo $json_output;
        // Flush and exit cleanly
        flush();
        exit;
    }

    /**
     * Import virtual files (Pro feature)
     */
    public function importFiles() : void {
        // Check if user is pro
        if ( !function_exists( 'intentdeep_vf_fs' ) || !intentdeep_vf_fs()->can_use_premium_code__premium_only() ) {
            wp_send_json_error( [
                'message' => __( 'Import is only available in Pro version.', 'intentdeep-virtual-files' ),
            ] );
        }
        // Check nonce
        if ( !check_ajax_referer( 'intentdeep_vf_settings', 'nonce', false ) ) {
            wp_send_json_error( [
                'message' => __( 'Security check failed.', 'intentdeep-virtual-files' ),
            ] );
        }
        if ( !current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [
                'message' => __( 'You do not have permission to import files.', 'intentdeep-virtual-files' ),
            ] );
        }
        // Check if file was uploaded
        if ( empty( $_FILES['import_file'] ) ) {
            wp_send_json_error( [
                'message' => __( 'No file uploaded.', 'intentdeep-virtual-files' ),
            ] );
        }
        $file = $_FILES['import_file'];
        // Validate file
        if ( $file['error'] !== UPLOAD_ERR_OK ) {
            $error_messages = [
                UPLOAD_ERR_INI_SIZE   => __( 'File is too large (server limit).', 'intentdeep-virtual-files' ),
                UPLOAD_ERR_FORM_SIZE  => __( 'File is too large.', 'intentdeep-virtual-files' ),
                UPLOAD_ERR_PARTIAL    => __( 'File was only partially uploaded.', 'intentdeep-virtual-files' ),
                UPLOAD_ERR_NO_FILE    => __( 'No file was uploaded.', 'intentdeep-virtual-files' ),
                UPLOAD_ERR_NO_TMP_DIR => __( 'Missing temporary folder.', 'intentdeep-virtual-files' ),
                UPLOAD_ERR_CANT_WRITE => __( 'Failed to write file to disk.', 'intentdeep-virtual-files' ),
                UPLOAD_ERR_EXTENSION  => __( 'File upload stopped by extension.', 'intentdeep-virtual-files' ),
            ];
            wp_send_json_error( [
                'message' => $error_messages[$file['error']] ?? __( 'Upload failed.', 'intentdeep-virtual-files' ),
            ] );
        }
        // Validate file size (10MB max)
        $max_size = 10 * 1024 * 1024;
        // 10MB
        if ( $file['size'] > $max_size ) {
            wp_send_json_error( [
                'message' => __( 'File is too large. Maximum size is 10MB.', 'intentdeep-virtual-files' ),
            ] );
        }
        // Validate file type
        $file_extension = strtolower( pathinfo( $file['name'], PATHINFO_EXTENSION ) );
        if ( !in_array( $file_extension, ['json', 'zip'] ) ) {
            wp_send_json_error( [
                'message' => __( 'Invalid file type. Only JSON and ZIP files are supported.', 'intentdeep-virtual-files' ),
            ] );
        }
        try {
            // Read file content
            $file_content = file_get_contents( $file['tmp_name'] );
            if ( $file_content === false ) {
                wp_send_json_error( [
                    'message' => __( 'Failed to read uploaded file.', 'intentdeep-virtual-files' ),
                ] );
            }
            if ( $file_extension === 'zip' ) {
                $import_result = $this->importFromZip( $file_content, $file['tmp_name'] );
            } else {
                $import_result = $this->importFromJson( $file_content );
            }
            // Force rewrite rules flush after import (using same logic as create/update)
            $this->forceRewriteFlush();
            // Determine appropriate success message
            if ( $import_result['imported'] > 0 ) {
                if ( $import_result['skipped'] > 0 ) {
                    /* translators: %1$d: number of new files imported, %2$d: number of files skipped */
                    $message = sprintf( 
                        /* translators: %1$d: number of new files imported, %2$d: number of files skipped */
                        __( 'Import completed successfully. %1$d new files imported, %2$d files skipped (already exist).', 'intentdeep-virtual-files' ),
                        $import_result['imported'],
                        $import_result['skipped']
                     );
                } else {
                    $message = sprintf( 
                        /* translators: %d: number of new files imported */
                        __( 'Import completed successfully. %d new files imported.', 'intentdeep-virtual-files' ),
                        $import_result['imported']
                     );
                }
            } elseif ( $import_result['skipped'] > 0 ) {
                $message = sprintf( 
                    /* translators: %d: number of files processed and skipped */
                    __( 'All files already exist. %d files processed and skipped.', 'intentdeep-virtual-files' ),
                    $import_result['processed']
                 );
            } else {
                $message = __( 'No files were imported.', 'intentdeep-virtual-files' );
            }
            wp_send_json_success( [
                'message' => $message,
                'summary' => $import_result,
                'stats'   => [
                    'active_files' => $this->getActiveFileCount(),
                    'total_files'  => $this->getTotalFileCount(),
                    'max_files'    => $this->getMaxFilesDisplay(),
                ],
            ] );
        } catch ( Exception $e ) {
            wp_send_json_error( [
                'message' => __( 'Import failed: ', 'intentdeep-virtual-files' ) . $e->getMessage(),
            ] );
        }
    }

    /**
     * Handle routing_enabled change - flush rewrite rules when setting changes
     */
    private function handleRoutingChange( $old_value, $new_value ) : void {
        // Convert both to boolean for proper comparison
        $old_bool = (bool) $old_value;
        $new_bool = (bool) $new_value;
        // Only flush if the routing_enabled setting actually changed
        if ( $old_bool !== $new_bool ) {
            // Log the change if debug is enabled
            intentdeep_vf_log( sprintf( 'Virtual Files: routing_enabled changed from %s to %s - flushing rewrite rules', ( $old_bool ? 'true' : 'false' ), ( $new_bool ? 'true' : 'false' ) ) );
            // If enabling routing, manually register virtual file rewrite rules first
            if ( $new_bool ) {
                $this->registerVirtualFileRewriteRules();
            }
            // Use the same simple flush as the manual Flush Rewrite Rules button
            flush_rewrite_rules();
        }
    }

    /**
     * Reset all plugin data via AJAX
     */
    public function resetPluginData() : void {
        // Check nonce
        if ( !check_ajax_referer( 'intentdeep_vf_settings', 'nonce', false ) ) {
            wp_send_json_error( [
                'message' => __( 'Security check failed.', 'intentdeep-virtual-files' ),
            ], 419 );
        }
        if ( !current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [
                'message' => __( 'You do not have permission to reset plugin data.', 'intentdeep-virtual-files' ),
            ], 403 );
        }
        try {
            // Delete all plugin data
            $summary = $this->deleteAllPluginData();
            wp_send_json_success( [
                'message' => __( 'Plugin data has been reset successfully.', 'intentdeep-virtual-files' ),
                'summary' => $summary,
                'stats'   => [
                    'active_files' => 0,
                    'total_files'  => 0,
                    'max_files'    => $this->getMaxFilesDisplay(),
                ],
            ] );
        } catch ( \Exception $e ) {
            wp_send_json_error( [
                'message' => __( 'Failed to reset plugin data: ', 'intentdeep-virtual-files' ) . $e->getMessage(),
            ] );
        }
    }

}
