<?php
ob_start();
/**
 * 2026企业CMS - 后台媒体库管理
 */
require_once __DIR__ . '/header.php';
check_permission('editor');
$pageTitle = '媒体库管理';

// 处理上传
$uploadMsg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload'])) {
	// CSRF 保护
	if (!csrf_validate($_POST["csrf_token"] ?? "")) {
	    die("CSRF 验证失败");
	}

    if (!empty($_FILES['file']['name'])) {
        $result = handle_upload($_FILES['file']);
        if (isset($result['success'])) {
            // 记录到数据库
            $filepath = $result['path'];
            $filename = basename($filepath);
            $filesize = $_FILES['file']['size'];
            $mimeType = $_FILES['file']['type'];
            $filetype = explode('/', $mimeType)[0] ?: 'file';
            
            db_exec(
                "INSERT INTO `media` (`filename`,`filepath`,`filesize`,`filetype`,`mime_type`,`uploaded_by`) VALUES (?,?,?,?,?,?)",
                [$filename, $filepath, $filesize, $filetype, $mimeType, $_SESSION['admin_id']]
            );
            $uploadMsg = '<div class="alert alert-success">上传成功！文件路径：' . $filepath . '</div>';
            add_log('upload', 'media', '上传文件: ' . $filename);
        } else {
            $uploadMsg = '<div class="alert alert-danger">' . ($result['error'] ?? '上传失败') . '</div>';
        }
    }
}

// 处理删除
if (isset($_GET['delete']) && $_GET['delete']) {
    $mediaId = intval($_GET['delete']);
    $media = db_query_one("SELECT * FROM `media` WHERE `id`=?", [$mediaId]);
    if ($media) {
        $filePath = __DIR__ . '/../' . ltrim($media['filepath'], '/');
        if (file_exists($filePath)) @unlink($filePath);
        db_exec("DELETE FROM `media` WHERE `id`=?", [$mediaId]);
        add_log('delete', 'media', '删除媒体文件: ' . $media['filename']);
        header('Location: /admin/media.php?msg=' . urlencode('删除成功！'));
        exit;
    }
}

$page = max(1, intval($_GET['page'] ?? 1));
$pageSize = 20;
$total = db_count('media');
$offset = ($page - 1) * $pageSize;
$mediaFiles = db_query("SELECT m.*,a.username FROM `media` m LEFT JOIN `admins` a ON m.`uploaded_by`=a.`id` ORDER BY m.`id` DESC LIMIT {$offset},{$pageSize}");

// 统计
$stats = [
    'total' => db_count('media'),
    'images' => db_count('media', "`filetype`='image'"),
    'files' => db_count('media', "`filetype`!='image'"),
    'totalSize' => db_query_one("SELECT SUM(`filesize`) as sz FROM `media`")['sz'] ?? 0,
];
?>
<div class="page-header">
    <h2>媒体库管理</h2>
</div>

<?php echo htmlspecialchars($uploadMsg, ENT_QUOTES, "UTF-8"); ?>
<?php if (isset($_GET['msg'])): ?><div class="alert alert-success"><?php echo xss_clean($_GET['msg']); ?></div><?php endif; ?>

<!-- 上传区域 -->
<div class="form-card" style="margin-bottom:20px;">
    <h3 style="margin-bottom:15px;font-size:16px;">上传文件</h3>
    <form method="post" action="" enctype="multipart/form-data">
        <?php echo csrf_input(); ?>
        <div style="display:flex;gap:15px;align-items:flex-end;">
            <div class="form-group" style="flex:1;margin-bottom:0;">
                <input type="file" name="file" required style="padding:8px;border:1px solid #ddd;border-radius:4px;width:100%;">
                <div class="hint">支持 jpg, png, gif, webp, pdf, doc, xls, zip 等格式</div>
            </div>
            <button type="submit" name="upload" class="btn btn-primary" style="padding:10px 30px;">上传</button>
        </div>
    </form>
</div>

<!-- 统计 -->
<div style="display:flex;gap:15px;margin-bottom:20px;">
    <div style="background:#fff;padding:15px 25px;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.1);">
        <div style="font-size:24px;font-weight:bold;color:#2c82e0;"><?php echo $stats['total']; ?></div>
        <div style="font-size:12px;color:#999;">总文件数</div>
    </div>
    <div style="background:#fff;padding:15px 25px;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.1);">
        <div style="font-size:24px;font-weight:bold;color:#52c41a;"><?php echo $stats['images']; ?></div>
        <div style="font-size:12px;color:#999;">图片文件</div>
    </div>
    <div style="background:#fff;padding:15px 25px;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.1);">
        <div style="font-size:24px;font-weight:bold;color:#faad14;"><?php echo round($stats['totalSize']/1024/1024,2); ?> MB</div>
        <div style="font-size:12px;color:#999;">总大小</div>
    </div>
</div>

<!-- 文件列表 -->
<div class="table-wrapper">
    <table>
        <thead><tr><th>ID</th><th>预览</th><th>文件名</th><th>类型</th><th>大小</th><th>上传者</th><th>上传时间</th><th>操作</th></tr></thead>
        <tbody>
            <?php foreach ($mediaFiles as $m): ?>
            <tr>
                <td><?php echo $m['id']; ?></td>
                <td>
                    <?php if ($m['filetype'] === 'image'): ?>
                    <img src="<?php echo xss_clean($m['filepath']); ?>" style="width:50px;height:50px;object-fit:cover;border-radius:4px;">
                    <?php else: ?>
                    <span style="font-size:24px;">📄</span>
                    <?php endif; ?>
                </td>
                <td>
                    <a href="<?php echo xss_clean($m['filepath']); ?>" target="_blank" style="font-size:13px;"><?php echo xss_clean($m['filename']); ?></a>
                    <div style="font-size:11px;color:#999;margin-top:3px;"><?php echo xss_clean($m['filepath']); ?></div>
                </td>
                <td><span class="badge <?php echo $m['filetype']=='image'?'badge-success':''; ?>"><?php echo xss_clean($m['filetype']); ?></span></td>
                <td><?php echo round($m['filesize']/1024,1); ?> KB</td>
                <td><?php echo xss_clean($m['username'] ?? '未知'); ?></td>
                <td><?php echo date('Y-m-d', strtotime($m['created_at'])); ?></td>
                <td class="actions">
                    <a href="<?php echo xss_clean($m['filepath']); ?>" target="_blank" class="btn btn-sm">查看</a>
                    <a href="javascript:void(0)" onclick="if(confirm('确定删除此文件？')){location.href='/admin/media.php?delete=<?php echo $m['id']; ?>'}" class="btn btn-sm btn-danger">删除</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php if ($total > $pageSize): $totalPage=ceil($total/$pageSize); ?>
<div class="pagination">
    <?php for ($i=1; $i<=$totalPage; $i++): ?><a href="/admin/media.php?page=<?php echo $i; ?>" <?php echo $i==$page?'class="current"':''; ?>><?php echo $i; ?></a><?php endfor; ?>
</div>
<?php endif; ?>
<?php require_once __DIR__ . '/footer.php'; ?>
