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

namespace Plugin\storage;

use Plugin\storage\drivers\Driver;
use Plugin\storage\drivers\LocalDriver;
use Plugin\storage\drivers\QiniuDriver;
use Plugin\storage\drivers\AliyunDriver;
use Plugin\storage\drivers\TencentDriver;

class StorageManager
{
    private static $instance = null;
    private $currentDriver = null;
    private $config = [];

    /**
     * 获取单例实例
     */
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->loadConfig();
        $this->initDriver();
    }

    /**
     * 加载配置
     */
    private function loadConfig()
    {
        if (!class_exists('Database')) {
            return;
        }

        try {
            $db = \Database::getInstance();
            $rows = $db->fetchAll("SELECT * FROM __PREFIX__storage_config");
            
            foreach ($rows as $row) {
                $this->config[$row['storage_type']][$row['config_key']] = $row['config_value'];
            }
        } catch (\Exception $e) {
            // 使用默认值
            $this->config = [
                'local' => ['enabled' => '1']
            ];
        }
    }

    /**
     * 初始化当前驱动
     */
    private function initDriver()
    {
        $currentType = $this->getCurrentStorageType();
        $this->currentDriver = $this->getDriver($currentType);
    }

    /**
     * 获取当前存储类型
     */
    public function getCurrentStorageType()
    {
        $defaultType = \Setting::get('storage_type', 'local');
        return $defaultType;
    }

    /**
     * 设置当前存储类型
     */
    public function setCurrentStorageType($type)
    {
        if (class_exists('Database')) {
            try {
                $db = \Database::getInstance();
                $db->query("DELETE FROM __PREFIX__settings WHERE `key` = 'storage_type'");
                $db->insert('settings', [
                    'key' => 'storage_type',
                    'value' => $type
                ]);
            } catch (\Exception $e) {
                // 可能表不存在
            }
        }
        $this->currentDriver = $this->getDriver($type);
    }

    /**
     * 获取驱动实例
     */
    public function getDriver($type)
    {
        $type = strtolower($type);
        
        switch ($type) {
            case 'qiniu':
                return new \Plugin\storage\drivers\QiniuDriver($this->config['qiniu'] ?? []);
            case 'aliyun':
            case 'oss':
                return new \Plugin\storage\drivers\AliyunDriver($this->config['aliyun'] ?? []);
            case 'tencent':
            case 'cos':
                return new \Plugin\storage\drivers\TencentDriver($this->config['tencent'] ?? []);
            case 'local':
            default:
                return new \Plugin\storage\drivers\LocalDriver($this->config['local'] ?? []);
        }
    }

    /**
     * 获取当前驱动
     */
    public function getCurrentDriver()
    {
        return $this->currentDriver;
    }

    /**
     * 上传文件
     */
    public function upload($filePath, $savePath, $originalName = '', $storageType = null)
    {
        $driver = $storageType ? $this->getDriver($storageType) : $this->currentDriver;
        return $driver->upload($filePath, $savePath, $originalName);
    }

    /**
     * 删除文件
     */
    public function delete($path, $storageType = null)
    {
        $driver = $storageType ? $this->getDriver($storageType) : $this->currentDriver;
        return $driver->delete($path);
    }

    /**
     * 获取文件URL
     */
    public function getUrl($path, $storageType = null)
    {
        $driver = $storageType ? $this->getDriver($storageType) : $this->currentDriver;
        return $driver->getUrl($path);
    }

    /**
     * 检查文件是否存在
     */
    public function exists($path, $storageType = null)
    {
        $driver = $storageType ? $this->getDriver($storageType) : $this->currentDriver;
        return $driver->exists($path);
    }

    /**
     * 获取所有存储类型
     */
    public function getStorageTypes()
    {
        return [
            'local' => '本地存储',
            'qiniu' => '七牛云存储',
            'aliyun' => '阿里云OSS',
            'tencent' => '腾讯云COS'
        ];
    }

    /**
     * 检查存储类型是否启用
     */
    public function isStorageEnabled($type)
    {
        return isset($this->config[$type]['enabled']) && $this->config[$type]['enabled'] == '1';
    }

    /**
     * 保存配置
     */
    public function saveConfig($type, $configs)
    {
        if (!class_exists('Database')) {
            return false;
        }

        try {
            $db = \Database::getInstance();
            
            foreach ($configs as $key => $value) {
                $db->query(
                    "INSERT INTO __PREFIX__storage_config (storage_type, config_key, config_value) 
                     VALUES (?, ?, ?) 
                     ON DUPLICATE KEY UPDATE config_value = ?",
                    [$type, $key, $value, $value]
                );
            }
            
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 获取配置
     */
    public function getConfig($type)
    {
        return $this->config[$type] ?? [];
    }

    /**
     * 验证存储配置
     */
    public function validateStorageConfig($type)
    {
        $driver = $this->getDriver($type);
        return $driver->validateConfig();
    }

    /**
     * 检查远程存储是否可用
     * @return bool
     */
    public function isRemoteAvailable()
    {
        $currentType = $this->getCurrentStorageType();

        if ($currentType === 'local') {
            return true; // 本地存储始终可用
        }

        $driver = $this->getDriver($currentType);

        // 验证配置是否完整
        if (!$driver->validateConfig()) {
            return false;
        }

        // 尝试实际连接测试
        try {
            return $driver->testConnection();
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 获取存储使用统计
     */
    public function getStorageStats($type = null)
    {
        if (!class_exists('Database')) {
            return [];
        }

        try {
            $db = \Database::getInstance();
            
            $where = $type ? "WHERE storage_type = ?" : "";
            $params = $type ? [$type] : [];
            
            $stats = $db->fetchAll("
                SELECT 
                    storage_type,
                    COUNT(*) as file_count,
                    SUM(file_size) as total_size
                FROM __PREFIX__storage_files 
                $where
                GROUP BY storage_type
            ", $params);
            
            return $stats;
        } catch (\Exception $e) {
            return [];
        }
    }
}
