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

class CodeEditor_CloudSync {
    protected $protocols = [
        'webdav' => 'WebDAV',
        'ftp' => 'FTP协议', 
        'sftp' => 'SFTP协议',
        'alist' => 'Alist网盘',
        'baidu' => '百度云盘',
        'smb' => 'SMB共享',
        'qqmail' => 'QQ邮箱',
        '163mail' => '网易邮箱'
    ];
    
    protected $protocol_forms = [
        'qqmail' => [
            ['type' => 'text', 'id' => 'qqmail-email', 'label' => 'QQ邮箱地址', 'required' => true],
            ['type' => 'password', 'id' => 'qqmail-password', 'label' => '授权码', 'required' => true],
            ['type' => 'text', 'id' => 'qqmail-smtp', 'label' => 'SMTP服务器', 'value' => 'smtp.qq.com'],
            ['type' => 'number', 'id' => 'qqmail-port', 'label' => '端口', 'value' => '465']
        ],
        '163mail' => [
            ['type' => 'text', 'id' => '163mail-email', 'label' => '网易邮箱地址', 'required' => true],
            ['type' => 'password', 'id' => '163mail-password', 'label' => '授权码', 'required' => true],
            ['type' => 'text', 'id' => '163mail-smtp', 'label' => 'SMTP服务器', 'value' => 'smtp.163.com'],
            ['type' => 'number', 'id' => '163mail-port', 'label' => '端口', 'value' => '465']
        ],
        'alist' => [
            ['type' => 'text', 'id' => 'alist-url', 'label' => 'Alist地址', 'required' => true],
            ['type' => 'text', 'id' => 'alist-username', 'label' => '用户名'],
            ['type' => 'password', 'id' => 'alist-password', 'label' => '密码'],
            ['type' => 'text', 'id' => 'alist-token', 'label' => '令牌(可选)']
        ],
        'baidu' => [
            ['type' => 'text', 'id' => 'baidu-access-key', 'label' => 'Access Key', 'required' => true],
            ['type' => 'text', 'id' => 'baidu-secret-key', 'label' => 'Secret Key', 'required' => true],
            ['type' => 'text', 'id' => 'baidu-bucket', 'label' => '存储桶名称']
        ],
        'smb' => [
            ['type' => 'text', 'id' => 'smb-host', 'label' => '主机/IP', 'required' => true],
            ['type' => 'text', 'id' => 'smb-share', 'label' => '共享名称', 'required' => true],
            ['type' => 'text', 'id' => 'smb-username', 'label' => '用户名'],
            ['type' => 'password', 'id' => 'smb-password', 'label' => '密码'],
            ['type' => 'text', 'id' => 'smb-domain', 'label' => '域(可选)']
        ]
    ];

    public function __construct() {
        add_action('wp_ajax_code_editor_cloud_connect', [$this, 'handle_connect_request']);
        add_action('wp_ajax_code_editor_send_to_email', [$this, 'handle_send_to_email']);
    }

    public function get_protocols() {
        return $this->protocols;
    }

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

        $protocol = isset($_POST['protocol']) ? sanitize_text_field($_POST['protocol']) : '';
        
        if (!array_key_exists($protocol, $this->protocols)) {
            wp_send_json_error('Invalid protocol', 400);
        }

        // 根据协议类型调用不同的连接方法
        $method = 'connect_' . $protocol;
        if (method_exists($this, $method)) {
            $this->$method();
        } else {
            wp_send_json_error('Protocol not implemented yet', 501);
        }
    }

    protected function connect_webdav() {
        // WebDAV连接逻辑已存在
        $webdav = new CodeEditor_WebDAV();
        $webdav->handle_connect_request();
    }

    protected function connect_ftp() {
        // TODO: 实现FTP连接
        wp_send_json_error('FTP connection not implemented yet', 501);
    }

    protected function connect_sftp() {
        // TODO: 实现SFTP连接
        wp_send_json_error('SFTP connection not implemented yet', 501);
    }

    protected function connect_alist() {
        $url = isset($_POST['url']) ? esc_url_raw($_POST['url']) : '';
        $username = isset($_POST['username']) ? sanitize_text_field($_POST['username']) : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        $token = isset($_POST['token']) ? sanitize_text_field($_POST['token']) : '';
        
        try {
            $api_url = rtrim($url, '/') . '/api/fs/list';
            $args = [
                'headers' => [
                    'Authorization' => $token ? 'Bearer ' . $token : 'Basic ' . base64_encode($username . ':' . $password)
                ]
            ];
            
            $response = wp_remote_get($api_url, $args);
            
            if (is_wp_error($response)) {
                throw new Exception($response->get_error_message());
            }
            
            $body = json_decode(wp_remote_retrieve_body($response), true);
            
            if ($body && isset($body['code']) && $body['code'] === 200) {
                wp_send_json_success([
                    'message' => 'Connected to Alist successfully',
                    'files' => $body['data']['content']
                ]);
            } else {
                wp_send_json_error('Alist connection failed: ' . ($body['message'] ?? 'Unknown error'), 400);
            }
        } catch (Exception $e) {
            wp_send_json_error('Alist connection failed: ' . $e->getMessage(), 500);
        }
    }

    protected function connect_baidu() {
        $access_key = isset($_POST['access-key']) ? sanitize_text_field($_POST['access-key']) : '';
        $secret_key = isset($_POST['secret-key']) ? sanitize_text_field($_POST['secret-key']) : '';
        $bucket = isset($_POST['bucket']) ? sanitize_text_field($_POST['bucket']) : '';
        
        if (empty($access_key) || empty($secret_key)) {
            wp_send_json_error('Access Key and Secret Key are required', 400);
        }

        try {
            // 使用百度云SDK进行连接
            $sdk_path = plugin_dir_path(__FILE__) . '../vendor/baidu-bcs-sdk/BaiduBCS.class.php';
            if (file_exists($sdk_path)) {
                require_once $sdk_path;
            } else {
                wp_send_json_error('Baidu BCS SDK not found', 500);
                return;
            }
            
            $bcs = new BaiduBCS($access_key, $secret_key);
            $response = $bcs->list_object($bucket);
            
            if ($response->isOK()) {
                $objects = $response->body->to_array()->Contents;
                wp_send_json_success([
                    'message' => 'Connected to Baidu Cloud successfully',
                    'files' => $objects
                ]);
            } else {
                wp_send_json_error('Baidu Cloud connection failed: ' . $response->status, 400);
            }
        } catch (Exception $e) {
            wp_send_json_error('Baidu Cloud connection failed: ' . $e->getMessage(), 500);
        }
    }

    protected function connect_smb() {
        $host = isset($_POST['host']) ? sanitize_text_field($_POST['host']) : '';
        $share = isset($_POST['share']) ? sanitize_text_field($_POST['share']) : '';
        $username = isset($_POST['username']) ? sanitize_text_field($_POST['username']) : '';
        $password = isset($_POST['password']) ? $_POST['password'] : ''; // 修复了这里的引号问题
        $domain = isset($_POST['domain']) ? sanitize_text_field($_POST['domain']) : '';
        
        if (empty($host) || empty($share)) {
            wp_send_json_error('Host and Share Name are required', 400);
        }

        try {
            // 使用SMB客户端库
            $lib_path = plugin_dir_path(__FILE__) . '../vendor/php-smbclient/SMBSession.php';
            if (file_exists($lib_path)) {
                require_once $lib_path;
            } else {
                wp_send_json_error('SMB client library not found', 500);
                return;
            }
            
            $session = new SMBSession($host, $username, $password, $domain);
            $files = $session->listFiles($share);
            
            wp_send_json_success([
                'message' => 'Connected to SMB share successfully',
                'files' => $files
            ]);
        } catch (Exception $e) {
            wp_send_json_error('SMB connection failed: ' . $e->getMessage(), 500);
        }
    }

    protected function connect_qqmail() {
        $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        $smtp = isset($_POST['smtp']) ? sanitize_text_field($_POST['smtp']) : 'smtp.qq.com';
        $port = isset($_POST['port']) ? intval($_POST['port']) : 465;
        
        if (empty($email) || empty($password)) {
            wp_send_json_error('邮箱地址和授权码是必填项', 400);
        }

        try {
            // 使用WordPress内置邮件函数测试连接
            add_action('phpmailer_init', function($phpmailer) use ($email, $password, $smtp, $port) {
                $phpmailer->isSMTP();
                $phpmailer->Host = $smtp;
                $phpmailer->SMTPAuth = true;
                $phpmailer->Port = $port;
                $phpmailer->Username = $email;
                $phpmailer->Password = $password;
                $phpmailer->SMTPSecure = 'ssl';
            });
            
            $test_result = wp_mail($email, '测试连接', '这是一封测试邮件');
            if (!$test_result) {
                throw new Exception('邮件发送测试失败');
            }
            
            wp_send_json_success([
                'message' => 'QQ邮箱连接成功',
                'email' => $email
            ]);
        } catch (Exception $e) {
            wp_send_json_error('QQ邮箱连接失败: ' . $e->getMessage(), 500);
        }
    }

    protected function connect_163mail() {
        $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        $smtp = isset($_POST['smtp']) ? sanitize_text_field($_POST['smtp']) : 'smtp.163.com';
        $port = isset($_POST['port']) ? intval($_POST['port']) : 465;
        
        if (empty($email) || empty($password)) {
            wp_send_json_error('邮箱地址和授权码是必填项', 400);
        }

        try {
            // 使用WordPress内置邮件函数测试连接
            add_action('phpmailer_init', function($phpmailer) use ($email, $password, $smtp, $port) {
                $phpmailer->isSMTP();
                $phpmailer->Host = $smtp;
                $phpmailer->SMTPAuth = true;
                $phpmailer->Port = $port;
                $phpmailer->Username = $email;
                $phpmailer->Password = $password;
                $phpmailer->SMTPSecure = 'ssl';
            });
            
            $test_result = wp_mail($email, '测试连接', '这是一封测试邮件');
            if (!$test_result) {
                throw new Exception('邮件发送测试失败');
            }
            
            wp_send_json_success([
                'message' => '网易邮箱连接成功',
                'email' => $email
            ]);
        } catch (Exception $e) {
            wp_send_json_error('网易邮箱连接失败: ' . $e->getMessage(), 500);
        }
    }

    public function handle_send_to_email() {
        check_ajax_referer('code_editor_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('无操作权限', 403);
        }

        $protocol = isset($_POST['protocol']) ? sanitize_text_field($_POST['protocol']) : '';
        $file_path = isset($_POST['file_path']) ? sanitize_text_field($_POST['file_path']) : '';
        $recipient = isset($_POST['recipient']) ? sanitize_email($_POST['recipient']) : '';
        
        if (empty($protocol) || empty($file_path) || empty($recipient)) {
            wp_send_json_error('协议、文件路径和收件人是必填项', 400);
        }

        try {
            $method = 'send_via_' . $protocol;
            if (method_exists($this, $method)) {
                $this->$method($file_path, $recipient);
            } else {
                wp_send_json_error('该协议不支持发送邮件', 400);
            }
        } catch (Exception $e) {
            wp_send_json_error('发送失败: ' . $e->getMessage(), 500);
        }
    }

    protected function send_via_qqmail($file_path, $recipient) {
        $this->send_email('qqmail', $file_path, $recipient);
    }

    protected function send_via_163mail($file_path, $recipient) {
        $this->send_email('163mail', $file_path, $recipient);
    }

    protected function send_email($protocol, $file_path, $recipient) {
        $base_path = ABSPATH;
        $full_path = realpath($base_path . $file_path);
        
        if (strpos($full_path, $base_path) !== 0 || !file_exists($full_path)) {
            wp_send_json_error('无效的文件路径', 400);
        }

        $email = get_option('cloud_sync_' . $protocol . '_email');
        $password = get_option('cloud_sync_' . $protocol . '_password');
        $smtp = get_option('cloud_sync_' . $protocol . '_smtp');
        $port = get_option('cloud_sync_' . $protocol . '_port');

        add_action('phpmailer_init', function($phpmailer) use ($email, $password, $smtp, $port) {
            $phpmailer->isSMTP();
            $phpmailer->Host = $smtp;
            $phpmailer->SMTPAuth = true;
            $phpmailer->Port = $port;
            $phpmailer->Username = $email;
            $phpmailer->Password = $password;
            $phpmailer->SMTPSecure = 'ssl';
        });

        $headers = array(
            'From: 文件同步服务 <' . $email . '>'
        );
        
        $attachments = array($full_path);
        $result = wp_mail($recipient, '文件同步: ' . basename($file_path), '请查收附件中的文件', $headers, $attachments);
        
        if ($result) {
            wp_send_json_success(['message' => '文件已成功发送到邮箱']);
        } else {
            wp_send_json_error('发送邮件失败', 500);
        }
    }
}

function code_editor_cloud_page() {
    $cloud_sync = new CodeEditor_CloudSync();
    $protocols = $cloud_sync->get_protocols();
    ?>
    <div class="wrap">
        <h1><?php _e('云同步服务', 'my-first-plugin'); ?></h1>
        <div class="cloud-sync-container">
            <div class="protocol-tabs">
                <?php foreach ($protocols as $key => $name): ?>
                <button class="protocol-tab" data-protocol="<?php echo esc_attr($key); ?>">
                    <?php echo esc_html($name); ?>
                </button>
                <?php endforeach; ?>
            </div>
            <div id="protocol-settings"></div>
        </div>
    </div>
    <?php
}

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