<?php
/**
 * 存储管理控制器
 */

use Plugin\storage\StorageManager;

class StorageController
{
    private $db;
    private $view;

    public function __construct()
    {
        if (class_exists('Database')) {
            $this->db = \Database::getInstance();
        }
    }

    /**
     * 设置页面
     */
    public function config()
    {
        $this->checkAdmin();
        
        $manager = new StorageManager();
        $currentType = $manager->getCurrentStorageType();
        
        $types = $manager->getStorageTypes();
        $configs = [];
        
        foreach ($types as $type => $name) {
            $driver = $manager->getDriver($type);
            $configs[$type] = [
                'name' => $name,
                'enabled' => $manager->isStorageEnabled($type),
                'is_current' => ($type === $currentType),
                'config_form' => $driver->getConfigForm(),
                'config_values' => $manager->getConfig($type)
            ];
        }
        
        // 加载视图
        $this->render('storage/config', [
            'types' => $types,
            'current_type' => $currentType,
            'configs' => $configs
        ]);
    }

    /**
     * 保存设置
     */
    public function saveConfig()
    {
        $this->checkAdmin();
        
        if (!\Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        try {
            $type = \Helper::post('type');
            $isDefault = \Helper::post('is_default', 0);
            
            if (empty($type)) {
                $this->jsonError('存储类型不能为空');
            }
            
            $manager = new StorageManager();
            
            // 获取配置表单
            $driver = $manager->getDriver($type);
            $formConfig = $driver->getConfigForm();
            
            // 收集配置值
            $configs = [];
            foreach ($formConfig['fields'] as $field) {
                $name = str_replace($type . '_', '', $field['name']);
                $value = \Helper::post($field['name'], '');
                $configs[$name] = $value;
            }
            
            // 保存配置
            $manager->saveConfig($type, $configs);
            
            // 如果是默认存储
            if ($isDefault) {
                $manager->setCurrentStorageType($type);
            }
            
            $this->jsonSuccess(null, '保存成功');
        } catch (\Exception $e) {
            $this->jsonError('保存失败: ' . $e->getMessage());
        }
    }

    /**
     * 文件管理页面
     */
    public function files()
    {
        $this->checkAdmin();
        
        $page = max(1, intval(\Helper::get('page', 1)));
        $limit = 20;
        $offset = ($page - 1) * $limit;
        
        $type = \Helper::get('type', '');
        $fileType = \Helper::get('file_type', '');
        $keyword = \Helper::get('keyword', '');
        
        $where = [];
        $params = [];
        
        if ($type) {
            $where[] = 'storage_type = ?';
            $params[] = $type;
        }
        
        if ($fileType) {
            $where[] = 'file_type = ?';
            $params[] = $fileType;
        }
        
        if ($keyword) {
            $where[] = '(original_name LIKE ? OR filename LIKE ?)';
            $params[] = '%' . $keyword . '%';
            $params[] = '%' . $keyword . '%';
        }
        
        $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';
        
        // 获取文件列表
        $sql = "SELECT * FROM __PREFIX__storage_files $whereClause ORDER BY created_at DESC LIMIT $limit OFFSET $offset";
        $files = $this->db->fetchAll($sql, $params);
        
        // 获取总数
        $countSql = "SELECT COUNT(*) as total FROM __PREFIX__storage_files $whereClause";
        $total = $this->db->fetch($countSql, $params)['total'];
        
        $pages = ceil($total / $limit);
        
        // 格式化数据
        foreach ($files as &$file) {
            $file['created_time'] = date('Y-m-d H:i', $file['created_at']);
            $file['size_formatted'] = $this->formatFileSize($file['file_size']);
        }
        
        $this->render('storage/files', [
            'files' => $files,
            'page' => $page,
            'pages' => $pages,
            'total' => $total,
            'type' => $type,
            'file_type' => $fileType,
            'keyword' => $keyword
        ]);
    }

    /**
     * 删除文件
     */
    public function deleteFile()
    {
        $this->checkAdmin();
        
        if (!\Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        $id = \Helper::post('id', 0);
        
        $file = $this->db->fetch("SELECT * FROM __PREFIX__storage_files WHERE id = ?", [$id]);
        
        if (!$file) {
            $this->jsonError('文件不存在');
        }
        
        // 删除物理文件
        $manager = new StorageManager();
        $driver = $manager->getDriver($file['storage_type']);
        $driver->delete($file['path']);
        
        // 删除数据库记录
        $this->db->delete('storage_files', 'id = ?', [$id]);
        
        $this->jsonSuccess(null, '删除成功');
    }

    /**
     * 批量删除文件
     */
    public function batchDelete()
    {
        $this->checkAdmin();
        
        if (!\Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        $ids = \Helper::post('ids', '');
        
        if (empty($ids)) {
            $this->jsonError('请选择要删除的文件');
        }
        
        $idArray = array_map('intval', explode(',', $ids));
        $manager = new StorageManager();
        
        foreach ($idArray as $id) {
            $file = $this->db->fetch("SELECT * FROM __PREFIX__storage_files WHERE id = ?", [$id]);
            
            if ($file) {
                $driver = $manager->getDriver($file['storage_type']);
                $driver->delete($file['path']);
                $this->db->delete('storage_files', 'id = ?', [$id]);
            }
        }
        
        $this->jsonSuccess(null, '批量删除成功');
    }

    /**
     * 本地文件浏览
     */
    public function browseLocal()
    {
        $this->checkAdmin();
        
        $path = \Helper::get('path', '');
        $basePath = defined('UPLOAD_PATH') ? UPLOAD_PATH : (\ROOT_PATH . 'uploads/');
        $currentPath = $basePath . ltrim($path, '/');
        
        // 安全检查：防止路径遍历
        if (strpos(realpath($currentPath), realpath($basePath)) !== 0) {
            $currentPath = $basePath;
            $path = '';
        }
        
        if (!is_dir($currentPath)) {
            $currentPath = $basePath;
            $path = '';
        }
        
        $items = [];
        
        // 获取上级目录
        $parentPath = '';
        if ($path) {
            $pathParts = explode('/', trim($path, '/'));
            array_pop($pathParts);
            $parentPath = implode('/', $pathParts);
        }
        
        // 列出目录内容
        if (is_dir($currentPath)) {
            $dh = opendir($currentPath);
            while (($item = readdir($dh)) !== false) {
                if ($item == '.' || $item == '..') continue;
                
                $itemPath = $currentPath . '/' . $item;
                $relativePath = ($path ? $path . '/' : '') . $item;
                
                $isDir = is_dir($itemPath);
                $size = $isDir ? 0 : filesize($itemPath);
                
                $items[] = [
                    'name' => $item,
                    'path' => $relativePath,
                    'is_dir' => $isDir,
                    'size' => $size,
                    'size_formatted' => $isDir ? '-' : $this->formatFileSize($size),
                    'modified' => date('Y-m-d H:i', filemtime($itemPath))
                ];
            }
            closedir($dh);
        }
        
        // 按目录/文件排序
        usort($items, function($a, $b) {
            if ($a['is_dir'] !== $b['is_dir']) {
                return $a['is_dir'] ? -1 : 1;
            }
            return strcmp($a['name'], $b['name']);
        });
        
        $this->render('storage/browse', [
            'items' => $items,
            'current_path' => $path,
            'parentPath' => $parentPath,
            'base_url' => defined('SITE_URL') ? rtrim(SITE_URL, '/') : ''
        ]);
    }

    /**
     * 获取存储统计
     */
    public function stats()
    {
        $this->checkAdmin();
        
        $manager = new StorageManager();
        $stats = $manager->getStorageStats();
        
        $totalSize = 0;
        $totalFiles = 0;
        
        foreach ($stats as $stat) {
            $totalSize += $stat['total_size'];
            $totalFiles += $stat['file_count'];
        }
        
        $this->jsonSuccess([
            'stats' => $stats,
            'total_size' => $totalSize,
            'total_size_formatted' => $this->formatFileSize($totalSize),
            'total_files' => $totalFiles
        ]);
    }

    /**
     * 验证云存储配置
     */
    public function testConnection()
    {
        $this->checkAdmin();
        
        $type = \Helper::post('type');
        
        $manager = new StorageManager();
        $valid = $manager->validateStorageConfig($type);
        
        if ($valid) {
            $this->jsonSuccess(null, '配置验证通过');
        } else {
            $this->jsonError('配置验证失败，请检查配置项');
        }
    }

    /**
     * 检查管理员权限
     */
    private function checkAdmin()
    {
        if (!isset($_SESSION['user_id']) || !isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
            if (\Helper::isAjax()) {
                $this->jsonError('无权限', 403);
            }
            header('Location: ' . \Helper::url('user/login'));
            exit;
        }
    }

    /**
     * 渲染视图
     */
    private function render($template, $data = [])
    {
        // 移除模板名中的 "storage/" 前缀
        $templateName = str_replace('storage/', '', $template);
        $templateFile = dirname(__FILE__) . '/views/' . $templateName . '.php';

        if (!file_exists($templateFile)) {
            echo '模板文件不存在: ' . $templateName;
            return;
        }

        // 创建View实例
        $view = new \View();
        
        // 禁用默认布局，因为我们直接渲染布局文件
        $view->setLayout(null);
        
        // 渲染插件视图
        ob_start();
        extract($data);
        include $templateFile;
        $content = ob_get_clean();
        
        // 将插件内容传递给View
        $view->assign('content', $content);
        
        // 将其他数据也传递给View
        foreach ($data as $key => $value) {
            $view->assign($key, $value);
        }
        
        // 直接渲染布局文件（不额外套布局）
        echo $view->render('layouts/admin');
    }

    /**
     * 返回JSON成功
     */
    private function jsonSuccess($data, $message = '操作成功')
    {
        while (ob_get_level() > 0) {
            ob_end_clean();
        }
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['code' => 0, 'message' => $message, 'data' => $data], JSON_UNESCAPED_UNICODE);
        exit;
    }

    /**
     * 返回JSON错误
     */
    private function jsonError($message, $code = 1)
    {
        while (ob_get_level() > 0) {
            ob_end_clean();
        }
        header('Content-Type: application/json; charset=utf-8');
        http_response_code(200);
        echo json_encode(['code' => $code, 'message' => $message, 'data' => null], JSON_UNESCAPED_UNICODE);
        exit;
    }

    /**
     * 格式化文件大小
     */
    private function formatFileSize($bytes)
    {
        if ($bytes < 1024) {
            return $bytes . ' B';
        } elseif ($bytes < 1024 * 1024) {
            return round($bytes / 1024, 2) . ' KB';
        } elseif ($bytes < 1024 * 1024 * 1024) {
            return round($bytes / (1024 * 1024), 2) . ' MB';
        } else {
            return round($bytes / (1024 * 1024 * 1024), 2) . ' GB';
        }
    }

    /**
     * 获取文件图标
     * @param string $ext 文件扩展名
     * @return string
     */
    public function getFileIcon($ext)
    {
        $icons = [
            'archive' => ['zip', 'rar', '7z', 'tar', 'gz'],
            'pdf' => ['pdf'],
            'word' => ['doc', 'docx'],
            'excel' => ['xls', 'xlsx', 'csv'],
            'video' => ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv'],
            'audio' => ['mp3', 'wav', 'flac', 'aac', 'ogg'],
            'code' => ['html', 'css', 'js', 'json', 'xml', 'php', 'py', 'java'],
            'text' => ['txt', 'md', 'log']
        ];

        foreach ($icons as $icon => $extensions) {
            if (in_array($ext, $extensions)) {
                return $icon . '-o';
            }
        }

        return 'text-o';
    }

    /**
     * 删除本地文件
     */
    public function deleteLocalFile()
    {
        $this->checkAdmin();

        if (!\Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }

        $path = \Helper::post('path', '');

        if (empty($path)) {
            $this->jsonError('文件路径不能为空');
        }

        $basePath = defined('UPLOAD_PATH') ? UPLOAD_PATH : (\ROOT_PATH . 'uploads/');
        $fullPath = $basePath . ltrim($path, '/');

        // 安全检查：防止路径遍历
        if (strpos(realpath(dirname($fullPath)), realpath($basePath)) !== 0) {
            $this->jsonError('非法路径');
        }

        if (!file_exists($fullPath)) {
            $this->jsonError('文件不存在');
        }

        if (is_dir($fullPath)) {
            $this->jsonError('不能删除目录');
        }

        if (@unlink($fullPath)) {
            $this->jsonSuccess(null, '删除成功');
        } else {
            $this->jsonError('删除失败，请检查权限');
        }
    }
}
