<?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;
}

$id = intval($_POST['id'] ?? 0);

if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => '参数错误']);
    exit;
}

// 获取文件路径并删除文件
$download = $db->fetchOne("SELECT file_path FROM downloads WHERE id = $id");
if ($download && $download['file_path']) {
    $site_root = dirname(__DIR__);
    $file_path = $site_root . $download['file_path'];
    if (file_exists($file_path)) {
        @unlink($file_path);
    }
}

$db->query("DELETE FROM downloads WHERE id = $id");
echo json_encode(['success' => true]);
exit;
?>