<?php
if (!defined('ABSPATH')) {
    exit;
}

class Cloud_Uploads_Settings {
    
    private $options;
    private $current_tab;
    private $tabs;
    
    public function __construct() {
        $this->options = get_option('cloud_uploads_options');
        $this->setup_tabs();
        $this->setup_hooks();
    }
    
    private function setup_tabs() {
        $this->tabs = array(
            'general' => array(
                'label' => 'General Settings',
                'icon' => 'dashicons-admin-generic'
            ),
            'backblaze' => array(
                'label' => 'Backblaze B2',
                'icon' => 'dashicons-backup'
            ),
            'sync' => array(
                'label' => 'Sync Status',
                'icon' => 'dashicons-update'
            ),
            'debug' => array(
                'label' => 'Debug & Tools',
                'icon' => 'dashicons-admin-tools'
            )
        );
        
        // Set current tab
        $this->current_tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'general';
        if (!array_key_exists($this->current_tab, $this->tabs)) {
            $this->current_tab = 'general';
        }
    }
    
    private function setup_hooks() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'settings_init'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_styles'));
    }
    
    public function enqueue_admin_styles($hook) {
        if ($hook === 'media_page_cloud-uploads') {
            wp_enqueue_style('cloud-uploads-admin', CLOUD_UPLOADS_PLUGIN_URL . 'assets/css/admin.css', array(), CLOUD_UPLOADS_VERSION);
        }
    }
    
    public function add_admin_menu() {
        add_media_page(
            'Cloud Uploads',
            'Cloud Uploads',
            'manage_options',
            'cloud-uploads',
            array($this, 'settings_page')
        );
    }
    
    public function settings_init() {
        register_setting('cloud_uploads_general', 'cloud_uploads_options', array($this, 'sanitize_options'));
        
        // General Settings Tab
        add_settings_section(
            'cloud_uploads_general_section',
            'S3 Compatible Storage Settings',
            array($this, 'general_section_callback'),
            'cloud_uploads_general'
        );
        
        $general_fields = array(
            'access_key' => 'Access Key ID',
            'secret_key' => 'Secret Access Key',
            'bucket_name' => 'Bucket Name',
            'region' => 'Region',
            'endpoint' => 'Custom Endpoint',
            'path_prefix' => 'Path Prefix',
            'delete_remote' => 'Delete from S3 when deleted from WordPress',
            'rewrite_urls' => 'Rewrite URLs to use S3 location',
            'use_cdn' => 'Use CDN for media URLs',
            'cdn_url' => 'CDN Base URL'
        );
        
        foreach ($general_fields as $field => $label) {
            add_settings_field(
                $field,
                $label,
                array($this, 'field_callback'),
                'cloud_uploads_general',
                'cloud_uploads_general_section',
                array('label_for' => $field, 'field' => $field, 'tab' => 'general')
            );
        }
        
        // Backblaze B2 Tab - No settings, just information and tools
        add_settings_section(
            'cloud_uploads_backblaze_section',
            'Backblaze B2 Configuration',
            array($this, 'backblaze_section_callback'),
            'cloud_uploads_backblaze'
        );
        
        // Sync Status Tab - No settings, just status display
        add_settings_section(
            'cloud_uploads_status_section',
            'Sync Status & Operations',
            array($this, 'status_section_callback'),
            'cloud_uploads_sync'
        );
        
        // Debug Tab - Tools and debugging
        add_settings_section(
            'cloud_uploads_debug_section',
            'Debugging & Tools',
            array($this, 'debug_section_callback'),
            'cloud_uploads_debug'
        );
    }
    
    // ==================== SECTION CALLBACK METHODS ====================
    
    /**
     * General Settings section callback
     */
    public function general_section_callback() {
        echo '<p>Configure your S3 compatible storage settings below. These settings are required for the plugin to function.</p>';
        
        // Show configuration status
        if ($this->is_configured()) {
            echo '<div class="notice notice-success inline"><p>';
            echo '<span class="dashicons dashicons-yes"></span> ';
            echo 'All required settings are configured.';
            echo '</p></div>';
        } else {
            echo '<div class="notice notice-warning inline"><p>';
            echo '<span class="dashicons dashicons-warning"></span> ';
            echo 'Please fill in all required settings to enable S3 sync functionality.';
            echo '</p></div>';
        }
    }
    
    /**
     * Backblaze B2 section callback
     */
    public function backblaze_section_callback() {
        echo '<p>Backblaze B2 specific configuration and tools. Use this section if you\'re using Backblaze B2 as your S3-compatible storage.</p>';
        
        if ($this->is_backblaze_configured()) {
            echo '<div class="notice notice-info inline"><p>';
            echo '<span class="dashicons dashicons-backup"></span> ';
            echo 'Backblaze B2 configuration detected.';
            echo '</p></div>';
        }
    }
    
    /**
     * Sync Status section callback
     */
    public function status_section_callback() {
        echo '<p>Monitor sync progress and manage bulk operations. This section shows the current status of your media library sync.</p>';
        
        if (!$this->is_configured()) {
            echo '<div class="notice notice-warning inline"><p>';
            echo '<span class="dashicons dashicons-warning"></span> ';
            echo 'Please configure your S3 settings on the General Settings tab first.';
            echo '</p></div>';
        }
    }
    
    /**
     * Debug section callback
     */
    public function debug_section_callback() {
        echo '<p>Debugging tools and diagnostic information. Use these tools to troubleshoot issues with cloud uploads and synchronization.</p>';
        
        // Show debug mode status
        if (defined('WP_DEBUG') && WP_DEBUG) {
            echo '<div class="notice notice-info inline"><p>';
            echo '<span class="dashicons dashicons-info"></span> ';
            echo 'WordPress debug mode is enabled. Additional debug information will be logged.';
            echo '</p></div>';
        }
    }
    
    // ==================== SETTINGS PAGE RENDERING ====================
    
    public function settings_page() {
        // Initialize required classes for status display
        $s3_client = null;
        $url_rewriter = null;
        $bulk_sync = null;
        $sync_stats = array(
            'total' => 0,
            'synced' => 0,
            'unsynced' => 0,
            'percentage' => 0
        );
        
        if ($this->is_configured()) {
            try {
                $s3_client = new Cloud_Uploads_Client($this);
                $s3_sync = new Cloud_Uploads($s3_client, $this);
                $url_rewriter = new S3_URL_Rewriter($this);
                $bulk_sync = new Bulk_Sync_Manager($s3_sync);
                $sync_stats = $bulk_sync->get_sync_stats();
            } catch (Exception $e) {
                error_log('Cloud Uploads: Error initializing classes for settings page - ' . $e->getMessage());
            }
        }
        
        ?>
        <div class="wrap cloud-uploads-settings">
            <h1 class="s3-settings-title">
                <span class="dashicons dashicons-cloud"></span>
                Cloud Uploads Settings
            </h1>
            
            <?php $this->display_admin_notices(); ?>
            
            <nav class="nav-tab-wrapper">
                <?php foreach ($this->tabs as $tab_id => $tab): ?>
                    <a href="<?php echo esc_url($this->get_tab_url($tab_id)); ?>" 
                       class="nav-tab <?php echo $this->current_tab === $tab_id ? 'nav-tab-active' : ''; ?>">
                        <span class="dashicons <?php echo esc_attr($tab['icon']); ?>"></span>
                        <?php echo esc_html($tab['label']); ?>
                    </a>
                <?php endforeach; ?>
            </nav>
            
            <div class="s3-settings-content">
                <?php
                switch ($this->current_tab) {
                    case 'general':
                        $this->render_general_tab();
                        break;
                    case 'backblaze':
                        $this->render_backblaze_tab($s3_client);
                        break;
                    case 'sync':
                        $this->render_sync_tab($sync_stats, $bulk_sync, $url_rewriter);
                        break;
                    case 'debug':
                        $this->render_debug_tab($s3_client);
                        break;
                }
                ?>
            </div>
        </div>
        <?php
    }
    
    private function render_general_tab() {
        ?>
        <form method="post" action="options.php" class="s3-settings-form">
            <?php
            settings_fields('cloud_uploads_general');
            do_settings_sections('cloud_uploads_general');
            submit_button('Save Settings', 'primary', 'submit', true, array('id' => 'submit-general'));
            ?>
        </form>
        
        <div class="s3-settings-sidebar">
            <div class="s3-info-box">
                <h3>Quick Setup Guide</h3>
                <ol>
                    <li>Enter your S3-compatible service credentials</li>
                    <li>Configure your bucket and region settings</li>
                    <li>Test the connection using the Sync Status tab</li>
                    <li>Enable URL rewriting if you want to serve files from S3</li>
                </ol>
            </div>
            
            <div class="s3-info-box">
                <h3>Supported Services</h3>
                <ul>
                    <li>Amazon S3</li>
                    <li>Backblaze B2</li>
                    <li>DigitalOcean Spaces</li>
                    <li>Any S3-compatible service</li>
                </ul>
            </div>
        </div>
        <?php
    }
    
    private function render_backblaze_tab($s3_client) {
        $is_backblaze = $this->is_backblaze_configured();
        ?>
        <div class="s3-backblaze-content">
            <div class="s3-main-content">
                <div class="s3-info-box">
                    <h3>Backblaze B2 Configuration</h3>
                    
                    <?php if (!$is_backblaze): ?>
                        <div class="notice notice-warning">
                            <p>Your current configuration doesn't appear to be using Backblaze B2. To use Backblaze B2:</p>
                            <ol>
                                <li>Set your Endpoint to: <code>s3.us-west-001.backblazeb2.com</code> (or your preferred region)</li>
                                <li>Set Region to: <code>us-west-001</code> (matching your endpoint)</li>
                                <li>Use your Backblaze B2 Application Key ID and Application Key</li>
                            </ol>
                        </div>
                    <?php endif; ?>
                    
                    <h4>Backblaze B2 Regions</h4>
                    <table class="widefat fixed" style="width: 100%;">
                        <thead>
                            <tr>
                                <th>Region Name</th>
                                <th>Endpoint</th>
                                <th>Region Code</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $backblaze_regions = array(
                                'us-west-001' => array('US West', 's3.us-west-001.backblazeb2.com'),
                                'us-west-002' => array('US West (Northern California)', 's3.us-west-002.backblazeb2.com'),
                                'us-east-005' => array('US East', 's3.us-east-005.backblazeb2.com'),
                                'eu-central-003' => array('EU Central', 's3.eu-central-003.backblazeb2.com')
                            );
                            
                            foreach ($backblaze_regions as $region_code => $region_info):
                            ?>
                            <tr>
                                <td><?php echo esc_html($region_info[0]); ?></td>
                                <td><code><?php echo esc_html($region_info[1]); ?></code></td>
                                <td><code><?php echo esc_html($region_code); ?></code></td>
                                <td>
                                    <button type="button" class="button button-small apply-b2-region" 
                                            data-endpoint="<?php echo esc_attr($region_info[1]); ?>" 
                                            data-region="<?php echo esc_attr($region_code); ?>">
                                        Apply
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <?php if ($is_backblaze && $s3_client): ?>
                <div class="s3-info-box">
                    <h3>Backblaze B2 Tools</h3>
                    
                    <div class="b2-tools">
                        <p>
                            <button type="button" id="test-b2-connection" class="button button-secondary">
                                Test B2 Connection
                            </button>
                            <span class="description">Test connection to Backblaze B2</span>
                        </p>
                        
                        <p>
                            <button type="button" id="get-b2-bucket-info" class="button button-secondary">
                                Get Bucket Information
                            </button>
                            <span class="description">Retrieve B2 bucket details</span>
                        </p>
                    </div>
                    
                    <div id="b2-tools-results" style="display: none; margin-top: 15px; padding: 10px; border-radius: 4px;"></div>
                </div>
                <?php endif; ?>
            </div>
            
            <div class="s3-settings-sidebar">
                <div class="s3-info-box">
                    <h3>Backblaze B2 Tips</h3>
                    <ul>
                        <li>Use Application Keys instead of Master Keys for better security</li>
                        <li>Ensure your bucket is set to "Public" if you want to serve files directly</li>
                        <li>Backblaze B2 offers free egress through Cloudflare</li>
                        <li>Consider using a custom domain with Cloudflare for CDN benefits</li>
                    </ul>
                </div>
            </div>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            $('.apply-b2-region').on('click', function() {
                var endpoint = $(this).data('endpoint');
                var region = $(this).data('region');
                
                // Redirect to general tab with pre-filled values
                var url = '<?php echo esc_url($this->get_tab_url('general')); ?>';
                url += '&b2_endpoint=' + encodeURIComponent(endpoint);
                url += '&b2_region=' + encodeURIComponent(region);
                
                window.location.href = url;
            });
        });
        </script>
        <?php
    }
    
    private function render_sync_tab($sync_stats, $bulk_sync, $url_rewriter) {
        $bulk_sync_active = isset($_GET['bulk_sync']);
        ?>
        <div class="s3-sync-content">
            <div class="s3-main-content">
                <?php if (!$this->is_configured()): ?>
                    <div class="notice notice-warning">
                        <p>Please configure your S3 settings on the General Settings tab before using sync features.</p>
                    </div>
                <?php else: ?>
                
                <div class="s3-info-box">
                    <h3>Sync Status</h3>
                    
                    <div class="sync-stats-grid">
                        <div class="stat-box">
                            <div class="stat-number"><?php echo esc_html($sync_stats['total']); ?></div>
                            <div class="stat-label">Total Media Files</div>
                        </div>
                        <div class="stat-box">
                            <div class="stat-number"><?php echo esc_html($sync_stats['synced']); ?></div>
                            <div class="stat-label">Synced to S3</div>
                        </div>
                        <div class="stat-box">
                            <div class="stat-number"><?php echo esc_html($sync_stats['unsynced']); ?></div>
                            <div class="stat-label">Need Sync</div>
                        </div>
                        <div class="stat-box">
                            <div class="stat-number"><?php echo esc_html($sync_stats['percentage']); ?>%</div>
                            <div class="stat-label">Completion</div>
                        </div>
                    </div>
                    
                    <div class="progress-container">
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: <?php echo esc_attr($sync_stats['percentage']); ?>%"></div>
                        </div>
                        <div class="progress-text"><?php echo esc_html($sync_stats['percentage']); ?>% Complete</div>
                    </div>
                </div>
                
                <div class="s3-info-box">
                    <h3>Bulk Operations</h3>
                    
                    <?php if ($sync_stats['unsynced'] > 0): ?>
                    <div id="bulk-sync-container" class="<?php echo $bulk_sync_active ? 'active' : ''; ?>">
                        <?php if (!$bulk_sync_active): ?>
                        <p>
                            <a href="<?php echo wp_nonce_url(admin_url('admin.php?action=sync_all_to_s3'), 'sync_all_to_s3'); ?>" 
                               class="button button-primary" id="start-bulk-sync">
                                Start Bulk Sync
                            </a>
                            <span class="description">Upload all unsynced media files to S3</span>
                        </p>
                        <?php else: ?>
                        <div id="sync-progress">
                            <div class="progress-bar large">
                                <div class="progress-fill" style="width: <?php echo esc_attr($sync_stats['percentage']); ?>%"></div>
                            </div>
                            <div class="progress-text">
                                <span class="percentage"><?php echo esc_html($sync_stats['percentage']); ?>%</span>
                                <span class="status-text">Ready to start</span>
                            </div>
                            <div class="progress-details">
                                <p>Processed: <span class="processed">0</span> / <span class="total"><?php echo esc_html($sync_stats['unsynced']); ?></span></p>
                                <p>Success: <span class="success">0</span> | Failed: <span class="failed">0</span></p>
                            </div>
                            <div class="progress-buttons">
                                <button type="button" class="button button-secondary" id="pause-sync" style="display: none;">Pause</button>
                                <button type="button" class="button button-secondary" id="resume-sync" style="display: none;">Resume</button>
                                <button type="button" class="button button-secondary" id="cancel-sync">Cancel</button>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php else: ?>
                    <div class="notice notice-success">
                        <p>All media files are already synced to S3!</p>
                    </div>
                    <?php endif; ?>
                </div>
                
                <?php if (isset($url_rewriter)): ?>
                <div class="s3-info-box">
                    <h3>URL Information</h3>
                    <table class="widefat">
                        <tr>
                            <th width="200">Local Upload URL</th>
                            <td><code><?php echo esc_html($url_rewriter->get_local_base_url()); ?></code></td>
                        </tr>
                        <tr>
                            <th>S3 Base URL</th>
                            <td><code><?php echo esc_html($url_rewriter->get_s3_base_url()); ?></code></td>
                        </tr>
                        <tr>
                            <th>URL Rewriting</th>
                            <td>
                                <?php if ($this->get_option('rewrite_urls')): ?>
                                    <span class="dashicons dashicons-yes" style="color: #46b450;"></span> Enabled
                                <?php else: ?>
                                    <span class="dashicons dashicons-no" style="color: #dc3232;"></span> Disabled
                                <?php endif; ?>
                            </td>
                        </tr>
                        <tr>
                            <th>CDN</th>
                            <td>
                                <?php if ($this->get_option('use_cdn')): ?>
                                    <span class="dashicons dashicons-yes" style="color: #46b450;"></span> Enabled
                                    <?php if ($this->get_option('cdn_url')): ?>
                                        <br><code><?php echo esc_html($this->get_option('cdn_url')); ?></code>
                                    <?php else: ?>
                                        <br><span class="description">CDN URL not set</span>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="dashicons dashicons-no" style="color: #dc3232;"></span> Disabled
                                <?php endif; ?>
                            </td>
                        </tr>
                    </table>
                </div>
                <?php endif; ?>
                
                <?php endif; ?>
            </div>
        </div>
        <?php
    }
    
    private function render_debug_tab($s3_client) {
        ?>
        <div class="s3-debug-content">
            <div class="s3-main-content">
                <div class="s3-info-box">
                    <h3>Debug Information</h3>
                    
                    <div class="debug-section">
                        <h4>Server Information</h4>
                        <?php
                        $server_info = array(
                            'PHP Version' => phpversion(),
                            'WordPress Version' => get_bloginfo('version'),
                            'Plugin Version' => CLOUD_UPLOADS_VERSION,
                            'Memory Limit' => ini_get('memory_limit'),
                            'Max Execution Time' => ini_get('max_execution_time'),
                            'Upload Max Filesize' => ini_get('upload_max_filesize')
                        );
                        ?>
                        <table class="widefat">
                            <?php foreach ($server_info as $label => $value): ?>
                            <tr>
                                <th width="200"><?php echo esc_html($label); ?></th>
                                <td><?php echo esc_html($value); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </table>
                    </div>
                    
                    <div class="debug-section">
                        <h4>Plugin Configuration</h4>
                        <table class="widefat">
                            <tr>
                                <th width="200">Settings Configured</th>
                                <td>
                                    <?php if ($this->is_configured()): ?>
                                        <span class="dashicons dashicons-yes" style="color: #46b450;"></span> Yes
                                    <?php else: ?>
                                        <span class="dashicons dashicons-no" style="color: #dc3232;"></span> No
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Using AWS SDK</th>
                                <td>
                                    <?php if ($s3_client && $s3_client->is_using_aws_sdk()): ?>
                                        <span class="dashicons dashicons-yes" style="color: #46b450;"></span> Yes
                                    <?php else: ?>
                                        <span class="dashicons dashicons-no" style="color: #dc3232;"></span> No (HTTP Fallback)
                                    <?php endif; ?>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }
    
    private function display_admin_notices() {
        if (isset($_GET['settings-updated']) && $_GET['settings-updated']) {
            echo '<div class="notice notice-success is-dismissible"><p>Settings saved successfully.</p></div>';
        }
        
        if (isset($_GET['b2_endpoint']) && isset($_GET['b2_region'])) {
            echo '<div class="notice notice-info is-dismissible"><p>Backblaze B2 settings applied. Please save the settings to confirm.</p></div>';
        }
    }
    
    private function get_tab_url($tab) {
        return add_query_arg('tab', $tab, admin_url('upload.php?page=cloud-uploads'));
    }
    
    private function is_backblaze_configured() {
        $endpoint = $this->get_option('endpoint');
        return $endpoint && strpos($endpoint, 'backblazeb2.com') !== false;
    }
    
    // ==================== FIELD CALLBACKS ====================
    
    public function field_callback($args) {
        $field = $args['field'];
        $value = isset($this->options[$field]) ? $this->options[$field] : '';
        
        // Pre-fill Backblaze B2 values if they were passed in URL
        if (isset($_GET['b2_endpoint']) && $field === 'endpoint' && empty($value)) {
            $value = sanitize_text_field($_GET['b2_endpoint']);
        }
        if (isset($_GET['b2_region']) && $field === 'region' && empty($value)) {
            $value = sanitize_text_field($_GET['b2_region']);
        }
        
        switch ($field) {
            case 'secret_key':
                echo '<input type="password" id="' . $field . '" name="cloud_uploads_options[' . $field . ']" value="' . esc_attr($value) . '" class="regular-text">';
                break;
            case 'delete_remote':
            case 'rewrite_urls':
                echo '<input type="checkbox" id="' . $field . '" name="cloud_uploads_options[' . $field . ']" value="1" ' . checked(1, $value, false) . '>';
                echo '<p class="description">' . 
                    ($field === 'rewrite_urls' ? 'All media URLs will be served from S3' : 
                    'Files will be deleted from S3 when removed from WordPress') . 
                    '</p>';
                break;
            case 'use_cdn':
                echo '<input type="checkbox" id="' . $field . '" name="cloud_uploads_options[' . $field . ']" value="1" ' . checked(1, $value, false) . '>';
                echo '<p class="description">Enable to serve media files via a CDN</p>';
                break;
            case 'cdn_url':
                echo '<input type="text" id="' . $field . '" name="cloud_uploads_options[' . $field . ']" value="' . esc_attr($value) . '" class="regular-text" placeholder="https://cdn.example.com">';
                echo '<p class="description">Base URL of your CDN (e.g., https://cdn.example.com/)</p>';
                break;
            case 'access_key':
                echo '<input type="text" id="' . $field . '" name="cloud_uploads_options[' . $field . ']" value="' . esc_attr($value) . '" class="regular-text">';
                break;
            case 'secret_key':
                echo '<input type="password" id="' . $field . '" name="cloud_uploads_options[' . $field . ']" value="' . esc_attr($value) . '" class="regular-text">';
                break;
            case 'bucket_name':
                echo '<input type="text" id="' . $field . '" name="cloud_uploads_options[' . $field . ']" value="' . esc_attr($value) . '" class="regular-text">';
                break;
            case 'endpoint':
                echo '<input type="text" id="' . $field . '" name="cloud_uploads_options[' . $field . ']" value="' . esc_attr($value) . '" class="regular-text">';
                echo '<p class="description">For S3-compatible services (e.g., s3.us-west-001.backblazeb2.com)</p>';
                break;
            case 'region':
                echo '<input type="text" id="' . $field . '" name="cloud_uploads_options[' . $field . ']" value="' . esc_attr($value) . '" class="regular-text">';
                echo '<p class="description">Region for your S3-compatible service</p>';
                break;
            case 'path_prefix':
                echo '<input type="text" id="' . $field . '" name="cloud_uploads_options[' . $field . ']" value="' . esc_attr($value) . '" class="regular-text" placeholder="uploads/">';
                echo '<p class="description">Optional prefix for S3 file paths</p>';
                break;
            default:
                echo '<input type="text" id="' . $field . '" name="cloud_uploads_options[' . $field . ']" value="' . esc_attr($value) . '" class="regular-text">';
        }
    }
    
    // ==================== SANITIZATION ====================
    
    public function sanitize_options($input) {
        $sanitized = array();
        
        foreach ($input as $key => $value) {
            switch ($key) {
                case 'access_key':
                case 'secret_key':
                case 'bucket_name':
                case 'use_cdn':
                case 'cdn_url':
                case 'region':
                case 'endpoint':
                case 'path_prefix':
                    $sanitized[$key] = sanitize_text_field($value);
                    break;
                case 'delete_remote':
                case 'rewrite_urls':
                    $sanitized[$key] = $value ? 1 : 0;
                    break;
                default:
                    $sanitized[$key] = sanitize_text_field($value);
            }
        }
        
        return $sanitized;
    }
    
    // ==================== UTILITY METHODS ====================
    
    public function get_option($key) {
        return isset($this->options[$key]) ? $this->options[$key] : '';
    }
    
    public function is_configured() {
        return !empty($this->options['access_key']) && 
               !empty($this->options['secret_key']) && 
               !empty($this->options['bucket_name']) && 
               !empty($this->options['region']);
    }
}