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

class CodeEditor_WebDAV {
    public function __construct() {
        add_action('wp_ajax_code_editor_webdav_connect', [$this, 'handle_connect_request']);
        add_action('wp_ajax_code_editor_webdav_list', [$this, 'handle_list_request']);
        add_action('wp_ajax_code_editor_webdav_download', [$this, 'handle_download_request']);
        add_action('wp_ajax_code_editor_webdav_upload', [$this, 'handle_upload_request']);
    }

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

        $url = isset($_POST['url']) ? esc_url_raw($_POST['url']) : '';
        $username = isset($_POST['username']) ? sanitize_text_field($_POST['username']) : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        
        error_log('WebDAV Connection Attempt: ' . $url . ' by user: ' . $username);
        
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, rtrim($url, '/') . '/remote.php/dav/');
            curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PROPFIND');
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Depth: 1',
                'Content-Type: application/xml'
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            
            if ($httpCode === 207) { // WebDAV Multi-Status
                // 保存服务器配置
                update_option('webdav_server_url', $url);
                update_option('webdav_username', $username);
                update_option('webdav_password', $password);
                
                wp_send_json_success([
                    'message' => 'Connected to Nextcloud successfully',
                    'serverInfo' => [
                        'username' => $username,
                        'url' => $url
                    ]
                ]);
            } else {
                wp_send_json_error('Nextcloud connection failed with HTTP code: ' . $httpCode, $httpCode);
            }
            
            curl_close($ch);
        } catch (\Exception $e) {
            wp_send_json_error('Nextcloud connection failed: ' . $e->getMessage(), 500);
        }
    }

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

        $path = isset($_POST['path']) ? sanitize_text_field($_POST['path']) : '';
        
        try {
            $url = rtrim(get_option('webdav_server_url'), '/') . '/remote.php/dav/files/' . 
                  get_option('webdav_username') . '/' . ltrim($path, '/');
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_USERPWD, get_option('webdav_username') . ":" . get_option('webdav_password'));
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PROPFIND');
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Depth: 1',
                'Content-Type: application/xml'
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            
            if ($httpCode === 207) {
                $xml = simplexml_load_string($response);
                $files = [];
                
                foreach ($xml->xpath('//d:response') as $response) {
                    $href = (string)$response->xpath('d:href')[0];
                    $isDir = count($response->xpath('d:propstat/d:prop/d:resourcetype/d:collection')) > 0;
                    
                    if (basename($href) === '') continue; // Skip root
                    
                    $files[] = [
                        'name' => basename($href),
                        'type' => $isDir ? 'directory' : 'file',
                        'path' => $href
                    ];
                }
                
                wp_send_json_success(['files' => $files]);
            } else {
                wp_send_json_error('Failed to list files with HTTP code: ' . $httpCode, $httpCode);
            }
            
            curl_close($ch);
        } catch (\Exception $e) {
            wp_send_json_error('Failed to list files: ' . $e->getMessage(), 500);
        }
    }

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

        $remotePath = isset($_POST['remotePath']) ? sanitize_text_field($_POST['remotePath']) : '';
        $localPath = isset($_POST['localPath']) ? sanitize_text_field($_POST['localPath']) : '';
        
        try {
            $base_path = ABSPATH;
            $full_local_path = realpath($base_path . $localPath);
            
            if (strpos($full_local_path, $base_path) !== 0) {
                wp_send_json_error('Invalid local path', 400);
            }

            $url = rtrim(get_option('webdav_server_url'), '/') . $remotePath;
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_USERPWD, get_option('webdav_username') . ":" . get_option('webdav_password'));
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_FILE, fopen($full_local_path, 'w'));
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            
            if ($httpCode === 200) {
                wp_send_json_success([
                    'message' => 'File downloaded successfully',
                    'path' => $localPath
                ]);
            } else {
                wp_send_json_error('Download failed with HTTP code: ' . $httpCode, $httpCode);
            }
            
            curl_close($ch);
            fclose($full_local_path);
        } catch (\Exception $e) {
            wp_send_json_error('Download failed: ' . $e->getMessage(), 500);
        }
    }

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

        $localPath = isset($_POST['localPath']) ? sanitize_text_field($_POST['localPath']) : '';
        $remotePath = isset($_POST['remotePath']) ? sanitize_text_field($_POST['remotePath']) : '';
        
        try {
            $base_path = ABSPATH;
            $full_local_path = realpath($base_path . $localPath);
            
            if (strpos($full_local_path, $base_path) !== 0 || !file_exists($full_local_path)) {
                wp_send_json_error('Invalid local file', 400);
            }

            $url = rtrim(get_option('webdav_server_url'), '/') . $remotePath;
            $file_content = file_get_contents($full_local_path);
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_USERPWD, get_option('webdav_username') . ":" . get_option('webdav_password'));
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $file_content);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/octet-stream',
                'Content-Length: ' . filesize($full_local_path)
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            
            if ($httpCode === 201 || $httpCode === 204) {
                wp_send_json_success([
                    'message' => 'File uploaded successfully',
                    'path' => $remotePath
                ]);
            } else {
                wp_send_json_error('Upload failed with HTTP code: ' . $httpCode, $httpCode);
            }
            
            curl_close($ch);
        } catch (\Exception $e) {
            wp_send_json_error('Upload failed: ' . $e->getMessage(), 500);
        }
    }
}

new CodeEditor_WebDAV();