<?php
ob_start();
/**
 * 2026企业CMS - 后台管理员管理
 */
require_once __DIR__ . '/header.php';
check_permission('superadmin');
$pageTitle = '管理员管理';
$action = $_GET['action'] ?? 'list';
$id = intval($_GET['id'] ?? 0);

// 处理删除
if ($action === 'delete' && $id) {
    if ($id == $_SESSION['admin_id']) {
        header('Location: /admin/admins.php?error=' . urlencode('不能删除自己！'));
        exit;
    }
    db_exec("DELETE FROM `admins` WHERE `id`=?", [$id]);
    add_log('delete', 'admins', '删除管理员ID:' . $id);
    header('Location: /admin/admins.php?msg=' . urlencode('删除成功！'));
    exit;
}

// 处理保存
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save'])) {
	// CSRF 保护
	if (!csrf_validate($_POST["csrf_token"] ?? "")) {
	    die("CSRF 验证失败");
	}

    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $realname = trim($_POST['realname'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $role = $_POST['role'] ?? 'editor';
    $status = intval($_POST['status'] ?? 1);
    
    if ($action === 'add') {
        if (!$password) {
            header('Location: /admin/admins.php?error=' . urlencode('密码不能为空！'));
            exit;
        }
        $hash = password_hash($password, PASSWORD_DEFAULT);
        db_exec(
            "INSERT INTO `admins` (`username`,`password`,`realname`,`email`,`role`,`status`) VALUES (?,?,?,?,?,?)",
            [$username, $hash, $realname, $email, $role, $status]
        );
        add_log('add', 'admins', '添加管理员: ' . $username);
    } elseif ($action === 'edit' && $id) {
        $sql = "UPDATE `admins` SET `username`=?,`realname`=?,`email`=?,`role`=?,`status`=? WHERE `id`=?";
        $params = [$username, $realname, $email, $role, $status, $id];
        if ($password) {
            $sql = str_replace('`status`=?', '`status`=?,`password`=?', $sql);
            array_splice($params, 5, 0, [password_hash($password, PASSWORD_DEFAULT)]);
        }
        db_exec($sql, $params);
        add_log('edit', 'admins', '编辑管理员: ' . $username);
    }
    header('Location: /admin/admins.php?msg=' . urlencode('保存成功！'));
    exit;
}

$admin = [];
if (($action === 'add' || $action === 'edit') && $action !== 'list') :
    if ($id) $admin = db_query_one("SELECT * FROM `admins` WHERE `id`=?", [$id]);
?>
<div class="page-header">
    <h2><?php echo htmlspecialchars($action, ENT_QUOTES, "UTF-8")=='add'?'添加管理员':'编辑管理员'; ?></h2>
    <a href="/admin/admins.php" class="btn">← 返回列表</a>
</div>
<div class="form-card">
    <form method="post" action="">
        <?php echo csrf_input(); ?>
        <input type="hidden" name="csrf_token" value="<?= csrf_generate() ?>">
        <div class="form-row">
            <div class="form-group">
                <label>用户名 <span style="color:red;">*</span></label>
                <input type="text" name="username" value="<?php echo xss_clean($admin['username'] ?? ''); ?>" required <?php echo htmlspecialchars($action, ENT_QUOTES, "UTF-8")=='edit'?'readonly style="background:#f5f5f5;"':''; ?>>
            </div>
            <div class="form-group">
                <label>密码 <?php echo htmlspecialchars($action, ENT_QUOTES, "UTF-8")=='edit'?'<span style="color:#999;font-weight:normal;">(留空不修改)</span>':'<span style="color:red;">*</span>'; ?></label>
                <input type="password" name="password" <?php echo htmlspecialchars($action, ENT_QUOTES, "UTF-8")=='add'?'required':''; ?>>
            </div>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label>真实姓名</label>
                <input type="text" name="realname" value="<?php echo xss_clean($admin['realname'] ?? ''); ?>">
            </div>
            <div class="form-group">
                <label>邮箱</label>
                <input type="email" name="email" value="<?php echo xss_clean($admin['email'] ?? ''); ?>">
            </div>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label>角色</label>
                <select name="role">
                    <option value="editor" <?php echo ($admin['role'] ?? 'editor')=='editor'?'selected':''; ?>>编辑员 (可发布内容)</option>
                    <option value="admin" <?php echo ($admin['role'] ?? '')=='admin'?'selected':''; ?>>管理员 (管理内容)</option>
                    <option value="superadmin" <?php echo ($admin['role'] ?? '')=='superadmin'?'selected':''; ?>>超级管理员 (全部权限)</option>
                </select>
            </div>
            <div class="form-group">
                <label>状态</label>
                <select name="status">
                    <option value="1" <?php echo ($admin['status'] ?? 1)==1?'selected':''; ?>>启用</option>
                    <option value="0" <?php echo ($admin['status'] ?? 1)==0?'selected':''; ?>>禁用</option>
                </select>
            </div>
        </div>
        <div style="margin-top:30px;">
            <button type="submit" name="save" class="btn btn-primary" style="margin-right:10px;">保存</button>
            <a href="/admin/admins.php" class="btn">取消</a>
        </div>
    </form>
</div>
<?php
require_once __DIR__ . '/footer.php';
exit;
endif;

$admins = db_query("SELECT * FROM `admins` ORDER BY `id` ASC");
?>
<div class="page-header">
    <h2>管理员管理</h2>
    <a href="/admin/admins.php?action=add" class="btn btn-primary"><i class="fas fa-plus"></i> 添加管理员</a>
</div>
<p style="color:#999;margin-bottom:15px;">只有超级管理员可以访问此页面</p>

<div class="table-wrapper">
    <table>
        <thead><tr><th>ID</th><th>用户名</th><th>姓名</th><th>角色</th><th>最后登录</th><th>状态</th><th>操作</th></tr></thead>
        <tbody>
            <?php foreach ($admins as $a): ?>
            <tr>
                <td><?php echo $a['id']; ?></td>
                <td><?php echo xss_clean($a['username']); ?></td>
                <td><?php echo xss_clean($a['realname']); ?></td>
                <td>
                    <?php 
                    $roleMap = ['superadmin'=>'超级管理员','admin'=>'管理员','editor'=>'编辑员'];
                    echo $roleMap[$a['role']] ?? $a['role'];
                    ?>
                </td>
                <td><?php echo $a['last_login'] ? date('Y-m-d H:i', strtotime($a['last_login'])) : '从未登录'; ?></td>
                <td>
                    <?php if ($a['status']): ?><span class="badge badge-success">启用</span>
                    <?php else: ?><span class="badge badge-danger">禁用</span>
                    <?php endif; ?>
                </td>
                <td class="actions">
                    <a href="/admin/admins.php?action=edit&id=<?php echo $a['id']; ?>" class="btn btn-sm btn-primary">编辑</a>
                    <?php if ($a['id'] != $_SESSION['admin_id']): ?>
                    <a href="javascript:void(0)" onclick="if(confirmDelete(<?php echo $a['id']; ?>,'<?php echo xss_clean($a['username']); ?>')){location.href='/admin/admins.php?action=delete&id=<?php echo $a['id']; ?>'}" class="btn btn-sm btn-danger">删除</a>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php require_once __DIR__ . '/footer.php'; ?>
