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

class CodeEditor_FileManager {
    public function __construct() {
        add_action('wp_ajax_code_editor_file_action', [$this, 'handle_file_actions']);
    }

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

        $action = sanitize_text_field($_POST['action_type']);
        $path = isset($_POST['path']) ? sanitize_text_field($_POST['path']) : '';
        
        switch ($action) {
            case 'list_files':
                $this->list_directory_contents($path);
                break;
            case 'get_file':
                $this->get_file_content($path);
                break;
            // 其他操作将在这里添加
            case 'upload_file':
                $this->handle_file_upload($path);
                break;
            case 'download_file':
                $this->download_file($path);
                break;
            default:
                wp_send_json_error('Invalid action', 400);
        }
    }

    private function handle_file_upload($path) {
        $base_path = ABSPATH;
        $full_path = realpath($base_path . $path);
        
        if (strpos($full_path, $base_path) !== 0 || !is_dir($full_path)) {
            wp_send_json_error('Invalid directory', 400);
        }

        if (!empty($_FILES['file'])) {
            $temp_file = $_FILES['file']['tmp_name'];
            $target_file = $full_path . '/' . sanitize_file_name($_FILES['file']['name']);
            
            if (move_uploaded_file($temp_file, $target_file)) {
                wp_send_json_success(['path' => str_replace($base_path, '', $target_file)]);
            }
        }
        
        wp_send_json_error('Upload failed', 500);
    }

    private function download_file($path) {
        $base_path = ABSPATH;
        $full_path = realpath($base_path . $path);
        
        if (strpos($full_path, $base_path) !== 0 || !is_file($full_path)) {
            wp_send_json_error('Invalid file', 400);
        }

        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($full_path).'"');
        header('Content-Length: ' . filesize($full_path));
        readfile($full_path);
        exit;
    }

    private function list_directory_contents($path) {
        $base_path = ABSPATH;
        $full_path = realpath($base_path . $path);
        
        if (strpos($full_path, $base_path) !== 0 || !is_dir($full_path)) {
            wp_send_json_error('Invalid directory', 400);
        }

        $items = [];
        foreach (new DirectoryIterator($full_path) as $item) {
            if ($item->isDot()) continue;
            
            $items[] = [
                'name' => $item->getFilename(),
                'path' => str_replace($base_path, '', $item->getPathname()),
                'type' => $item->isDir() ? 'directory' : 'file',
                'size' => $item->isFile() ? $item->getSize() : 0,
                'modified' => $item->getMTime()
            ];
        }

        wp_send_json_success($items);
    }

    private function get_file_content($path) {
        $base_path = ABSPATH;
        $full_path = realpath($base_path . $path);
        
        if (strpos($full_path, $base_path) !== 0 || !is_file($full_path)) {
            wp_send_json_error('Invalid file', 400);
        }

        $content = file_get_contents($full_path);
        wp_send_json_success([
            'content' => $content,
            'path' => $path
        ]);
    }
}

new CodeEditor_FileManager();