<?php
defined('ABSPATH') or die('Direct access not allowed');

class CodeEditor_RDP {
    public function __construct() {
        add_action('wp_ajax_code_editor_rdp_connect', [$this, 'handle_rdp_connect']);
        add_action('wp_ajax_code_editor_save_rdp_settings', [$this, 'handle_save_rdp_settings']);
    }

    public function handle_rdp_connect() {
        check_ajax_referer('code_editor_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized', 403);
        }

        $host = isset($_POST['host']) ? sanitize_text_field($_POST['host']) : '';
        $username = isset($_POST['username']) ? sanitize_text_field($_POST['username']) : '';
        
        if (empty($host)) {
            wp_send_json_error('Host is required', 400);
        }

        // 生成RDP文件内容
        $rdp_content = $this->generate_rdp_file($host, $username);
        
        wp_send_json_success([
            'rdp_content' => $rdp_content,
            'filename' => sanitize_file_name($host . '.rdp')
        ]);
    }

    private function generate_rdp_file($host, $username) {
        $settings = get_option('code_editor_rdp_settings_' . md5($host . $username), []);
        
        $content = [
            'full address:s:' . $host,
            'username:s:' . $username,
            'screen mode id:i:' . ($settings['fullscreen'] ?? 1),
            'desktopwidth:i:' . ($settings['width'] ?? 1024),
            'desktopheight:i:' . ($settings['height'] ?? 768),
            'session bpp:i:' . ($settings['color_depth'] ?? 16),
            'redirectclipboard:i:1',
            'redirectprinters:i:1',
            'audiomode:i:0'
        ];

        return implode("\n", $content);
    }

    public function handle_save_rdp_settings() {
        check_ajax_referer('code_editor_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized', 403);
        }

        $host = isset($_POST['host']) ? sanitize_text_field($_POST['host']) : '';
        $username = isset($_POST['username']) ? sanitize_text_field($_POST['username']) : '';
        $settings = isset($_POST['settings']) ? $_POST['settings'] : [];
        
        if (empty($host)) {
            wp_send_json_error('Host is required', 400);
        }

        update_option('code_editor_rdp_settings_' . md5($host . $username), $settings);
        wp_send_json_success();
    }
}

// 确保只实例化一次
if (!isset($GLOBALS['code_editor_rdp'])) {
    $GLOBALS['code_editor_rdp'] = new CodeEditor_RDP();
}