<?php
/**
 * 腾讯云COS存储驱动
 */

namespace Plugin\storage\drivers;

class TencentDriver extends Driver
{
    private $secretId;
    private $secretKey;
    private $bucket;
    private $region;
    private $domain;

    public function __construct($config = [])
    {
        parent::__construct($config);
        $this->secretId = $config['secret_id'] ?? '';
        $this->secretKey = $config['secret_key'] ?? '';
        $this->bucket = $config['bucket'] ?? '';
        $this->region = $config['region'] ?? 'ap-guangzhou';
        $this->domain = $config['domain'] ?? '';
    }

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

        // 检查是否安装了COS SDK
        if (!class_exists('Qcloud\Cos\Client')) {
            return ['success' => false, 'message' => '请安装腾讯云COS PHP SDK'];
        }

        try {
            $cosClient = new \Qcloud\Cos\Client([
                'region' => $this->region,
                'credentials' => [
                    'secretId' => $this->secretId,
                    'secretKey' => $this->secretKey
                ]
            ]);

            $result = $cosClient->putObject([
                'Bucket' => $this->bucket,
                'Key' => $savePath,
                'Body' => fopen($filePath, 'rb')
            ]);

            return [
                'success' => true,
                'path' => $savePath,
                'url' => $this->getUrl($savePath),
                'filename' => $savePath,
                'original_name' => $originalName,
                'file_size' => filesize($filePath)
            ];
        } catch (\Exception $e) {
            return ['success' => false, 'message' => '上传失败: ' . $e->getMessage()];
        }
    }

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

        try {
            $cosClient = new \Qcloud\Cos\Client([
                'region' => $this->region,
                'credentials' => [
                    'secretId' => $this->secretId,
                    'secretKey' => $this->secretKey
                ]
            ]);

            $cosClient->deleteObject([
                'Bucket' => $this->bucket,
                'Key' => $path
            ]);
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

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

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

        try {
            $cosClient = new \Qcloud\Cos\Client([
                'region' => $this->region,
                'credentials' => [
                    'secretId' => $this->secretId,
                    'secretKey' => $this->secretKey
                ]
            ]);

            $result = $cosClient->headObject([
                'Bucket' => $this->bucket,
                'Key' => $path
            ]);
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

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

    /**
     * 获取配置表单
     */
    public function getConfigForm()
    {
        return [
            'title' => '腾讯云COS存储',
            'fields' => [
                [
                    'name' => 'tencent_secret_id',
                    'label' => 'SecretId',
                    'type' => 'text',
                    'placeholder' => '请输入腾讯云SecretId',
                    'required' => true
                ],
                [
                    'name' => 'tencent_secret_key',
                    'label' => 'SecretKey',
                    'type' => 'password',
                    'placeholder' => '请输入腾讯云SecretKey',
                    'required' => true
                ],
                [
                    'name' => 'tencent_bucket',
                    'label' => 'Bucket名称',
                    'type' => 'text',
                    'placeholder' => '请输入COS Bucket名称',
                    'required' => true
                ],
                [
                    'name' => 'tencent_region',
                    'label' => '存储区域',
                    'type' => 'select',
                    'options' => [
                        'ap-beijing' => '北京',
                        'ap-shanghai' => '上海',
                        'ap-guangzhou' => '广州',
                        'ap-chengdu' => '成都',
                        'ap-singapore' => '新加坡',
                        'ap-hongkong' => '香港'
                    ],
                    'default' => 'ap-guangzhou'
                ],
                [
                    'name' => 'tencent_domain',
                    'label' => '访问域名',
                    'type' => 'text',
                    'placeholder' => '如: https://cdn.example.com',
                    'required' => true
                ]
            ]
        ];
    }

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

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

        if (!class_exists('Qcloud\Cos\Client')) {
            return false;
        }

        try {
            $cosClient = new \Qcloud\Cos\Client([
                'region' => $this->region,
                'credentials' => [
                    'secretId' => $this->secretId,
                    'secretKey' => $this->secretKey
                ]
            ]);
            $cosClient->headBucket(['Bucket' => $this->bucket]);
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
}
