<?php

require_once __DIR__ . '/common.php';

admin_require_login();

$pdo       = db();
$adminUser = admin_current_user();
$siteTitle = get_setting('site.title', '六柱博客');

$errors = [];
$infos  = [];


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!admin_csrf_check($_POST['csrf_token'] ?? null)) {
        $errors[] = '请求已失效，请刷新页面后重试。';
    } else {
        $action = $_POST['action'] ?? '';
        $userId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
        if ($userId <= 0) {
            $errors[] = '缺少用户 ID。';
        } else {
            try {
            $now = time();
            if ($action === 'set_status') {
                $status = $_POST['status'] ?? '';
                if (!in_array($status, ['active', 'disabled'], true)) {
                    $errors[] = '不支持的账号状态。';
                } else {
                    if ($status === 'disabled') {
                        
                        $stmt = $pdo->prepare("
                            UPDATE users
                            SET status = 'disabled',
                                is_comment_banned = 1,
                                is_post_banned = 1,
                                updated_at = :t
                            WHERE id = :id
                        ");
                        $stmt->execute([
                            ':t'  => $now,
                            ':id' => $userId,
                        ]);
                        $infos[] = '已将用户 #' . $userId . ' 标记为禁用（软删除），并禁止评论与投稿。';
                        admin_log('user_disable', '禁用用户 ID=' . $userId);
                    } else {
                        
                        $stmt = $pdo->prepare("
                            UPDATE users
                            SET status = 'active',
                                updated_at = :t
                            WHERE id = :id
                        ");
                        $stmt->execute([
                            ':t'  => $now,
                            ':id' => $userId,
                        ]);
                        $infos[] = '已恢复用户 #' . $userId . ' 的账号状态为正常。';
                    }
                }
            } elseif ($action === 'set_comment_ban') {
                $val = ($_POST['value'] ?? '0') === '1' ? 1 : 0;
                $stmt = $pdo->prepare("UPDATE users SET is_comment_banned = :v, updated_at = :t WHERE id = :id");
                $stmt->execute([
                    ':v'  => $val,
                    ':t'  => $now,
                    ':id' => $userId,
                ]);
                $infos[] = ($val ? '已禁止' : '已恢复') . '用户 #' . $userId . ' 的评论权限。';
                admin_log($val ? 'user_comment_ban' : 'user_comment_unban', '用户 ID=' . $userId);
            } elseif ($action === 'set_post_ban') {
                $val = ($_POST['value'] ?? '0') === '1' ? 1 : 0;
                $stmt = $pdo->prepare("UPDATE users SET is_post_banned = :v, updated_at = :t WHERE id = :id");
                $stmt->execute([
                    ':v'  => $val,
                    ':t'  => $now,
                    ':id' => $userId,
                ]);
                $infos[] = ($val ? '已禁止' : '已恢复') . '用户 #' . $userId . ' 的投稿权限。';
                admin_log($val ? 'user_post_ban' : 'user_post_unban', '用户 ID=' . $userId);
            } elseif ($action === 'mark_email_verified') {
                $stmt = $pdo->prepare("UPDATE users SET email_verified = 1, updated_at = :t WHERE id = :id");
                $stmt->execute([
                    ':t'  => $now,
                    ':id' => $userId,
                ]);
                $infos[] = '已标记用户 #' . $userId . ' 的邮箱为“已验证”。';
                admin_log('user_email_verified', '标记邮箱已验证 用户 ID=' . $userId);
            } elseif ($action === 'update_user') {
                $nickname = trim((string)($_POST['nickname'] ?? ''));
                $email    = trim((string)($_POST['email'] ?? ''));
                $password = (string)($_POST['password'] ?? '');

                if ($nickname === '') {
                    $errors[] = '昵称不能为空。';
                }
                if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $errors[] = '邮箱格式不正确。';
                }

                if (!$errors) {
                    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = :email AND id <> :id LIMIT 1");
                    $stmt->execute([
                        ':email' => $email,
                        ':id'    => $userId,
                    ]);
                    if ($stmt->fetchColumn()) {
                        $errors[] = '该邮箱已被其他用户占用。';
                    }
                }

                if (!$errors) {
                    $fields = [
                        'nickname = :nickname',
                        'email = :email',
                        'updated_at = :t',
                    ];
                    $params = [
                        ':nickname' => $nickname,
                        ':email'    => $email,
                        ':t'        => $now,
                        ':id'       => $userId,
                    ];
                    if (trim($password) !== '') {
                        if (strlen($password) < 6) {
                            $errors[] = '新密码至少 6 位。';
                        } else {
                            $fields[] = 'password_hash = :ph';
                            $params[':ph'] = password_hash($password, PASSWORD_DEFAULT);
                        }
                    }
                    if (!$errors) {
                        $sql = "UPDATE users SET " . implode(', ', $fields) . " WHERE id = :id";
                        $stmt = $pdo->prepare($sql);
                        $stmt->execute($params);
                        $infos[] = '已更新用户 #' . $userId . ' 的资料。';
                        admin_log('user_update', '更新用户资料 ID=' . $userId);
                    }
                }
            }
        } catch (Throwable $e) {
            $errors[] = '操作失败：' . $e->getMessage();
        }
        }
    }
}


$q      = trim((string)($_GET['q'] ?? ''));
$status = (string)($_GET['status'] ?? '');

$where   = [];
$params  = [];

if ($q !== '') {
    $where[]         = '(email LIKE :q OR nickname LIKE :q)';
    $params[':q']    = '%' . $q . '%';
}

if ($status === 'active' || $status === 'disabled') {
    $where[]          = 'status = :status';
    $params[':status'] = $status;
} elseif ($status === 'pending_email') {
    $where[] = 'email_verified = 0';
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';


$total = 0;
try {
    $stmt = $pdo->prepare("SELECT COUNT(*) AS c FROM users $whereSql");
    $stmt->execute($params);
    $total = (int)$stmt->fetchColumn();
} catch (Throwable $e) {
    $total = 0;
}


$page     = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$pageSize = 30;
$offset   = ($page - 1) * $pageSize;


$users = [];
try {
    $sql = "
SELECT
    id,
    email,
    nickname,
    role,
    status,
    email_verified,
    is_comment_banned,
    is_post_banned,
    created_at,
    last_login_at,
    last_login_ip
FROM users
$whereSql
ORDER BY id DESC
LIMIT :limit OFFSET :offset
";
    $stmt = $pdo->prepare($sql);
    foreach ($params as $k => $v) {
        $stmt->bindValue($k, $v);
    }
    $stmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $users = $stmt->fetchAll() ?: [];
} catch (Throwable $e) {
    $errors[] = '读取用户列表失败：' . $e->getMessage();
    $users    = [];
}

?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>会员管理 - <?php echo h($siteTitle); ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        html, body { height:100%;  margin:0; padding:0; }
        body {
            margin: 0; padding:0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
            background: #020617;
            color: #e5e7eb;
        }
        a {
            color: #60a5fa;
            text-decoration: none;
        }
        a:hover {
            text-decoration: underline;
        }
        .topbar {
            background: #0f172a;
            border-bottom: 1px solid #1f2937;
            padding:18px 16px 6px;
            display: flex;
            align-items:flex-start;
            justify-content: space-between;
         margin:0;  margin-top:-12px; }
        .topbar-title {
            font-size: 16px;
            font-weight: 600;
        }
        .topbar-user {
            font-size: 13px;
            color: #9ca3af;
        }
        .topbar-nav a {
            margin-left: 10px;
            font-size: 13px;
        }
        .page {
            max-width: 1100px;
            margin: 0 auto;
            padding: 16px;
        }
        .card {
            background: #020617;
            border-radius: 6px;
            border: 1px solid #1f2937;
            padding: 12px 14px;
            margin-bottom: 12px;
        }
        .card-title {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 8px;
        }
        .small-text {
            font-size: 12px;
            color: #9ca3af;
        }
        details.user-edit {
            margin-top: 6px;
        }
        details.user-edit summary {
            cursor: pointer;
            font-size: 12px;
            color: #93c5fd;
        }
        .edit-form {
            margin-top: 6px;
            padding: 6px;
            border: 1px solid #1f2937;
            border-radius: 4px;
            background: #0b1220;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 6px;
        }
        .edit-form label {
            display: flex;
            flex-direction: column;
            font-size: 12px;
            color: #9ca3af;
        }
        .edit-form input {
            margin-top: 4px;
            padding: 4px 6px;
            border-radius: 4px;
            border: 1px solid #1f2937;
            background: #020617;
            color: #e5e7eb;
            font-size: 12px;
        }
        .edit-form .form-actions {
            grid-column: 1 / -1;
            display: flex;
            gap: 6px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 12px;
        }
        th, td {
            border-bottom: 1px solid #1f2937;
            padding: 4px 6px;
            text-align: left;
        }
        th {
            font-weight: 600;
            background: #020617;
        }
        .status-badge {
            display: inline-block;
            padding: 1px 6px;
            border-radius: 999px;
            font-size: 11px;
        }
        .status-active {
            background: rgba(16, 185, 129, 0.1);
            color: #6ee7b7;
        }
        .status-disabled {
            background: rgba(248, 113, 113, 0.1);
            color: #fecaca;
        }
        .status-pending-email {
            background: rgba(59, 130, 246, 0.1);
            color: #bfdbfe;
        }
        .btn-small {
            border-radius: 999px;
            border: 1px solid #374151;
            background: transparent;
            color: #e5e7eb;
            font-size: 11px;
            padding: 2px 6px;
            cursor: pointer;
        }
        .filters {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            margin-bottom: 8px;
        }
        .filters input,
        .filters select {
            padding: 3px 6px;
            border-radius: 4px;
            border: 1px solid #374151;
            background: #020617;
            color: #e5e7eb;
            font-size: 12px;
        }
        .errors {
            background: #7f1d1d;
            border: 1px solid #fecaca;
            color: #fee2e2;
            padding: 6px 8px;
            border-radius: 4px;
            font-size: 12px;
            margin-bottom: 10px;
        }
        .infos {
            background: #064e3b;
            border: 1px solid #6ee7b7;
            color: #d1fae5;
            padding: 6px 8px;
            border-radius: 4px;
            font-size: 12px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body style="margin:0;padding:0;"><div class="topbar">
    <div class="topbar-title">会员管理</div>
    <div class="topbar-user">
        管理员：<?php echo h($adminUser['nickname'] ?? $adminUser['email'] ?? ''); ?>
        <span class="topbar-nav">
            <a href="index.php">仪表盘</a>
            <a href="articles.php">文章</a>
            <a href="categories.php">分类</a>
            <a href="tags.php">&#26631;&#31614;</a>
            <a href="comments.php">评论</a>
            <a href="links.php">友链</a>
                <a href="media.php">文件</a>
            <a href="users.php"><strong>会员</strong></a>
            <a href="sensitive_words.php">敏感词</a>
            <a href="stats.php">流量</a>
            <a href="security.php">防护</a>
            <a href="logs.php">日志</a>
            <a href="settings.php">设置</a>
            <a href="backup_sqlite.php">&#25968;&#25454;</a>
            <a href="../index.php">前台</a>
            <a href="../logout.php">退出</a>
        </span>
    </div>
</div>

<div class="page">
    <?php if ($errors): ?>
        <div class="errors">
            <?php foreach ($errors as $err): ?>
                <div><?php echo h($err); ?></div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
    <?php if ($infos): ?>
        <div class="infos">
            <?php foreach ($infos as $msg): ?>
                <div><?php echo h($msg); ?></div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <div class="card">
        <div class="card-title">筛选</div>
        <form method="get" class="filters">
            <div>
                <input type="text" name="q" placeholder="按邮箱 / 昵称搜索" value="<?php echo h($q); ?>">
            </div>
            <div>
                <select name="status">
                    <option value="">全部状态</option>
                    <option value="active" <?php echo $status === 'active' ? 'selected' : ''; ?>>正常</option>
                    <option value="disabled" <?php echo $status === 'disabled' ? 'selected' : ''; ?>>已禁用</option>
                    <option value="pending_email" <?php echo $status === 'pending_email' ? 'selected' : ''; ?>>邮箱未验证</option>
                </select>
            </div>
            <div>
                <button type="submit" class="btn-small">应用筛选</button>
            </div>
            <div class="small-text">
                共 <?php echo (int)$total; ?> 个会员，当前第 <?php echo (int)$page; ?> 页。
            </div>
        </form>
    </div>

    <div class="card">
        <div class="card-title">会员列表（按 ID 倒序，每页 30 条）</div>
        <?php if ($users): ?>
            <table>
                <thead>
                <tr>
                    <th>ID</th>
                    <th>邮箱 / 昵称</th>
                    <th>角色</th>
                    <th>状态</th>
                    <th>邮箱验证</th>
                    <th>评论</th>
                    <th>投稿</th>
                    <th>注册时间</th>
                    <th>最近登录</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($users as $u): ?>
                    <tr>
                        <td><?php echo (int)$u['id']; ?></td>
                        <td>
                            <div><?php echo h($u['email']); ?></div>
                            <div class="small-text"><?php echo h($u['nickname']); ?></div>
                        </td>
                        <td><?php echo h($u['role']); ?></td>
                        <td>
                            <?php
                            $statusClass = 'status-active';
                            $statusText  = '正常';
                            if ($u['status'] !== 'active') {
                                $statusClass = 'status-disabled';
                                $statusText  = '已禁用';
                            } elseif ((int)$u['email_verified'] === 0) {
                                $statusClass = 'status-pending-email';
                                $statusText  = '待验证';
                            }
                            ?>
                            <span class="status-badge <?php echo $statusClass; ?>"><?php echo $statusText; ?></span>
                        </td>
                        <td>
                            <?php if ((int)$u['email_verified'] === 1): ?>
                                <span class="small-text">已验证</span>
                            <?php else: ?>
                                <form method="post" style="display:inline;">
                                    <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                    <input type="hidden" name="user_id" value="<?php echo (int)$u['id']; ?>">
                                    <input type="hidden" name="action" value="mark_email_verified">
                                    <button type="submit" class="btn-small">标记已验证</button>
                                </form>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ((int)$u['is_comment_banned'] === 1): ?>
                                <span class="small-text">已禁用</span>
                                <form method="post" style="display:inline;">
                                    <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                    <input type="hidden" name="user_id" value="<?php echo (int)$u['id']; ?>">
                                    <input type="hidden" name="action" value="set_comment_ban">
                                    <input type="hidden" name="value" value="0">
                                    <button type="submit" class="btn-small">恢复</button>
                                </form>
                            <?php else: ?>
                                <span class="small-text">正常</span>
                                <form method="post" style="display:inline;">
                                    <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                    <input type="hidden" name="user_id" value="<?php echo (int)$u['id']; ?>">
                                    <input type="hidden" name="action" value="set_comment_ban">
                                    <input type="hidden" name="value" value="1">
                                    <button type="submit" class="btn-small">禁止</button>
                                </form>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ((int)$u['is_post_banned'] === 1): ?>
                                <span class="small-text">已禁用</span>
                                <form method="post" style="display:inline;">
                                    <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                    <input type="hidden" name="user_id" value="<?php echo (int)$u['id']; ?>">
                                    <input type="hidden" name="action" value="set_post_ban">
                                    <input type="hidden" name="value" value="0">
                                    <button type="submit" class="btn-small">恢复</button>
                                </form>
                            <?php else: ?>
                                <span class="small-text">正常</span>
                                <form method="post" style="display:inline;">
                                    <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                    <input type="hidden" name="user_id" value="<?php echo (int)$u['id']; ?>">
                                    <input type="hidden" name="action" value="set_post_ban">
                                    <input type="hidden" name="value" value="1">
                                    <button type="submit" class="btn-small">禁止</button>
                                </form>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php echo $u['created_at'] ? date('Y-m-d', (int)$u['created_at']) : '-'; ?>
                        </td>
                        <td>
                            <?php if (!empty($u['last_login_at'])): ?>
                                <div><?php echo date('m-d H:i', (int)$u['last_login_at']); ?></div>
                                <?php if (!empty($u['last_login_ip'])): ?>
                                    <div class="small-text"><?php echo h($u['last_login_ip']); ?></div>
                                <?php endif; ?>
                            <?php else: ?>
                                <span class="small-text">从未登录</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($u['status'] === 'active'): ?>
                                <form method="post" style="display:inline;">
                                    <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                    <input type="hidden" name="user_id" value="<?php echo (int)$u['id']; ?>">
                                    <input type="hidden" name="action" value="set_status">
                                    <input type="hidden" name="status" value="disabled">
                                    <button type="submit" class="btn-small">禁用账号</button>
                                </form>
                            <?php else: ?>
                                <form method="post" style="display:inline;">
                                    <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                    <input type="hidden" name="user_id" value="<?php echo (int)$u['id']; ?>">
                                    <input type="hidden" name="action" value="set_status">
                                    <input type="hidden" name="status" value="active">
                                    <button type="submit" class="btn-small">恢复账号</button>
                                </form>
                            <?php endif; ?>
                            <details class="user-edit">
                                <summary>编辑资料</summary>
                                <form method="post" class="edit-form">
                                    <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                    <input type="hidden" name="user_id" value="<?php echo (int)$u['id']; ?>">
                                    <input type="hidden" name="action" value="update_user">
                                    <label>
                                        昵称
                                        <input type="text" name="nickname" value="<?php echo h($u['nickname']); ?>">
                                    </label>
                                    <label>
                                        邮箱
                                        <input type="email" name="email" value="<?php echo h($u['email']); ?>">
                                    </label>
                                    <label>
                                        新密码
                                        <input type="password" name="password" placeholder="留空不修改">
                                    </label>
                                    <div class="form-actions">
                                        <button type="submit" class="btn-small">保存</button>
                                    </div>
                                </form>
                            </details>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <div class="small-text">暂无会员记录。</div>
        <?php endif; ?>
    </div>
</div>
</body>
</html>
