<?php
if (version_compare(PHP_VERSION, '7.1.0', '<')) {
    die('require PHP >= 7.1 !');
}
include("./includes/common.php");

if(isset($_GET['m']) && $_GET['m']=='mine'){
    $title = '我的文件 - ' . $conf['title'];
    $htext = '我上传的文件';
    if($islogin2){
        $sql = " uid='{$uid}'";
    }else{
        if($conf['userlogin']==1){
			$htext .= '<span class="header-note">（根据浏览器缓存记录，<a href="login.php">登录</a>后可永久保留记录）</span>';
		}else{
			$htext .= '<span class="header-note">（根据浏览器缓存记录）</span>';
		}
        $guestIds = get_guest_file_ids();
        $sessionIds = (isset($_SESSION['fileids']) && count($_SESSION['fileids'])>0) ? $_SESSION['fileids'] : [];
        $mergeIds = array_values(array_unique(array_merge($guestIds, $sessionIds)));
        
        $guest_token = get_guest_token();
        
        if(count($mergeIds) > 0){
            $ids = array_reverse($mergeIds);
            // $ids = array_splice($ids, 0, 60); // 移除只显示前60个的限制
            $ids = implode(',', $ids);
            if ($guest_token) {
                $sql = " (id IN ($ids) OR guest_token = '$guest_token')";
            } else {
                $sql = " id IN ($ids)";
            }
        } else {
            if ($guest_token) {
                $sql = " guest_token = '$guest_token'";
            } else {
                $sql = " 1=2";
            }
        }
    }
    $link = '&m=mine';
}else{
    $title = $conf['title'];
    $htext = '文件列表';
    $sql = " hide=0";
    $link = '';
}
$kw = isset($_GET['kw'])?daddslashes(trim(strip_tags($_GET['kw']))):null;
if($conf['filesearch']==1 && $kw){
    $sql.=" AND name LIKE '%{$kw}%'";
    $link .= '&kw='.$kw;
}

$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$pagesize = 20;
$offset = ($page - 1) * $pagesize;

$numrows = $DB->getColumn("SELECT COUNT(*) FROM pre_file WHERE {$sql}");
$pages = max(1, ceil($numrows / $pagesize));
if($page > $pages) $page = $pages;

$rs = $DB->query("SELECT * FROM pre_file WHERE {$sql} ORDER BY id DESC LIMIT {$offset}, {$pagesize}");

include SYSTEM_ROOT.'header.php';
?>
<link rel="stylesheet" href="assets/css/home.css?v=<?php echo VERSION?>">

<div class="container" style="margin-top: 20px;">
    <div class="page-header-card">
        <h1><i class="fa <?php echo isset($_GET['m']) ? 'fa-folder-open' : 'fa-files-o'; ?>"></i> <?php echo $htext?></h1>
        <p><?php echo isset($_GET['m']) ? '管理您上传的所有文件' : '浏览和下载共享文件' ?></p>
        <?php if($conf['filesearch']==1){?>
        <form class="search-box-modern" action="./" method="GET">
            <?php if(isset($_GET['m'])){?><input name="m" type="hidden" value="<?php echo htmlspecialchars($_GET['m'])?>"><?php }?>
            <input name="kw" type="search" placeholder="搜索文件名..." value="<?php echo $kw?>" required>
            <button type="submit"><i class="fa fa-search"></i> 搜索</button>
        </form>
        <?php }?>
    </div>

    <div class="file-list-container">
        <div class="file-list-header">
            <h3><i class="fa fa-list"></i> 文件列表</h3>
            <span class="stats">共 <strong><?php echo $numrows?></strong> 个文件</span>
        </div>

        <div class="file-table-wrapper">
        <table class="file-table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>文件名</th>
                    <th>大小</th>
                    <th>格式</th>
                    <th>上传时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
<?php
$i=1;
if($rs) while($res = $rs->fetch())
{
	$fileurl = './down.php?hash='.$res['hash'];
	$viewurl = './file.php?hash='.$res['hash'];
    
    $is_quota_exceeded = false;
    if($res['uid'] > 0){
        $userrow_owner = $DB->getRow("SELECT * FROM pre_user WHERE uid=:uid LIMIT 1", [':uid'=>$res['uid']]);
        if($userrow_owner){
            $is_owner = ($islogin2 && $res['uid'] == $uid);
            $quota_owner = check_user_quota($userrow_owner, $is_owner);
            if($quota_owner['code'] !== 0 && !$is_owner){
                $is_quota_exceeded = true;
            }
        }
    }
?>
                <tr>
                    <td><?php echo $i++?></td>
                    <td>
                        <div class="file-name-cell">
                            <div class="file-icon">
                                <i class="fa <?php echo type_to_icon($res['type'])?>"></i>
                            </div>
                            <span class="file-name" title="<?php echo htmlspecialchars($res['name'])?>"><?php echo htmlspecialchars($res['name'])?></span>
                        </div>
                    </td>
                    <td class="file-size"><?php echo size_format($res['size'])?></td>
                    <td><span class="file-type"><?php echo $res['type']?$res['type']:'file'?></span></td>
                    <td class="file-time"><?php echo $res['addtime']?></td>
                    <td>
                        <div class="file-actions">
                            <?php if($is_quota_exceeded){?>
                            <span class="btn-action btn-quota-exceeded"><i class="fa fa-exclamation-circle"></i> 已超限</span>
                            <a href="<?php echo $viewurl?>" class="btn-action btn-view"><i class="fa fa-eye"></i> 查看</a>
                            <?php }else{?>
                            <a href="<?php echo $fileurl?>" class="btn-action btn-download"><i class="fa fa-download"></i> 下载</a>
                            <a href="<?php echo $viewurl?>" class="btn-action btn-view"><i class="fa fa-eye"></i> 查看</a>
                            <?php }?>
                        </div>
                    </td>
                </tr>
<?php }
if($numrows == 0) echo '<tr><td colspan="6" class="empty-state" style="text-align:center; padding:60px 20px;"><i class="fa fa-inbox"></i><p>暂无文件</p></td></tr>';
?>
            </tbody>
        </table>
        </div>

        <?php if($numrows > 0){?>
        <div class="file-list-footer">
            <div class="stats-info">
                当前第 <strong><?php echo $page?></strong> 页，共 <strong><?php echo $pages?></strong> 页
            </div>
        </div>
        <?php }?>

        <?php if($pages > 1){?>
        <div class="pagination-wrapper">
<?php
if ($page>1) {
    echo '<a href="index.php?page=1'.$link.'"><i class="fa fa-angle-double-left"></i></a>';
    echo '<a href="index.php?page='.($page-1).$link.'"><i class="fa fa-angle-left"></i></a>';
} else {
    echo '<span class="disabled"><i class="fa fa-angle-double-left"></i></span>';
    echo '<span class="disabled"><i class="fa fa-angle-left"></i></span>';
}

$start=$page-3>1?$page-3:1;
$end=$page+3<$pages?$page+3:$pages;

for ($i=$start;$i<$page;$i++)
    echo '<a href="index.php?page='.$i.$link.'">'.$i.'</a>';
echo '<span class="current">'.$page.'</span>';
for ($i=$page+1;$i<=$end;$i++)
    echo '<a href="index.php?page='.$i.$link.'">'.$i.'</a>';

if ($page<$pages) {
    echo '<a href="index.php?page='.($page+1).$link.'"><i class="fa fa-angle-right"></i></a>';
    echo '<a href="index.php?page='.$pages.$link.'"><i class="fa fa-angle-double-right"></i></a>';
} else {
    echo '<span class="disabled"><i class="fa fa-angle-right"></i></span>';
    echo '<span class="disabled"><i class="fa fa-angle-double-right"></i></span>';
}
?>
        </div>
        <?php }?>
    </div>
</div>
<?php include SYSTEM_ROOT.'footer.php';?>
<?php if(!empty($conf['gonggao'])){?>
<!-- 公告弹窗 - 支持HTML格式 -->
<link rel="stylesheet" href="./assets/css/announcement-modal.css?v=2">
<script src="./assets/js/announcement-modal.js?v=2"></script>
<script>
(function() {
    // 初始化公告弹窗，支持HTML格式内容
    AnnouncementModal.init({
        title: '系统公告',
        // 使用htmlspecialchars_decode解码，支持HTML格式
        content: <?php echo json_encode(htmlspecialchars_decode($conf['gonggao'], ENT_QUOTES)); ?>,
        expireHours: 1
    });
})();
</script>
<?php }?>
</body>
</html>
