<?php
require_once dirname(__DIR__) . '/config.php';

header('Content-Type: application/json');

// 检查登录和权限
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

$user = currentUser();
if ($user['role'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => '权限不足']);
    exit;
}

$title = trim($_POST['title'] ?? '');
$description = trim($_POST['description'] ?? '');
$version = trim($_POST['version'] ?? '');
$sort = intval($_POST['sort'] ?? 0);
$status = intval($_POST['status'] ?? 1);

if (empty($title)) {
    echo json_encode(['success' => false, 'message' => '标题不能为空']);
    exit;
}

if (!isset($_FILES['file']) || $_FILES['file']['error'] != 0) {
    $error_msg = isset($_FILES['file']) ? '上传错误码：' . $_FILES['file']['error'] : '请选择文件';
    echo json_encode(['success' => false, 'message' => $error_msg]);
    exit;
}

$file = $_FILES['file'];
$max_size = 100 * 1024 * 1024; // 100MB

if ($file['size'] > $max_size) {
    echo json_encode(['success' => false, 'message' => '文件大小不能超过100MB']);
    exit;
}

// 创建上传目录
$upload_dir = dirname(__DIR__) . '/assets/uploads/downloads/';
if (!is_dir($upload_dir)) {
    if (!mkdir($upload_dir, 0755, true)) {
        echo json_encode(['success' => false, 'message' => '无法创建上传目录，请检查权限']);
        exit;
    }
}

// 生成文件名
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = date('YmdHis') . '_' . uniqid() . '.' . $ext;
$file_path = $upload_dir . $filename;

// 移动文件
if (move_uploaded_file($file['tmp_name'], $file_path)) {
    // 计算文件大小
    $file_size = formatFileSize($file['size']);
    $file_url = '/assets/uploads/downloads/' . $filename;
    
    // 转义
    $title = $db->escape($title);
    $description = $db->escape($description);
    $version = $db->escape($version);
    $file_name = $db->escape($file['name']);
    $file_url_safe = $db->escape($file_url);
    
    $result = $db->query("INSERT INTO downloads (title, description, file_name, file_path, file_size, version, sort, status) 
                VALUES ('$title', '$description', '$file_name', '$file_url_safe', '$file_size', '$version', $sort, $status)");
    
    if ($result) {
        echo json_encode(['success' => true, 'message' => '上传成功']);
    } else {
        echo json_encode(['success' => false, 'message' => '数据库保存失败']);
        @unlink($file_path);
    }
} else {
    echo json_encode(['success' => false, 'message' => '文件移动失败，请检查目录权限']);
}
exit;

function formatFileSize($bytes) {
    if ($bytes >= 1073741824) {
        return round($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return round($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return round($bytes / 1024, 2) . ' KB';
    } else {
        return $bytes . ' B';
    }
}
?>