<?php
require_once 'config.php';

function ensureUploadDir($path) {
    if (!file_exists($path)) {
        mkdir($path, 0777, true);
    }
}

function getDateDir() {
    return date('Y/m/d');
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["image"])) {
    $conn = getDBConnection();
    
    try {
        $conn->begin_transaction();
        
        $sql = "INSERT INTO images (upload_time) VALUES (NOW())";
        if (!$conn->query($sql)) {
            throw new Exception("数据库插入失败: " . $conn->error);
        }
        
        $imageId = $conn->insert_id;
        $dateDir = getDateDir();
        $targetDir = "uploads/$dateDir/";
        ensureUploadDir($targetDir);
        
        $fileExt = strtolower(pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION));
        $newFileName = $imageId . '.png';
        $targetFile = $targetDir . $newFileName;

        $check = getimagesize($_FILES["image"]["tmp_name"]);
        if ($check === false) {
            throw new Exception("文件不是有效的图片");
        }

        if ($_FILES["image"]["size"] > 5000000) {
            throw new Exception("图片大小超过5MB限制");
        }

        $sourceImage = null;
        switch ($check['mime']) {
            case 'image/jpeg':
                $sourceImage = imagecreatefromjpeg($_FILES["image"]["tmp_name"]);
                break;
            case 'image/png':
                $sourceImage = imagecreatefrompng($_FILES["image"]["tmp_name"]);
                break;
            case 'image/gif':
                $sourceImage = imagecreatefromgif($_FILES["image"]["tmp_name"]);
                break;
            default:
                throw new Exception("不支持的图片格式");
        }

        if ($sourceImage === false) {
            throw new Exception("图片处理失败");
        }

        if (!imagepng($sourceImage, $targetFile)) {
            throw new Exception("图片保存失败");
        }
        
        $updateSql = "UPDATE images SET filename='$dateDir/$newFileName' WHERE id=$imageId";
        if (!$conn->query($updateSql)) {
            throw new Exception("数据库更新失败: " . $conn->error);
        }
        
        $conn->commit();
        header("Location: index.php?upload=success");
        exit;
        
    } catch (Exception $e) {
        $conn->rollback();
        header("Location: index.php?error=" . urlencode($e->getMessage()));
        exit;
    } finally {
        if (isset($sourceImage)) {
            imagedestroy($sourceImage);
        }
        $conn->close();
    }
}
?>