<?php
/**
 * 文件管理
**/
include("../includes/common.php");

// 检查是否为AJAX请求
$isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';

// 未登录处理：AJAX请求返回JSON，页面请求跳转
if($islogin!=1){
    if($isAjax){
        exit('{"code":-1,"msg":"请先登录"}');
    }else{
        exit("<script language='javascript'>window.location.href='./login.php';</script>");
    }
}

$title='文件管理';

if(isset($_POST['ids']) && isset($_POST['do']) && $isAjax){
	$ids = $_POST['ids'];
	$do = $_POST['do'];
	if($do=='del'){
		foreach($ids as $hash){
			$row=$DB->getRow("select * from pre_file where hash='{$hash}' limit 1");
			if($row){
				$stor->delete($row['hash']);
				$DB->exec("DELETE FROM pre_file WHERE hash='{$hash}'");
				if($row['uid']>0){
					$DB->exec("UPDATE pre_user SET storage_used=storage_used-:size WHERE uid=:uid AND storage_used>=:size", [':size'=>$row['size'], ':uid'=>$row['uid']]);
				}
			}
		}
		exit('{"code":0,"msg":"删除成功"}');
	}elseif($do=='ban'){
		$sql="";
		foreach($ids as $id){
			if($sql) $sql.=",";
			$sql.="'".$id."'";
		}
		$DB->exec("UPDATE pre_file SET block=1 WHERE hash IN ($sql)");
		exit('{"code":0,"msg":"屏蔽成功"}');
	}elseif($do=='unban'){
		$sql="";
		foreach($ids as $id){
			if($sql) $sql.=",";
			$sql.="'".$id."'";
		}
		$DB->exec("UPDATE pre_file SET block=0 WHERE hash IN ($sql)");
		exit('{"code":0,"msg":"解除屏蔽成功"}');
	}
}

if(isset($_GET['do']) && $isAjax){
	if($_GET['do']=='del'){
		$hash = $_GET['hash'];
		$row=$DB->getRow("select * from pre_file where hash='{$hash}' limit 1");
		if($row){
			$stor->delete($row['hash']);
			$DB->exec("DELETE FROM pre_file WHERE hash='{$hash}'");
			if($row['uid']>0){
				$DB->exec("UPDATE pre_user SET storage_used=storage_used-:size WHERE uid=:uid AND storage_used>=:size", [':size'=>$row['size'], ':uid'=>$row['uid']]);
			}
		}
		exit('{"code":0,"msg":"删除成功"}');
	}elseif($_GET['do']=='ban'){
		$hash = $_GET['hash'];
		$DB->exec("UPDATE pre_file SET block=1 WHERE hash='{$hash}'");
		exit('{"code":0,"msg":"屏蔽成功"}');
	}elseif($_GET['do']=='unban'){
		$hash = $_GET['hash'];
		$DB->exec("UPDATE pre_file SET block=0 WHERE hash='{$hash}'");
		exit('{"code":0,"msg":"解除屏蔽成功"}');
	}
}

include './head.php';

function display_zt($zt){
	if($zt=='0')return '<span class="status-badge normal">正常</span>';
	else return '<span class="status-badge banned">已屏蔽</span>';
}

// 获取筛选参数
$kw = isset($_GET['kw']) ? trim($_GET['kw']) : '';
$block = isset($_GET['block']) ? intval($_GET['block']) : -1;
$uid = isset($_GET['uid']) ? intval($_GET['uid']) : 0;

// 构建查询条件
$sql = "1=1";
if($kw){
	$sql .= " AND (name LIKE '%{$kw}%' OR hash='{$kw}')";
}
if($block>=0){
	$sql .= " AND block={$block}";
}
if($uid>0){
	$sql .= " AND uid={$uid}";
}

// 分页
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$pagesize = 20;
$total = $DB->getColumn("SELECT count(*) FROM pre_file WHERE {$sql}");
$pages = ceil($total / $pagesize);
$page = max(1, min($page, $pages));
$offset = ($page - 1) * $pagesize;

// 获取文件列表
$rs = $DB->query("SELECT * FROM pre_file WHERE {$sql} ORDER BY addtime DESC LIMIT {$offset},{$pagesize}");

// 获取文件类型图标
function getFileIconClass($filename){
	$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
	$imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
	$videoExts = ['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm'];
	$audioExts = ['mp3', 'wav', 'flac', 'aac', 'ogg', 'wma'];
	$docExts = ['doc', 'docx', 'pdf', 'txt', 'xls', 'xlsx', 'ppt', 'pptx'];
	$archiveExts = ['zip', 'rar', '7z', 'tar', 'gz'];
	$codeExts = ['php', 'js', 'css', 'html', 'py', 'java', 'c', 'cpp', 'json', 'xml'];
	
	if(in_array($ext, $imageExts)) return 'image';
	if(in_array($ext, $videoExts)) return 'video';
	if(in_array($ext, $audioExts)) return 'audio';
	if(in_array($ext, $docExts)) return 'document';
	if(in_array($ext, $archiveExts)) return 'archive';
	if(in_array($ext, $codeExts)) return 'code';
	return '';
}

function getFileIcon($filename){
	$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
	$imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
	$videoExts = ['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm'];
	$audioExts = ['mp3', 'wav', 'flac', 'aac', 'ogg', 'wma'];
	$docExts = ['doc', 'docx', 'pdf', 'txt', 'xls', 'xlsx', 'ppt', 'pptx'];
	$archiveExts = ['zip', 'rar', '7z', 'tar', 'gz'];
	$codeExts = ['php', 'js', 'css', 'html', 'py', 'java', 'c', 'cpp', 'json', 'xml'];
	
	if(in_array($ext, $imageExts)) return 'fa-file-image-o';
	if(in_array($ext, $videoExts)) return 'fa-file-video-o';
	if(in_array($ext, $audioExts)) return 'fa-file-audio-o';
	if(in_array($ext, $docExts)) return 'fa-file-text-o';
	if(in_array($ext, $archiveExts)) return 'fa-file-archive-o';
	if(in_array($ext, $codeExts)) return 'fa-file-code-o';
	return 'fa-file-o';
}

// 格式化文件大小
function formatBytes($bytes){
	if($bytes >= 1073741824) return round($bytes / 1073741824, 2) . ' GB';
	if($bytes >= 1048576) return round($bytes / 1048576, 2) . ' MB';
	if($bytes >= 1024) return round($bytes / 1024, 2) . ' KB';
	return $bytes . ' B';
}
?>
<div class="container">
    <!-- 页面标题 -->
    <div class="page-header-section">
        <div class="page-title">
            <div class="page-title-icon"><i class="fa fa-folder-open"></i></div>
            <h1>文件管理</h1>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon blue">
                    <i class="fa fa-files-o"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo $DB->getColumn("SELECT count(*) FROM pre_file"); ?></div>
                    <div class="stat-label">文件总数</div>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon green">
                    <i class="fa fa-check-circle"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo $DB->getColumn("SELECT count(*) FROM pre_file WHERE block=0"); ?></div>
                    <div class="stat-label">正常文件</div>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon red">
                    <i class="fa fa-ban"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo $DB->getColumn("SELECT count(*) FROM pre_file WHERE block=1"); ?></div>
                    <div class="stat-label">已屏蔽</div>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon orange">
                    <i class="fa fa-hdd-o"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo formatBytes($DB->getColumn("SELECT sum(size) FROM pre_file") ?: 0); ?></div>
                    <div class="stat-label">总存储量</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
        <form class="filter-form" method="get" action="">
            <div class="filter-group">
                <label>关键词搜索</label>
                <input type="text" class="form-control" name="kw" value="<?php echo htmlspecialchars($kw); ?>" placeholder="文件名或文件Hash">
            </div>
            <div class="filter-group">
                <label>文件状态</label>
                <select class="form-control" name="block">
                    <option value="-1">全部状态</option>
                    <option value="0" <?php echo $block===0?'selected':''; ?>>正常</option>
                    <option value="1" <?php echo $block===1?'selected':''; ?>>已屏蔽</option>
                </select>
            </div>
            <div class="filter-group">
                <label>用户ID</label>
                <input type="number" class="form-control" name="uid" value="<?php echo $uid; ?>" placeholder="输入用户ID">
            </div>
            <div class="filter-actions">
                <button type="submit" class="btn btn-primary"><i class="fa fa-search"></i> 搜索</button>
                <a href="./file.php" class="btn btn-secondary"><i class="fa fa-refresh"></i> 重置</a>
            </div>
        </form>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar-section">
        <div class="batch-actions">
            <button type="button" class="btn-batch delete" onclick="batchAction('del')"><i class="fa fa-trash"></i> 批量删除</button>
            <button type="button" class="btn-batch ban" onclick="batchAction('ban')"><i class="fa fa-ban"></i> 批量屏蔽</button>
            <button type="button" class="btn-batch unban" onclick="batchAction('unban')"><i class="fa fa-check"></i> 批量解除</button>
        </div>
        <div class="selected-count">已选择 <span id="selectedCount">0</span> 项</div>
    </div>

    <!-- 文件列表 -->
    <div class="table-section">
        <div class="table-container">
            <table class="data-table" id="fileTable">
                <thead>
                    <tr>
                        <th><input type="checkbox" id="selectAll"></th>
                        <th>ID</th>
                        <th>文件信息</th>
                        <th>文件大小</th>
                        <th>上传时间</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while($row = $rs->fetch()): ?>
                    <tr>
                        <td><input type="checkbox" name="ids[]" value="<?php echo $row['hash']; ?>"></td>
                        <td class="col-id"><?php echo $row['id']; ?></td>
                        <td class="col-name">
                            <div class="file-info">
                                <div class="file-icon <?php echo getFileIconClass($row['name']); ?>">
                                    <i class="fa <?php echo getFileIcon($row['name']); ?>"></i>
                                </div>
                                <div class="file-details">
                                    <div class="file-name" title="<?php echo htmlspecialchars($row['name']); ?>">
                                        <a href="<?php echo './view.php/'.$row['hash'].'.'.($row['type']?$row['type']:'file'); ?>" target="_blank">
                                            <?php echo htmlspecialchars($row['name']); ?>
                                        </a>
                                    </div>
                                    <div class="file-meta">
                                        <span><i class="fa fa-user"></i> UID: <?php echo $row['uid']; ?></span>
                                        <span><i class="fa fa-link"></i> <?php echo $row['hash']; ?></span>
                                    </div>
                                </div>
                            </div>
                        </td>
                        <td class="col-size"><?php echo formatBytes($row['size']); ?></td>
                        <td class="col-date">
                            <div class="primary"><?php echo $row['addtime']; ?></div>
                            <div class="secondary"><?php echo $row['ip']; ?></div>
                        </td>
                        <td class="col-status"><?php echo display_zt($row['block']); ?></td>
                        <td class="col-actions">
                            <div class="action-group">
                                <a href="<?php echo './view.php/'.$row['hash'].'.'.($row['type']?$row['type']:'file'); ?>" target="_blank" class="btn-action view" title="查看"><i class="fa fa-eye"></i></a>
                                <?php if($row['block']==0): ?>
                                <button type="button" class="btn-action disable" onclick="banFile('<?php echo $row['hash']; ?>')" title="屏蔽"><i class="fa fa-ban"></i></button>
                                <?php else: ?>
                                <button type="button" class="btn-action enable" onclick="unbanFile('<?php echo $row['hash']; ?>')" title="解除屏蔽"><i class="fa fa-check"></i></button>
                                <?php endif; ?>
                                <button type="button" class="btn-action delete" onclick="delFile('<?php echo $row['hash']; ?>')" title="删除"><i class="fa fa-trash"></i></button>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
        
        <!-- 分页 -->
        <div class="pagination-wrapper">
            <div class="pagination-info">共 <?php echo $total; ?> 条记录，第 <?php echo $page; ?>/<?php echo max(1, $pages); ?> 页</div>
            <ul class="pagination">
                <?php if($page>1): ?>
                <li><a href="?page=<?php echo $page-1; ?>&kw=<?php echo urlencode($kw); ?>&block=<?php echo $block; ?>&uid=<?php echo $uid; ?>"><i class="fa fa-angle-left"></i></a></li>
                <?php else: ?>
                <li class="disabled"><span><i class="fa fa-angle-left"></i></span></li>
                <?php endif; ?>
                
                <?php
                $start = max(1, $page-2);
                $end = min($pages, $page+2);
                for($i=$start; $i<=$end; $i++):
                ?>
                <?php if($i==$page): ?>
                <li class="active"><span><?php echo $i; ?></span></li>
                <?php else: ?>
                <li><a href="?page=<?php echo $i; ?>&kw=<?php echo urlencode($kw); ?>&block=<?php echo $block; ?>&uid=<?php echo $uid; ?>"><?php echo $i; ?></a></li>
                <?php endif; ?>
                <?php endfor; ?>
                
                <?php if($page<$pages): ?>
                <li><a href="?page=<?php echo $page+1; ?>&kw=<?php echo urlencode($kw); ?>&block=<?php echo $block; ?>&uid=<?php echo $uid; ?>"><i class="fa fa-angle-right"></i></a></li>
                <?php else: ?>
                <li class="disabled"><span><i class="fa fa-angle-right"></i></span></li>
                <?php endif; ?>
            </ul>
        </div>
    </div>
</div>

<script>
// 全选/取消全选
document.getElementById('selectAll').addEventListener('change', function() {
    var checkboxes = document.querySelectorAll('input[name="ids[]"]');
    checkboxes.forEach(function(cb) {
        cb.checked = this.checked;
    }, this);
    updateSelectedCount();
});

// 监听单个复选框变化
document.querySelectorAll('input[name="ids[]"]').forEach(function(cb) {
    cb.addEventListener('change', updateSelectedCount);
});

// 更新已选择数量
function updateSelectedCount() {
    var count = document.querySelectorAll('input[name="ids[]"]:checked').length;
    document.getElementById('selectedCount').textContent = count;
}

// 获取选中的ID
function getSelectedIds() {
    var ids = [];
    document.querySelectorAll('input[name="ids[]"]:checked').forEach(function(cb) {
        ids.push(cb.value);
    });
    return ids;
}

// 批量操作
function batchAction(action) {
    var ids = getSelectedIds();
    if(ids.length === 0) {
        alert('请选择要操作的文件');
        return;
    }

    var msg = '';
    if(action === 'del') msg = '确定要删除选中的 ' + ids.length + ' 个文件吗？';
    else if(action === 'ban') msg = '确定要屏蔽选中的 ' + ids.length + ' 个文件吗？';
    else if(action === 'unban') msg = '确定要解除屏蔽选中的 ' + ids.length + ' 个文件吗？';

    if(!confirm(msg)) return;

    $.ajax({
        url: './file.php',
        type: 'POST',
        data: {ids: ids, do: action},
        dataType: 'json',
        success: function(data) {
            if(data.code === 0) {
                alert(data.msg);
                window.location.reload();
            } else {
                alert(data.msg || '操作失败');
            }
        },
        error: function(xhr, status, error) {
            alert('请求失败：' + error);
        }
    });
}

// 删除文件
function delFile(hash) {
    if(!confirm('确定要删除该文件吗？')) return;
    $.ajax({
        url: './file.php?do=del&hash=' + encodeURIComponent(hash),
        type: 'GET',
        dataType: 'json',
        success: function(data) {
            if(data.code === 0) {
                alert(data.msg);
                window.location.reload();
            } else {
                alert(data.msg || '删除失败');
            }
        },
        error: function(xhr, status, error) {
            alert('请求失败：' + error);
        }
    });
}

// 屏蔽文件
function banFile(hash) {
    if(!confirm('确定要屏蔽该文件吗？')) return;
    $.ajax({
        url: './file.php?do=ban&hash=' + encodeURIComponent(hash),
        type: 'GET',
        dataType: 'json',
        success: function(data) {
            if(data.code === 0) {
                alert(data.msg);
                window.location.reload();
            } else {
                alert(data.msg || '屏蔽失败');
            }
        },
        error: function(xhr, status, error) {
            alert('请求失败：' + error);
        }
    });
}

// 解除屏蔽
function unbanFile(hash) {
    if(!confirm('确定要解除屏蔽该文件吗？')) return;
    $.ajax({
        url: './file.php?do=unban&hash=' + encodeURIComponent(hash),
        type: 'GET',
        dataType: 'json',
        success: function(data) {
            if(data.code === 0) {
                alert(data.msg);
                window.location.reload();
            } else {
                alert(data.msg || '解除屏蔽失败');
            }
        },
        error: function(xhr, status, error) {
            alert('请求失败：' + error);
        }
    });
}
</script>

</body>
</html>
