<?php
/**
 * 本地存储驱动
 */

namespace Plugin\storage\drivers;

class LocalDriver extends Driver
{
    private $uploadPath;
    private $baseUrl;

    public function __construct($config = [])
    {
        parent::__construct($config);
        $this->uploadPath = defined('UPLOAD_PATH') ? UPLOAD_PATH : (\ROOT_PATH . 'uploads/');
        $this->baseUrl = defined('SITE_URL') ? rtrim(SITE_URL, '/') : '';
    }

    /**
     * 上传文件到本地
     */
    public function upload($filePath, $savePath, $originalName = '')
    {
        $dir = dirname($this->uploadPath . $savePath);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

        $targetPath = $this->uploadPath . $savePath;
        
        if (!copy($filePath, $targetPath) && !move_uploaded_file($filePath, $targetPath)) {
            return ['success' => false, 'message' => '文件保存失败'];
        }

        chmod($targetPath, 0644);

        return [
            'success' => true,
            'path' => $savePath,
            'url' => $this->getUrl($savePath),
            'filename' => basename($savePath),
            'original_name' => $originalName,
            'file_size' => filesize($targetPath)
        ];
    }

    /**
     * 删除本地文件
     */
    public function delete($path)
    {
        $filePath = $this->uploadPath . $path;
        if (file_exists($filePath)) {
            return unlink($filePath);
        }
        return true;
    }

    /**
     * 获取本地文件URL
     */
    public function getUrl($path)
    {
        return $this->baseUrl . '/uploads/' . ltrim($path, '/');
    }

    /**
     * 检查文件是否存在
     */
    public function exists($path)
    {
        return file_exists($this->uploadPath . $path);
    }

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

    /**
     * 获取配置表单
     */
    public function getConfigForm()
    {
        return [
            'title' => '本地存储',
            'fields' => [
                [
                    'name' => 'local_base_url',
                    'label' => '访问域名',
                    'type' => 'text',
                    'placeholder' => '如: https://cdn.example.com，留空使用默认',
                    'default' => ''
                ]
            ]
        ];
    }

    /**
     * 验证配置
     */
    public function validateConfig()
    {
        return true;
    }

    /**
     * 测试连接 - 本地存储检查上传目录是否可写
     */
    public function testConnection()
    {
        return is_dir($this->uploadPath) && is_writable($this->uploadPath);
    }
}
