<?php
/**
 * 七牛云存储驱动
 */

namespace Plugin\storage\drivers;

class QiniuDriver extends Driver
{
    private $accessKey;
    private $secretKey;
    private $bucket;
    private $domain;
    private $region;

    public function __construct($config = [])
    {
        parent::__construct($config);
        $this->accessKey = $config['access_key'] ?? '';
        $this->secretKey = $config['secret_key'] ?? '';
        $this->bucket = $config['bucket'] ?? '';
        $this->domain = $config['domain'] ?? '';
        $this->region = $config['region'] ?? 'z0';
    }

    /**
     * 上传文件到七牛云
     */
    public function upload($filePath, $savePath, $originalName = '')
    {
        if (!$this->validateConfig()) {
            return ['success' => false, 'message' => '七牛云配置不完整'];
        }

        // 检查是否安装了七牛SDK
        if (!class_exists('Qiniu\Config')) {
            return ['success' => false, 'message' => '请安装七牛云PHP SDK'];
        }

        $auth = new \Qiniu\Auth($this->accessKey, $this->secretKey);
        $token = $auth->uploadToken($this->bucket);
        
        $uploadManager = new \Qiniu\Storage\UploadManager();
        
        $result = $uploadManager->putFile($token, $savePath, $filePath);
        
        if ($result && isset($result[0]['key'])) {
            return [
                'success' => true,
                'path' => $savePath,
                'url' => $this->getUrl($savePath),
                'filename' => $result[0]['key'],
                'original_name' => $originalName,
                'file_size' => filesize($filePath)
            ];
        }

        return ['success' => false, 'message' => '上传失败'];
    }

    /**
     * 删除七牛云文件
     */
    public function delete($path)
    {
        if (!$this->validateConfig()) {
            return false;
        }

        $auth = new \Qiniu\Auth($this->accessKey, $this->secretKey);
        $bucketManager = new \Qiniu\Storage\BucketManager($auth);
        
        $result = $bucketManager->delete($this->bucket, $path);
        return $result === null;
    }

    /**
     * 获取七牛云文件URL
     */
    public function getUrl($path)
    {
        $domain = rtrim($this->domain, '/');
        return $domain . '/' . ltrim($path, '/');
    }

    /**
     * 检查文件是否存在
     */
    public function exists($path)
    {
        if (!$this->validateConfig()) {
            return false;
        }

        $auth = new \Qiniu\Auth($this->accessKey, $this->secretKey);
        $bucketManager = new \Qiniu\Storage\BucketManager($auth);
        
        list($_, $err) = $bucketManager->stat($this->bucket, $path);
        return $err === null;
    }

    /**
     * 获取驱动名称
     */
    public function getName()
    {
        return 'qiniu';
    }

    /**
     * 获取配置表单
     */
    public function getConfigForm()
    {
        return [
            'title' => '七牛云存储',
            'fields' => [
                [
                    'name' => 'qiniu_access_key',
                    'label' => 'AccessKey',
                    'type' => 'text',
                    'placeholder' => '请输入七牛云AccessKey',
                    'required' => true
                ],
                [
                    'name' => 'qiniu_secret_key',
                    'label' => 'SecretKey',
                    'type' => 'password',
                    'placeholder' => '请输入七牛云SecretKey',
                    'required' => true
                ],
                [
                    'name' => 'qiniu_bucket',
                    'label' => '存储空间名称',
                    'type' => 'text',
                    'placeholder' => '请输入七牛云存储空间名称',
                    'required' => true
                ],
                [
                    'name' => 'qiniu_domain',
                    'label' => '访问域名',
                    'type' => 'text',
                    'placeholder' => '如: https://cdn.example.com',
                    'required' => true
                ],
                [
                    'name' => 'qiniu_region',
                    'label' => '存储区域',
                    'type' => 'select',
                    'options' => [
                        'z0' => '华东',
                        'z1' => '华北',
                        'z2' => '华南',
                        'na0' => '北美'
                    ],
                    'default' => 'z0'
                ]
            ]
        ];
    }

    /**
     * 验证配置
     */
    public function validateConfig()
    {
        return !empty($this->accessKey) && !empty($this->secretKey) && 
               !empty($this->bucket) && !empty($this->domain);
    }

    /**
     * 测试连接
     */
    public function testConnection()
    {
        if (!$this->validateConfig()) {
            return false;
        }

        if (!class_exists('Qiniu\Config')) {
            return false;
        }

        try {
            $auth = new \Qiniu\Auth($this->accessKey, $this->secretKey);
            $bucketManager = new \Qiniu\Storage\BucketManager($auth);
            list(, $err) = $bucketManager->buckets();
            return $err === null;
        } catch (\Exception $e) {
            return false;
        }
    }
}
