<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */
$action = isset($_GET['action']) ? $_GET['action'] : 'list';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'save') {
        requireAdminCsrfToken();
        $id = intval($_POST['id']);
        $roleId = intval($_POST['role_id'] ?? -1);
        $enabled = isset($_POST['is_enabled']) ? 1 : 0;
        if ($roleId !== 0 && !$db->fetch("SELECT id FROM {$db->table('role')} WHERE id = ? LIMIT 1", [$roleId])) {
            echo '<script>alert("请选择有效角色");history.back();</script>';
            exit;
        }
        if ($id === intval($_SESSION['admin_id']) && ($roleId !== 0 || !$enabled)) {
            echo '<script>alert("不能降级或禁用当前登录的超级管理员");history.back();</script>';
            exit;
        }
        $data = [
            'username' => trim($_POST['username']),
            'realname' => trim($_POST['realname']),
            'pen_name' => trim($_POST['pen_name']),
            'phone' => trim($_POST['mobile']),
            'email' => trim($_POST['email']),
            'role_id' => $roleId,
            'is_enabled' => $enabled,
            'update_time' => time()
        ];
        if (!empty($_POST['password'])) {
            $data['password'] = password_hash(trim($_POST['password']), PASSWORD_DEFAULT);
        }
        if ($id > 0) {
            $targetAdmin = $db->fetch("SELECT role_id FROM {$db->table('admin')} WHERE id = ?", [$id]);
            if (intval($targetAdmin['role_id'] ?? -1) === 0 && ($roleId !== 0 || !$enabled)) {
                $superCount = $db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('admin')} WHERE role_id = 0 AND is_enabled = 1")['cnt'];
                if (intval($superCount) <= 1) {
                    echo '<script>alert("系统必须保留至少一个启用的超级管理员");history.back();</script>';
                    exit;
                }
            }
            $db->update('admin', $data, 'id = ?', [$id]);
            addLog('修改', '管理员管理', '修改管理员 ' . $data['realname']);
        } else {
            $data['password'] = password_hash(trim($_POST['password']), PASSWORD_DEFAULT);
            $data['create_time'] = time();
            $db->insert('admin', $data);
            addLog('添加', '管理员管理', '添加管理员 ' . $data['realname']);
        }
        echo '<script>alert("保存成功");location.href="?act=admin_user"</script>';
        exit;
    }
    if ($action === 'delete') {
        requireAdminCsrfToken(true);
        $id = intval($_POST['id']);
        if ($id == $_SESSION['admin_id']) {
            echo json_encode(['code' => 400, 'msg' => '不能删除当前登录的管理员']);
            exit;
        }
        $admin = $db->fetch("SELECT username FROM {$db->table('admin')} WHERE id = ?", [$id]);
        $target = $db->fetch("SELECT username, role_id, is_enabled FROM {$db->table('admin')} WHERE id = ?", [$id]);
        if (intval($target['role_id'] ?? -1) === 0 && intval($target['is_enabled'] ?? 0) === 1) {
            $superCount = $db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('admin')} WHERE role_id = 0 AND is_enabled = 1")['cnt'];
            if (intval($superCount) <= 1) {
                echo json_encode(['code' => 400, 'msg' => '系统必须保留至少一个启用的超级管理员']);
                exit;
            }
        }
        $db->delete('admin', 'id = ?', [$id]);
        addLog('删除', '管理员管理', '删除管理员 ' . ($admin['username'] ?? $id));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
}

if ($action === 'list') {
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $pageSize = 15;
    $offset = ($page - 1) * $pageSize;
    $lists = $db->fetchAll("SELECT a.*, r.role_name FROM {$db->table('admin')} a LEFT JOIN {$db->table('role')} r ON r.id = a.role_id ORDER BY a.id DESC LIMIT {$offset}, {$pageSize}");
    $total = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('admin')}")['cnt'];
    $totalPages = ceil($total / $pageSize);

    $totalAdmins = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('admin')}")['cnt'];
    $activeAdmins = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('admin')} WHERE is_enabled = 1")['cnt'];
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div class="page-title">
                <div class="page-icon"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg></div>
                <div><h1>管理员管理</h1><p style="font-size:12px;color:#64748b;margin:0;">后台统一为轻量列表结构，不再展示摘要卡。</p></div>
            </div>
            <div class="page-actions"><a href="?act=admin_user&action=add" class="btn btn-primary">添加管理员</a></div>
        </div>
        <div class="page-context-bar">
            <div class="page-context-item"><span class="page-context-label">管理员总数</span><span class="page-context-value"><?php echo $totalAdmins; ?> 人</span></div>
            <div class="page-context-item"><span class="page-context-label">已启用</span><span class="page-context-value"><?php echo $activeAdmins; ?> 人</span></div>
            <div class="page-context-item"><span class="page-context-label">分页大小</span><span class="page-context-value">每页 <?php echo $pageSize; ?> 条</span></div>
            <div class="page-context-item"><span class="page-context-label">当前页</span><span class="page-context-value page-context-muted">第 <?php echo $page; ?> / <?php echo max(1, $totalPages); ?> 页</span></div>
        </div>
        <div class="content-card">
            <table class="data-table">
                <thead>
                    <tr><th style="width:50px;">ID</th><th>用户名</th><th>真实姓名</th><th style="width:80px;">角色</th><th style="width:100px;">状态</th><th style="width:140px;">最后登录</th><th style="width:120px;">操作</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($lists as $item): ?>
                    <tr>
                        <td class="id-cell"><?php echo $item['id']; ?></td>
                        <td style="font-weight:500;"><?php echo htmlspecialchars($item['username']); ?></td>
                        <td><?php echo htmlspecialchars($item['realname'] ?: '-'); ?></td>
                        <td><span class="badge <?php echo intval($item['role_id']) === 0 ? 'badge-danger' : 'badge-primary'; ?>"><?php echo intval($item['role_id']) === 0 ? '超级管理员' : htmlspecialchars($item['role_name'] ?: '未配置角色'); ?></span></td>
                        <td>
                            <?php if ($item['is_enabled']): ?>
                            <span class="badge badge-success">正常</span>
                            <?php else: ?>
                            <span class="badge badge-secondary">禁用</span>
                            <?php endif; ?>
                        </td>
                        <td style="font-size:12px;color:#64748b;"><?php echo $item['last_login_time'] ? date('Y-m-d H:i', $item['last_login_time']) : '-'; ?></td>
                        <td>
                            <div class="btn-group">
                                <a href="?act=admin_user&action=edit&id=<?php echo $item['id']; ?>" class="btn btn-primary"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg> 编辑</a>
                                <?php if ($item['id'] != $_SESSION['admin_id']): ?>
                                <a href="javascript:delAdmin(<?php echo $item['id']; ?>);" class="btn btn-ghost" style="color:#EF4444;"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg> 删除</a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php if ($totalPages > 1): ?>
            <div class="pagination">
                <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                <a href="?act=admin_user&page=<?php echo $i; ?>" <?php echo $i == $page ? 'class="active"' : ''; ?>><?php echo $i; ?></a>
                <?php endfor; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>
    <style>
    .page-context-bar{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-bottom:16px;}
    .page-context-item{background:#fff;border:1px solid #e2e8f0;border-radius:14px;padding:14px 16px;}
    .page-context-label{display:block;font-size:12px;color:#94a3b8;margin-bottom:6px;}
    .page-context-value{display:block;font-size:14px;font-weight:700;color:#1e293b;line-height:1.6;}
    .page-context-muted{color:#475569;font-weight:600;}
    @media (max-width: 1200px){.page-context-bar{grid-template-columns:repeat(2,minmax(0,1fr));}}
    @media (max-width: 768px){.page-context-bar{grid-template-columns:1fr;}}
    </style>
    <script>
    function delAdmin(id) { if (confirm('确定删除该管理员?')) { fetch('?act=admin_user&action=delete', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+id+'&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>'}).then(r=>r.json()).then(d=>{alert(d.msg);if(d.code==200)location.reload();}); } }
    </script>
    <?php
}

if ($action === 'add' || $action === 'edit') {
    $roles = $db->fetchAll("SELECT id, role_name FROM {$db->table('role')} ORDER BY role_name ASC");
    $editData = ['id'=>'','username'=>'','password'=>'','realname'=>'','pen_name'=>'','mobile'=>'','email'=>'','role_id'=>($roles ? $roles[0]['id'] : -1),'is_enabled'=>1];
    if ($action === 'edit' && isset($_GET['id'])) {
        $editData = $db->fetch("SELECT * FROM {$db->table('admin')} WHERE id = ?", [intval($_GET['id'])]);
        $editData['mobile'] = $editData['phone'] ?? '';
        $editData['role_id'] = $editData['role_id'] ?? 2;
        $editData['password'] = '';
    }
    $isEdit = $action === 'edit';
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div class="page-title">
                <div class="page-icon"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="8.5" cy="7" r="4"/><line x1="20" y1="8" x2="20" y2="14"/><line x1="23" y1="11" x2="17" y2="11"/></svg></div>
                <div><h1><?php echo $isEdit ? '编辑管理员' : '添加管理员'; ?></h1><p style="font-size:12px;color:#64748b;margin:0;">填写管理员信息</p></div>
            </div>
            <div class="page-actions"><a href="?act=admin_user" class="btn btn-secondary">&larr; 返回</a></div>
        </div>
        <form method="post" action="?act=admin_user&action=save">
            <input type="hidden" name="id" value="<?php echo $editData['id']; ?>">
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
            <div class="form-section">
                <div class="form-section-header"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg> 基本信息</div>
                <div class="form-section-body">
                    <div class="form-row">
                        <div class="form-group">
                            <label>用户名 <span class="required">*</span></label>
                            <input type="text" name="username" class="form-control" value="<?php echo htmlspecialchars($editData['username']); ?>" placeholder="<?php echo $isEdit ? '(不可修改)' : '请输入用户名'; ?>" <?php echo $isEdit ? 'readonly' : 'required'; ?> style="<?php echo $isEdit ? 'background:#f1f5f9;cursor:not-allowed;' : ''; ?>">
                        </div>
                        <div class="form-group">
                            <label><?php echo $isEdit ? '新密码（留空不变）' : '密码'; ?> <span class="required">*</span></label>
                            <input type="password" name="password" class="form-control" placeholder="<?php echo $isEdit ? '留空保持原密码' : '请输入密码'; ?>" <?php echo $isEdit ? '' : 'required'; ?>>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group"><label>真实姓名</label><input type="text" name="realname" class="form-control" value="<?php echo htmlspecialchars($editData['realname']); ?>" placeholder=""></div>
                        <div class="form-group"><label>笔名</label><input type="text" name="pen_name" class="form-control" value="<?php echo htmlspecialchars($editData['pen_name']); ?>" placeholder=""></div>
                    </div>
                    <div class="form-row">
                        <div class="form-group"><label>手机号</label><input type="text" name="mobile" class="form-control" value="<?php echo htmlspecialchars($editData['mobile']); ?>" placeholder=""></div>
                        <div class="form-group"><label>邮箱</label><input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($editData['email']); ?>" placeholder=""></div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>角色</label>
                            <select name="role_id" class="form-control" style="width:200px;">
                                <option value="0" <?php echo intval($editData['role_id'])===0?'selected':''; ?>>超级管理员</option>
                                <?php foreach ($roles as $role): ?><option value="<?php echo intval($role['id']); ?>" <?php echo intval($editData['role_id'])===intval($role['id'])?'selected':''; ?>><?php echo htmlspecialchars($role['role_name']); ?></option><?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <label style="display:flex;align-items:center;gap:12px;cursor:pointer;padding-top:8px;">
                                <input type="checkbox" name="is_enabled" value="1" <?php echo $editData['is_enabled']?'checked':''; ?> id="statusToggle" style="display:none;">
                                <div id="statusSwitch" style="width:44px;height:24px;background:<?php echo $editData['is_enabled']?'#10b981':'#cbd5e1'; ?>;border-radius:12px;position:relative;transition:all 0.2s;"><div style="width:18px;height:18px;background:#fff;border-radius:50%;position:absolute;top:3px;left:<?php echo $editData['is_enabled']?'23px':'3px'; ?>;transition:all 0.2s;"></div></div>
                                <span id="statusLabel" style="font-weight:500;color:<?php echo $editData['is_enabled']?'#10b981':'#64748b'; ?>;"><?php echo $editData['is_enabled']?'启用':'禁用'; ?></span>
                            </label>
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-actions"><button type="submit" class="btn btn-success btn-lg">OK <?php echo $isEdit?'保存':'添加'; ?></button><a href="?act=admin_user" class="btn btn-secondary btn-lg">取消</a></div>
        </form>
    </div>
    <script>
    document.getElementById('statusToggle').addEventListener('change', function() {
        var sw = document.getElementById('statusSwitch');
        var lb = document.getElementById('statusLabel');
        if (this.checked) { sw.style.background = '#10b981'; sw.querySelector('div').style.left = '23px'; lb.textContent = '启用'; lb.style.color = '#10b981'; }
        else { sw.style.background = '#cbd5e1'; sw.querySelector('div').style.left = '3px'; lb.textContent = '禁用'; lb.style.color = '#64748b'; }
    });
    </script>
    <?php
}
?>

