<?php

require_once dirname(__DIR__, 2) . '/core/lib/media_library.php';
require_once dirname(__DIR__, 2) . '/core/lib/system_health.php';

$rootPath = dirname(__DIR__, 2);
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['media_action'] ?? '') === 'delete') {
    requireAdminCsrfToken(true);
    while (ob_get_level() > 0) { ob_end_clean(); }
    header('Content-Type: application/json; charset=utf-8');
    $url = trim((string) ($_POST['url'] ?? ''));
    $result = cmsDeleteUnusedMedia($db, $rootPath, $url);
    if ($result['success']) { addLog('永久删除', '媒体资源', '删除未使用资源 ' . cmsNormalizeMediaUrl($url)); }
    echo json_encode(['code'=>$result['success'] ? 200 : 409,'msg'=>$result['message'],'references'=>$result['references'] ?? []], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit;
}

$files = cmsScanMediaFiles($rootPath);
$references = cmsCollectMediaReferences($db, $rootPath);
$keyword = trim((string) ($_GET['keyword'] ?? ''));
$type = trim((string) ($_GET['type'] ?? ''));
$usage = trim((string) ($_GET['usage'] ?? ''));
$dateFrom = trim((string) ($_GET['date_from'] ?? ''));
$dateTo = trim((string) ($_GET['date_to'] ?? ''));
$type = in_array($type, ['image','video','audio','document','archive','other'], true) ? $type : '';
$usage = in_array($usage, ['used','unused'], true) ? $usage : '';
$items = [];
foreach ($files as $url => $file) {
    $file['references'] = $references[$url] ?? [];
    $file['used'] = !empty($file['references']);
    if ($keyword !== '' && stripos($file['name'].' '.$url, $keyword) === false) { continue; }
    if ($type !== '' && $file['type'] !== $type) { continue; }
    if ($usage === 'used' && !$file['used']) { continue; }
    if ($usage === 'unused' && $file['used']) { continue; }
    if ($dateFrom !== '' && strtotime($dateFrom) !== false && $file['modified_at'] < strtotime($dateFrom)) { continue; }
    if ($dateTo !== '' && strtotime($dateTo) !== false && $file['modified_at'] > strtotime($dateTo.' 23:59:59')) { continue; }
    $items[] = $file;
}
usort($items, function($a,$b){ return $b['modified_at'] <=> $a['modified_at']; });
$page=max(1,intval($_GET['page'] ?? 1)); $pageSize=24; $total=count($items); $totalPages=max(1,intval(ceil($total/$pageSize))); $items=array_slice($items,($page-1)*$pageSize,$pageSize);
$totalSize=0;$imageCount=0;$unusedCount=0;foreach($files as $url=>$file){$totalSize+=$file['size'];if($file['type']==='image')$imageCount++;if(empty($references[$url]))$unusedCount++;}
$query=$_GET;unset($query['page']);$queryString=http_build_query($query);
$typeLabels=['image'=>'图片','video'=>'视频','audio'=>'音频','document'=>'文档','archive'=>'压缩包','other'=>'其他'];
?>
<div class="page-container fade-in media-page">
<div class="page-header"><div class="page-title"><div class="page-icon"><i class="fa fa-picture-o"></i></div><div><h1>媒体资源</h1><p>统一查看上传文件、引用关系与未使用资源</p></div></div><div class="page-actions"><a href="?act=media" class="btn btn-secondary"><i class="fa fa-refresh"></i> 重新扫描</a></div></div>
<div class="media-summary"><div><small>资源总数</small><strong><?php echo count($files); ?></strong><span>个文件</span></div><div><small>图片资源</small><strong><?php echo $imageCount; ?></strong><span>个文件</span></div><div><small>未使用资源</small><strong><?php echo $unusedCount; ?></strong><span>删除前会再次检查</span></div><div><small>占用空间</small><strong><?php echo cmsFormatBytes($totalSize); ?></strong><span>上传目录合计</span></div></div>
<form class="media-filter" method="get"><input type="hidden" name="act" value="media"><input name="keyword" value="<?php echo htmlspecialchars($keyword); ?>" placeholder="搜索文件名或路径"><select name="type"><option value="">全部类型</option><?php foreach($typeLabels as $k=>$v): ?><option value="<?php echo $k; ?>" <?php echo $type===$k?'selected':''; ?>><?php echo $v; ?></option><?php endforeach; ?></select><select name="usage"><option value="">全部引用状态</option><option value="used" <?php echo $usage==='used'?'selected':''; ?>>使用中</option><option value="unused" <?php echo $usage==='unused'?'selected':''; ?>>未使用</option></select><input type="date" name="date_from" value="<?php echo htmlspecialchars($dateFrom); ?>"><input type="date" name="date_to" value="<?php echo htmlspecialchars($dateTo); ?>"><button class="btn btn-primary">筛选</button><a class="btn btn-secondary" href="?act=media">重置</a></form>
<div class="media-note"><i class="fa fa-info-circle"></i><span>“未使用”表示数据库、装修数据和模板文件中未发现引用。系统隐藏文件不会显示；删除操作不可恢复。</span></div>
<?php if(!$items): ?><div class="content-card media-empty">没有符合条件的资源</div><?php else: ?><div class="media-grid"><?php foreach($items as $item): ?><article class="media-card"><div class="media-preview"><?php if($item['type']==='image'): ?><img src="<?php echo htmlspecialchars($item['url']); ?>" alt="" loading="lazy"><?php else: ?><div class="media-file-icon"><i class="fa <?php echo $item['type']==='video'?'fa-file-video-o':($item['type']==='audio'?'fa-file-audio-o':($item['type']==='archive'?'fa-file-archive-o':'fa-file-text-o')); ?>"></i><span><?php echo strtoupper(htmlspecialchars($item['extension'] ?: 'FILE')); ?></span></div><?php endif; ?><span class="media-type"><?php echo $typeLabels[$item['type']]; ?></span></div><div class="media-body"><strong title="<?php echo htmlspecialchars($item['name']); ?>"><?php echo htmlspecialchars($item['name']); ?></strong><code title="<?php echo htmlspecialchars($item['url']); ?>"><?php echo htmlspecialchars($item['url']); ?></code><div class="media-meta"><span><?php echo cmsFormatBytes($item['size']); ?></span><span><?php echo date('Y-m-d H:i',$item['modified_at']); ?></span></div><div class="media-usage"><span class="is-<?php echo $item['used']?'used':'unused'; ?>"><?php echo $item['used']?'使用中 · '.count($item['references']).' 处':'未使用'; ?></span><?php if($item['used']): ?><button type="button" class="media-ref-btn" data-refs='<?php echo htmlspecialchars(json_encode($item['references'],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),ENT_QUOTES,'UTF-8'); ?>'>查看引用</button><?php else: ?><button type="button" class="media-delete" data-url="<?php echo htmlspecialchars($item['url']); ?>">安全删除</button><?php endif; ?></div></div></article><?php endforeach; ?></div><?php endif; ?>
<?php if($totalPages>1): ?><div class="pagination media-pagination"><?php for($i=max(1,$page-2);$i<=min($totalPages,$page+2);$i++): ?><a class="<?php echo $i===$page?'active':''; ?>" href="?<?php echo htmlspecialchars($queryString.'&page='.$i); ?>"><?php echo $i; ?></a><?php endfor; ?></div><?php endif; ?>
</div>
<div class="media-modal" id="mediaModal" hidden><div class="media-dialog"><div><h2>资源引用</h2><button type="button" id="mediaClose">×</button></div><ul id="mediaRefs"></ul></div></div>
<style>
.media-page{max-width:1500px}.media-summary{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:16px}.media-summary>div{padding:16px 18px;border:1px solid #e2e8f0;border-radius:14px;background:#fff}.media-summary small,.media-summary span{display:block;color:#94a3b8;font-size:11px}.media-summary strong{display:inline-block;margin:5px 7px 2px 0;color:#1e293b;font-size:23px}.media-filter{display:flex;gap:10px;flex-wrap:wrap;padding:14px;margin-bottom:12px;border:1px solid #e2e8f0;border-radius:14px;background:#fff}.media-filter input,.media-filter select{height:38px;padding:0 11px;border:1px solid #dbe3ee;border-radius:9px;background:#fff}.media-filter input[name=keyword]{flex:1;min-width:220px}.media-note{display:flex;gap:9px;align-items:center;margin-bottom:16px;padding:10px 13px;border-radius:10px;background:#eff6ff;color:#475569;font-size:11px}.media-note i{color:#2563eb}.media-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px}.media-card{overflow:hidden;border:1px solid #dfe6ef;border-radius:15px;background:#fff;box-shadow:0 7px 20px rgba(15,23,42,.04);transition:.18s ease}.media-card:hover{transform:translateY(-2px);box-shadow:0 12px 28px rgba(15,23,42,.08)}.media-preview{position:relative;height:160px;background:#f1f5f9}.media-preview img{width:100%;height:100%;object-fit:cover}.media-type{position:absolute;top:10px;left:10px;padding:4px 7px;border-radius:7px;background:rgba(15,23,42,.72);color:#fff;font-size:10px}.media-file-icon{height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;color:#64748b}.media-file-icon i{font-size:38px}.media-file-icon span{font-size:11px;font-weight:800}.media-body{padding:14px}.media-body>strong,.media-body>code{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.media-body>strong{color:#29364d;font-size:13px}.media-body>code{margin-top:5px;color:#94a3b8;font-size:10px}.media-meta,.media-usage{display:flex;justify-content:space-between;align-items:center;margin-top:12px}.media-meta{color:#94a3b8;font-size:10px}.media-usage{padding-top:11px;border-top:1px solid #eef2f7}.media-usage>span{font-size:11px;font-weight:800}.media-usage .is-used{color:#047857}.media-usage .is-unused{color:#b45309}.media-ref-btn,.media-delete{padding:0;border:0;background:none;color:#2563eb;font-size:11px;cursor:pointer}.media-delete{color:#dc2626}.media-empty{padding:60px;text-align:center;color:#94a3b8}.media-pagination{margin-top:18px}.media-modal{position:fixed;inset:0;z-index:9999;background:rgba(15,23,42,.42);backdrop-filter:blur(3px)}.media-modal:not([hidden]){display:flex;align-items:center;justify-content:center;padding:24px}.media-dialog{width:min(560px,100%);max-height:80vh;overflow:auto;padding:20px;border-radius:17px;background:#fff}.media-dialog>div{display:flex;justify-content:space-between;align-items:center}.media-dialog h2{margin:0}.media-dialog button{border:0;background:none;font-size:27px;color:#64748b}.media-dialog ul{list-style:none;padding:0;margin:15px 0 0}.media-dialog li{padding:11px 4px;border-top:1px solid #edf2f7;color:#475569;font-size:12px}.media-dialog li strong{color:#1e293b}@media(max-width:1200px){.media-grid{grid-template-columns:repeat(3,1fr)}}@media(max-width:900px){.media-summary,.media-grid{grid-template-columns:repeat(2,1fr)}}@media(max-width:600px){.media-summary,.media-grid{grid-template-columns:1fr}}
</style>
<script>(function(){var modal=document.getElementById('mediaModal'),list=document.getElementById('mediaRefs');document.querySelectorAll('.media-ref-btn').forEach(function(btn){btn.onclick=function(){var refs=JSON.parse(this.getAttribute('data-refs'));list.innerHTML='';refs.forEach(function(ref){var li=document.createElement('li');li.innerHTML='<strong></strong><span></span>';li.querySelector('strong').textContent=ref.source+' #'+(ref.id||'-');li.querySelector('span').textContent=' · '+ref.field;list.appendChild(li);});modal.hidden=false;};});function close(){modal.hidden=true;}document.getElementById('mediaClose').onclick=close;modal.onclick=function(e){if(e.target===modal)close();};document.querySelectorAll('.media-delete').forEach(function(btn){btn.onclick=function(){var url=this.getAttribute('data-url');if(!confirm('确定永久删除这个未使用资源？此操作无法恢复。'))return;fetch('?act=media',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'media_action=delete&url='+encodeURIComponent(url)+'&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>'}).then(function(r){return r.json();}).then(function(d){alert(d.msg);if(d.code===200)location.reload();});};});})();</script>
