
<?php
class WP_File_Manager_Pro_Ajax {
// 获取目录内容
public function ajax_get_contents() {
try {
check_ajax_referer('fm-pro-security', 'security');

        $path = isset($_POST['path']) ? realpath(ABSPATH . ltrim($_POST['path'], '/')) : ABSPATH;
        
        if (!$this->is_valid_path($path)) {
            throw new Exception(__('访问路径受限', 'wp-file-manager-pro'));
        }

        $items = array_diff(scandir($path), ['.', '..']);
        $contents = [];
        
        foreach ($items as $item) {
            $full_path = $path . DIRECTORY_SEPARATOR . $item;
            $contents[] = [
                'name' => $item,
                'path' => str_replace(ABSPATH, '', $full_path),
                'type' => is_dir($full_path) ? 'directory' : 'file',
                'size' => is_file($full_path) ? size_format(filesize($full_path)) : '',
                'modified' => date('Y-m-d H:i:s', filemtime($full_path)),
                'permissions' => substr(sprintf('%o', fileperms($full_path)), -4)
            ];
        }
        
        wp_send_json_success([
            'path' => str_replace(ABSPATH, '', $path),
            'contents' => $contents
        ]);
        
    } catch (Exception $e) {
        wp_send_json_error(['message' => $e->getMessage()]);
    }
}

// 文件编辑
public function ajax_edit_file() {
    try {
        check_ajax_referer('fm-pro-security', 'security');
        
        $path = isset($_POST['path']) ? realpath(ABSPATH . ltrim($_POST['path'], '/')) : '';
        
        if (!$this->is_valid_path($path)) {
            throw new Exception(__('访问路径受限', 'wp-file-manager-pro'));
        }

        $content = file_get_contents($path);
        if ($content === false) {
            throw new Exception(__('无法读取文件内容', 'wp-file-manager-pro'));
        }

        wp_send_json_success([
            'content' => $content,
            'path' => str_replace(ABSPATH, '', $path)
        ]);
        
    } catch (Exception $e) {
        wp_send_json_error(['message' => $e->getMessage()]);
    }
}

// 文件保存
public function ajax_save_file() {
    try {
        check_ajax_referer('fm-pro-security', 'security');
        
        $path = isset($_POST['path']) ? realpath(ABSPATH . ltrim($_POST['path'], '/')) : '';
        $content = isset($_POST['content']) ? $_POST['content'] : '';
        
        if (!$this->is_valid_path($path)) {
            throw new Exception(__('访问路径受限', 'wp-file-manager-pro'));
        }

        if (file_put_contents($path, $content) === false) {
            throw new Exception(__('文件保存失败', 'wp-file-manager-pro'));
        }

        wp_send_json_success(['message' => __('文件保存成功', 'wp-file-manager-pro')]);
        
    } catch (Exception $e) {
        wp_send_json_error(['message' => $e->getMessage()]);
    }
}

// 文件上传
public function ajax_upload() {
    try {
        check_ajax_referer('fm-pro-security', 'security');
        
        if (empty($_FILES['files'])) {
            throw new Exception(__('未选择文件', 'wp-file-manager-pro'));
        }

        $current_path = isset($_POST['current_path']) ? realpath(ABSPATH . ltrim($_POST['current_path'], '/')) : ABSPATH;
        
        if (!$this->is_valid_path($current_path)) {
            throw new Exception(__('访问路径受限', 'wp-file-manager-pro'));
        }

        $results = [];
        foreach ($_FILES['files']['name'] as $key => $value) {
            $file_name = sanitize_file_name($value);
            $file_tmp = $_FILES['files']['tmp_name'][$key];
            $target_path = $current_path . DIRECTORY_SEPARATOR . $file_name;
            
            if (move_uploaded_file($file_tmp, $target_path)) {
                $results[] = [
                    'name' => $file_name,
                    'path' => str_replace(ABSPATH, '', $target_path),
                    'status' => 'success'
                ];
            } else {
                $results[] = [
                    'name' => $file_name,
                    'status' => 'failed',
                    'error' => __('文件上传失败', 'wp-file-manager-pro')
                ];
            }
        }

        wp_send_json_success([
            'message' => __('文件上传完成', 'wp-file-manager-pro'),
            'results' => $results
        ]);
    } catch (Exception $e) {
        wp_send_json_error(['message' => $e->getMessage()]);
    }
}

// 创建目录
public function ajax_create_directory() {
    try {
        check_ajax_referer('fm-pro-security', 'security');
        
        $path = isset($_POST['path']) ? realpath(ABSPATH . ltrim($_POST['path'], '/')) : '';
        $dir_name = isset($_POST['dir_name']) ? sanitize_file_name($_POST['dir_name']) : '';
        
        if (!$this->is_valid_path($path)) {
            throw new Exception(__('访问路径受限', 'wp-file-manager-pro'));
        }

        $new_dir = $path . DIRECTORY_SEPARATOR . $dir_name;
        if (!mkdir($new_dir, 0755)) {
            throw new Exception(__('目录创建失败', 'wp-file-manager-pro'));
        }

        wp_send_json_success([
            'message' => __('目录创建成功', 'wp-file-manager-pro'),
            'path' => str_replace(ABSPATH, '', $new_dir)
        ]);
    } catch (Exception $e) {
        wp_send_json_error(['message' => $e->getMessage()]);
    }
}

// 删除项目
public function ajax_delete_item() {
    try {
        check_ajax_referer('fm-pro-security', 'security');
        
        $path = isset($_POST['path']) ? realpath(ABSPATH . ltrim($_POST['path'], '/')) : '';
        
        if (!$this->is_valid_path($path)) {
            throw new Exception(__('访问路径受限', 'wp-file-manager-pro'));
        }

        if (is_dir($path)) {
            $this->delete_directory($path);
        } else {
            if (!unlink($path)) {
                throw new Exception(__('文件删除失败', 'wp-file-manager-pro'));
            }
        }

        wp_send_json_success(['message' => __('删除成功', 'wp-file-manager-pro')]);
    } catch (Exception $e) {
        wp_send_json_error(['message' => $e->getMessage()]);
    }
}

// 重命名项目
public function ajax_rename_item() {
    try {
        check_ajax_referer('fm-pro-security', 'security');
        
        $path = isset($_POST['path']) ? realpath(ABSPATH . ltrim($_POST['path'], '/')) : '';
        $new_name = isset($_POST['new_name']) ? sanitize_file_name($_POST['new_name']) : '';
        
        if (!$this->is_valid_path($path)) {
            throw new Exception(__('访问路径受限', 'wp-file-manager-pro'));
        }

        $parent_dir = dirname($path);
        $new_path = $parent_dir . DIRECTORY_SEPARATOR . $new_name;

        if (!rename($path, $new_path)) {
            throw new Exception(__('重命名失败', 'wp-file-manager-pro'));
        }

        wp_send_json_success([
            'message' => __('重命名成功', 'wp-file-manager-pro'),
            'new_path' => str_replace(ABSPATH, '', $new_path)
        ]);
    } catch (Exception $e) {
        wp_send_json_error(['message' => $e->getMessage()]);
    }
}

// 复制项目
public function ajax_copy_item() {
    try {
        check_ajax_referer('fm-pro-security', 'security');
        
        $source = isset($_POST['source']) ? realpath(ABSPATH . ltrim($_POST['source'], '/')) : '';
        $destination = isset($_POST['destination']) ? realpath(ABSPATH . ltrim($_POST['destination'], '/')) : '';
        
        if (!$this->is_valid_path($source) || !$this->is_valid_path($destination)) {
            throw new Exception(__('访问路径受限', 'wp-file-manager-pro'));
        }

        $dest_path = $destination . DIRECTORY_SEPARATOR . basename($source);
        
        if (is_dir($source)) {
            $this->copy_directory($source, $dest_path);
        } else {
            if (!copy($source, $dest_path)) {
                throw new Exception(__('文件复制失败', 'wp-file-manager-pro'));
            }
        }

        wp_send_json_success([
            'message' => __('复制成功', 'wp-file-manager-pro'),
            'new_path' => str_replace(ABSPATH, '', $dest_path)
        ]);
    } catch (Exception $e) {
        wp_send_json_error(['message' => $e->getMessage()]);
    }
}
