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

class CodeEditor_Terminal {
    public function __construct() {
        add_action('wp_ajax_code_editor_execute_command', [$this, 'handle_command_request']);
        add_action('wp_ajax_code_editor_save_ssh_password', [$this, 'handle_save_ssh_password']);
        add_action('wp_ajax_code_editor_rdp_connect', [$this, 'handle_rdp_connect']);
    }

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

        $command = isset($_POST['command']) ? sanitize_text_field($_POST['command']) : '';
        $path = isset($_POST['path']) ? sanitize_text_field($_POST['path']) : '';
        
        if (empty($command)) {
            wp_send_json_error('Empty command', 400);
        }

        $result = $this->execute_command($command, $path);
        wp_send_json_success($result);
    }

    private function execute_command($command, $path = '') {
        $base_path = ABSPATH;
        $full_path = $base_path;
        
        if ($path) {
            $full_path = realpath($base_path . $path);
            if (strpos($full_path, $base_path) !== 0 || !is_dir($full_path)) {
                return [
                    'success' => false,
                    'output' => 'Invalid directory path',
                    'exit_code' => 1
                ];
            }
        }

        // 检查是否是SSH命令
        if (strpos($command, 'ssh ') === 0) {
            return $this->execute_ssh_command($command);
        }

        $descriptors = [
            0 => ['pipe', 'r'], // stdin
            1 => ['pipe', 'w'], // stdout
            2 => ['pipe', 'w']  // stderr
        ];

        $process = proc_open($command, $descriptors, $pipes, $full_path);
        
        if (!is_resource($process)) {
            return [
                'success' => false,
                'output' => 'Failed to execute command',
                'exit_code' => 1
            ];
        }

        $output = stream_get_contents($pipes[1]);
        $error = stream_get_contents($pipes[2]);
        
        fclose($pipes[0]);
        fclose($pipes[1]);
        fclose($pipes[2]);
        
        $exit_code = proc_close($process);

        return [
            'success' => $exit_code === 0,
            'output' => $output ?: $error,
            'exit_code' => $exit_code
        ];
    }

    private function execute_ssh_command($command) {
        // 解析SSH连接参数
        preg_match('/ssh\s+(?:-i\s+([^\s]+)\s+)?([^\s]+)@([^\s]+)(?:\s+(.*))?/', $command, $matches);
        
        if (count($matches) < 4) {
            return [
                'success' => false,
                'output' => 'Invalid SSH command format',
                'exit_code' => 1
            ];
        }

        $private_key = $matches[1] ?? '';
        $username = $matches[2];
        $host = $matches[3];
        $remote_command = $matches[4] ?? '';

        try {
            // 使用phpseclib实现SSH连接
            if (!class_exists('phpseclib3\Net\SSH2')) {
                require_once ABSPATH . 'wp-content/plugins/my-first-plugin/vendor/autoload.php';
            }

            $ssh = new \phpseclib3\Net\SSH2($host);
            
            if ($private_key) {
                $key = \phpseclib3\Crypt\PublicKeyLoader::load(
                    file_get_contents($private_key)
                );
                if (!$ssh->login($username, $key)) {
                    throw new \Exception('SSH key authentication failed');
                }
            } else {
                $password = get_option('terminal_ssh_password_' . md5($username . '@' . $host));
                if (!$ssh->login($username, $password)) {
                    throw new \Exception('SSH password authentication failed');
                }
            }

            $output = $ssh->exec($remote_command);
            return [
                'success' => true,
                'output' => $output,
                'exit_code' => 0
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'output' => 'SSH Error: ' . $e->getMessage(),
                'exit_code' => 1
            ];
        }
    }

    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']) : '';
        $settings = isset($_POST['settings']) ? $_POST['settings'] : [];
        
        if (empty($host)) {
            wp_send_json_error('Computer name is required', 400);
        }

        // 生成RDP文件内容
        $rdp_content = "full address:s:{$host}\n";
        if (!empty($username)) {
            $rdp_content .= "username:s:{$username}\n";
        }
        if ($settings['fullscreen']) {
            $rdp_content .= "screen mode id:i:2\n";
        } else {
            $rdp_content .= "screen mode id:i:1\n";
            $rdp_content .= "desktopwidth:i:{$settings['width']}\n";
            $rdp_content .= "desktopheight:i:{$settings['height']}\n";
        }
        $rdp_content .= "session bpp:i:32\n";
        $rdp_content .= "winposstr:s:0,1,0,0,800,600\n";

        $filename = "connection_{$host}_" . date('YmdHis') . ".rdp";
        
        wp_send_json_success([
            'rdp_content' => $rdp_content,
            'filename' => $filename
        ]);
    }

    public function handle_save_ssh_password() {
        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']) : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        
        if (empty($host) || empty($username)) {
            wp_send_json_error('Host and username are required', 400);
        }

        // 加密存储密码
        if (empty($password)) {
            wp_send_json_error('Password is required', 400);
        }
        
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        if ($hashed_password === false) {
            wp_send_json_error('Password encryption failed', 500);
        }
        
        update_option('terminal_ssh_password_' . md5($username . '@' . $host), $hashed_password);
        
        wp_send_json_success(['message' => 'SSH credentials saved successfully']);
    }
}

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