<?php

namespace App\Controllers;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use App\Models\Image;
use App\Utils\Response as ApiResponse;

class ImageController
{
    /**
     * 上传图片
     */
    public function upload(Request $request, Response $response)
    {
        $uploadedFiles = $request->getUploadedFiles();
        $file = $uploadedFiles['file'] ?? null;

        if (!$file || $file->getError() !== UPLOAD_ERR_OK) {
            $response->getBody()->write(ApiResponse::json(ApiResponse::fail('文件上传失败')));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(400);
        }

        $uploadDir = $_ENV['UPLOAD_DIR'] ?? '../uploads';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $originalName = $file->getClientFilename();
        $extension = pathinfo($originalName, PATHINFO_EXTENSION);
        $storedName = uniqid() . '.' . $extension;
        $filePath = $uploadDir . '/' . $storedName;

        try {
            $file->moveTo($filePath);

            $params = $request->getParsedBody();
            $markdownId = $params['markdownId'] ?? null;

            $model = new Image();
            $imageId = $model->create(
                $originalName,
                $storedName,
                $storedName,
                $file->getSize(),
                $file->getClientMediaType(),
                $markdownId
            );

            $image = $model->findById($imageId);
            $response->getBody()->write(ApiResponse::json(ApiResponse::success($image)));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
        } catch (\Exception $e) {
            $response->getBody()->write(ApiResponse::json(ApiResponse::error('上传失败: ' . $e->getMessage())));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(500);
        }
    }

    /**
     * 根据ID删除图片
     */
    public function delete(Request $request, Response $response, $args)
    {
        $id = $args['id'];
        $uploadDir = $_ENV['UPLOAD_DIR'] ?? '../uploads';

        try {
            $model = new Image();
            $image = $model->findById($id);

            if (!$image) {
                $response->getBody()->write(ApiResponse::json(ApiResponse::fail('图片不存在')));
                return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(404);
            }

            // 删除物理文件
            $filePath = $uploadDir . '/' . $image['stored_name'];
            if (file_exists($filePath)) {
                unlink($filePath);
            }

            // 删除数据库记录
            $model->delete($id);

            $response->getBody()->write(ApiResponse::json(ApiResponse::success(null, '删除成功')));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
        } catch (\Exception $e) {
            $response->getBody()->write(ApiResponse::json(ApiResponse::error('删除失败: ' . $e->getMessage())));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(500);
        }
    }

    /**
     * 在线预览图片
     */
    public function preview(Request $request, Response $response, $args)
    {
        $url = $args['url'];
        $uploadDir = $_ENV['UPLOAD_DIR'] ?? '../uploads';
        $filePath = $uploadDir . '/' . $url;

        if (empty($url) || !file_exists($filePath)) {
            $response->getBody()->write(ApiResponse::json(ApiResponse::fail('文件不存在')));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(404);
        }

        // 获取文件 MIME 类型
        $contentType = $this->getContentTypeFromFileExtension($url);

        // 读取文件内容
        $fileContent = file_get_contents($filePath);
        $fileSize = filesize($filePath);

        $response->getBody()->write($fileContent);
        return $response
            ->withHeader('Content-Type', $contentType)
            ->withHeader('Content-Length', (string)$fileSize);
    }

    /**
     * 根据URL删除图片
     */
    public function deleteByUrl(Request $request, Response $response)
    {
        $data = $request->getParsedBody();
        $url = $data['url'] ?? '';
        $uploadDir = $_ENV['UPLOAD_DIR'] ?? '../uploads';

        if (empty($url)) {
            $response->getBody()->write(ApiResponse::json(ApiResponse::fail('URL不能为空')));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(400);
        }

        try {
            // 删除物理文件
            $filePath = $uploadDir . '/' . $url;
            if (file_exists($filePath)) {
                unlink($filePath);
            }

            // 删除数据库记录
            $model = new Image();
            $model->deleteByUrl($url);

            $response->getBody()->write(ApiResponse::json(ApiResponse::success(null, '删除成功')));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
        } catch (\Exception $e) {
            $response->getBody()->write(ApiResponse::json(ApiResponse::error('删除失败: ' . $e->getMessage())));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(500);
        }
    }

    /**
     * 批量删除图片
     */
    public function batchDelete(Request $request, Response $response)
    {
        $data = $request->getParsedBody();
        $urls = $data['urls'] ?? [];
        $uploadDir = $_ENV['UPLOAD_DIR'] ?? '../uploads';

        if (empty($urls) || !is_array($urls)) {
            $response->getBody()->write(ApiResponse::json(ApiResponse::fail('URL列表不能为空')));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(400);
        }

        try {
            // 删除物理文件
            foreach ($urls as $url) {
                $filePath = $uploadDir . '/' . $url;
                if (file_exists($filePath)) {
                    unlink($filePath);
                }
            }

            // 删除数据库记录
            $model = new Image();
            $model->deleteByUrls($urls);

            $response->getBody()->write(ApiResponse::json(ApiResponse::success(null, '批量删除成功')));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
        } catch (\Exception $e) {
            $response->getBody()->write(ApiResponse::json(ApiResponse::error('批量删除失败: ' . $e->getMessage())));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(500);
        }
    }

    /**
     * 根据文件扩展名获取 MIME 类型
     */
    private function getContentTypeFromFileExtension($fileName)
    {
        if (empty($fileName) || strpos($fileName, '.') === false) {
            return 'application/octet-stream';
        }

        $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

        $mimeTypes = [
            'jpg' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
            'bmp' => 'image/bmp',
            'webp' => 'image/webp',
            'svg' => 'image/svg+xml'
        ];

        return $mimeTypes[$extension] ?? 'application/octet-stream';
    }
}
