<?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') {
        $id = intval($_POST['id']);
        $data = [
            'realname' => trim($_POST['realname']),
            'pen_name' => trim($_POST['pen_name']),
            'phone' => trim($_POST['mobile']),
            'email' => trim($_POST['email']),
            'role_id' => intval($_POST['role_id']),
            'is_enabled' => isset($_POST['is_enabled']) ? 1 : 0,
            'update_time' => time()
        ];
        if (!empty($_POST['password'])) {
            $data['password'] = md5(trim($_POST['password']));
        }
        if ($id > 0) {
            $db->update('admin', $data, 'id = ?', [$id]);
            addLog('修改', '管理员管理', '修改管理员 ' . $data['realname']);
        } else {
            $data['password'] = md5(trim($_POST['password']));
            $data['create_time'] = time();
            $db->insert('admin', $data);
            addLog('添加', '管理员管理', '添加管理员 ' . $data['realname']);
        }
        echo '<script>alert("保存成功");location.href="?act=admin_user"</script>';
        exit;
    }
    if ($action === 'delete') {
        $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]);
        $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 * FROM {$db->table('admin')} ORDER BY 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="stats-grid">
        <div class="stat-card">
            <div class="stat-icon" style="background:#eff6ff;color:#2563eb;"><svg style="width:22px;height:22px;" 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 class="stat-info"><div class="stat-value"><?php echo $totalAdmins; ?></div><div class="stat-label">管理员总数</div></div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background:#ecfdf5;color:#10b981;"><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"/><polyline points="17 11 19 13 23 9"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $activeAdmins; ?></div><div class="stat-label">已启用</div></div>
        </div>
    </div>
    <div class="filter-bar">
        <a href="?act=admin_user&action=add" class="btn btn-success">+ 添加管理员</a>
    </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 $item['role_id'] === 1 ? 'badge-danger' : 'badge-primary'; ?>"><?php echo $item['role_id'] === 1 ? '超级' : '普通'; ?></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>
    <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}).then(r=>r.json()).then(d=>{alert(d.msg);if(d.code==200)location.reload();}); } }
    </script>
    <?php
}

if ($action === 'add' || $action === 'edit') {
    $editData = ['id'=>'','username'=>'','password'=>'','realname'=>'','pen_name'=>'','mobile'=>'','email'=>'','role_id'=>2,'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']; ?>">
            <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" class="form-control" style="width:200px;">
                                <option value="2" <?php echo $editData['role_id']==2?'selected':''; ?>>普通管理员</option>
                                <option value="1" <?php echo $editData['role_id']==1?'selected':''; ?>>超级管理员</option>
                            </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="status" 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
}
?>

