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

function display_zt($zt){
	if(intval($zt)==1)return '<span class="status-badge active">正常</span>';
	else return '<span class="status-badge banned">封禁</span>';
}

// 处理批量操作
if(isset($_POST['ids']) && isset($_POST['do'])){
	$ids = $_POST['ids'];
	$do = $_POST['do'];
	if($do=='del'){
		$sql="";
		foreach($ids as $id){
			if($sql) $sql.=",";
			$sql.="'".$id."'";
		}
		$result = $DB->exec("DELETE FROM pre_user WHERE uid IN ($sql)");
		if($result !== false) exit('{"code":0,"msg":"删除成功"}');
		else exit('{"code":-1,"msg":"删除失败"}');
	}elseif($do=='ban'){
		$sql="";
		foreach($ids as $id){
			if($sql) $sql.=",";
			$sql.="'".$id."'";
		}
		$result = $DB->exec("UPDATE pre_user SET enable=0 WHERE uid IN ($sql)");
		if($result !== false) exit('{"code":0,"msg":"封禁成功"}');
		else exit('{"code":-1,"msg":"封禁失败"}');
	}elseif($do=='unban'){
		$sql="";
		foreach($ids as $id){
			if($sql) $sql.=",";
			$sql.="'".$id."'";
		}
		$result = $DB->exec("UPDATE pre_user SET enable=1 WHERE uid IN ($sql)");
		if($result !== false) exit('{"code":0,"msg":"解封成功"}');
		else exit('{"code":-1,"msg":"解封失败"}');
	}
}

// 处理单个操作
if(isset($_GET['do'])){
	if($_GET['do']=='del'){
		$uid = $_GET['uid'];
		$result = $DB->exec("DELETE FROM pre_user WHERE uid='{$uid}'");
		if($result !== false) exit('{"code":0,"msg":"删除成功"}');
		else exit('{"code":-1,"msg":"删除失败"}');
	}elseif($_GET['do']=='ban'){
		$uid = $_GET['uid'];
		$result = $DB->exec("UPDATE pre_user SET enable=0 WHERE uid='{$uid}'");
		if($result !== false) exit('{"code":0,"msg":"封禁成功"}');
		else exit('{"code":-1,"msg":"封禁失败"}');
	}elseif($_GET['do']=='unban'){
		$uid = $_GET['uid'];
		$result = $DB->exec("UPDATE pre_user SET enable=1 WHERE uid='{$uid}'");
		if($result !== false) exit('{"code":0,"msg":"解封成功"}');
		else exit('{"code":-1,"msg":"解封失败"}');
	}
}

$title='用户管理';
include './head.php';

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

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

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

// 获取用户列表
$rs = $DB->query("SELECT * FROM pre_user WHERE {$sql} ORDER BY uid DESC LIMIT {$offset},{$pagesize}");
?>
<div class="container">
    <!-- 页面标题 -->
    <div class="page-header-section">
        <div class="page-title">
            <div class="page-title-icon"><i class="fa fa-users"></i></div>
            <h1>用户管理</h1>
        </div>
        <div class="page-actions">
            <a href="user_edit.php?action=add" class="btn btn-success"><i class="fa fa-plus"></i> 添加用户</a>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon blue">
                    <i class="fa fa-users"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo $DB->getColumn("SELECT count(*) FROM pre_user"); ?></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-user-check"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo $DB->getColumn("SELECT count(*) FROM pre_user WHERE enable=1"); ?></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-user-times"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo $DB->getColumn("SELECT count(*) FROM pre_user WHERE enable=0"); ?></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-calendar-check-o"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo $DB->getColumn("SELECT count(*) FROM pre_user WHERE addtime>'".date("Y-m-d")."'"); ?></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="用户ID/用户名/昵称">
            </div>
            <div class="filter-group">
                <label>用户状态</label>
                <select class="form-control" name="enable">
                    <option value="-1">全部状态</option>
                    <option value="1" <?php echo $enable===1?'selected':''; ?>>正常</option>
                    <option value="0" <?php echo $enable===0?'selected':''; ?>>封禁</option>
                </select>
            </div>
            <div class="filter-actions">
                <button type="submit" class="btn btn-primary"><i class="fa fa-search"></i> 搜索</button>
                <a href="./user.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="userTable">
                <thead>
                    <tr>
                        <th><input type="checkbox" id="selectAll"></th>
                        <th>UID</th>
                        <th>用户信息</th>
                        <th>会员等级</th>
                        <th>注册时间</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while($row = $rs->fetch()): 
                    $level = intval($row['level']);
                    ?>
                    <tr>
                        <td><input type="checkbox" name="ids[]" value="<?php echo $row['uid']; ?>"></td>
                        <td class="col-id"><?php echo $row['uid']; ?></td>
                        <td class="col-name">
                            <div class="user-info">
                                <div class="user-avatar">
                                    <?php echo strtoupper(substr($row['nickname']?:$row['username'], 0, 1)); ?>
                                </div>
                                <div class="user-details">
                                    <div class="user-name"><?php echo htmlspecialchars($row['nickname']?:$row['username']); ?></div>
                                    <div class="user-login"><i class="fa fa-user-o"></i> <?php echo htmlspecialchars($row['username']); ?></div>
                                </div>
                            </div>
                        </td>
                        <td>
                            <?php if($level == 1): ?>
                            <span class="type-badge vip">VIP会员</span>
                            <?php else: ?>
                            <span class="type-badge normal">普通用户</span>
                            <?php endif; ?>
                        </td>
                        <td class="col-date">
                            <div class="primary"><?php echo $row['addtime']; ?></div>
                            <div class="secondary"><?php echo $row['regip']; ?></div>
                        </td>
                        <td class="col-status"><?php echo display_zt(intval($row['enable'])); ?></td>
                        <td class="col-actions">
                            <div class="action-group">
                                <a href="user_edit.php?action=edit&uid=<?php echo $row['uid']; ?>" class="btn-action edit" title="编辑"><i class="fa fa-pencil"></i></a>
                                <a href="file.php?uid=<?php echo $row['uid']; ?>" class="btn-action view" title="查看文件"><i class="fa fa-folder-open"></i></a>
                                <?php if(intval($row['enable'])==1): ?>
                                <button type="button" class="btn-action disable" onclick="banUser('<?php echo $row['uid']; ?>')" title="封禁"><i class="fa fa-ban"></i></button>
                                <?php else: ?>
                                <button type="button" class="btn-action enable" onclick="unbanUser('<?php echo $row['uid']; ?>')" title="解封"><i class="fa fa-check"></i></button>
                                <?php endif; ?>
                                <button type="button" class="btn-action delete" onclick="delUser('<?php echo $row['uid']; ?>')" 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); ?>&enable=<?php echo $enable; ?>"><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); ?>&enable=<?php echo $enable; ?>"><?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); ?>&enable=<?php echo $enable; ?>"><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: './user.php',
        type: 'POST',
        data: {ids: ids, do: action},
        dataType: 'json',
        success: function(data) {
            if(data.code === 0) {
                alert(data.msg);
                location.reload();
            } else {
                alert('操作失败：' + (data.msg || '未知错误'));
            }
        },
        error: function(xhr, status, error) {
            alert('请求失败：' + error);
        }
    });
}

// 删除用户
function delUser(uid) {
    if(!confirm('确定要删除该用户吗？此操作不可恢复！')) return;
    $.ajax({
        url: './user.php?do=del&uid=' + uid,
        type: 'GET',
        dataType: 'json',
        success: function(data) {
            if(data.code === 0) {
                alert(data.msg);
                location.reload();
            } else {
                alert('删除失败：' + (data.msg || '未知错误'));
            }
        },
        error: function(xhr, status, error) {
            alert('请求失败：' + error);
        }
    });
}

// 封禁用户
function banUser(uid) {
    if(!confirm('确定要封禁该用户吗？')) return;
    $.ajax({
        url: './user.php?do=ban&uid=' + uid,
        type: 'GET',
        dataType: 'json',
        success: function(data) {
            if(data.code === 0) {
                alert(data.msg);
                location.reload();
            } else {
                alert('封禁失败：' + (data.msg || '未知错误'));
            }
        },
        error: function(xhr, status, error) {
            alert('请求失败：' + error);
        }
    });
}

// 解封用户
function unbanUser(uid) {
    if(!confirm('确定要解封该用户吗？')) return;
    $.ajax({
        url: './user.php?do=unban&uid=' + uid,
        type: 'GET',
        dataType: 'json',
        success: function(data) {
            if(data.code === 0) {
                alert(data.msg);
                location.reload();
            } else {
                alert('解封失败：' + (data.msg || '未知错误'));
            }
        },
        error: function(xhr, status, error) {
            alert('请求失败：' + error);
        }
    });
}
</script>

</body>
</html>
