<?php
// 功能：用户管理专用文件
// 作者：启肯科技
// Q Q：328493711
// 微信：13738373177（同手机）
// 官网：http://www.qiken.com
// 说明：QKCMS-轻量级AI智能内容管理建站系统
// 版权：© 2025 温州启肯网络有限公司 保留所有权利，盗版必究。

if (!defined('ADMIN_LOADED')) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        require_once dirname(__DIR__) . '\common.php';
        get_db_connection();
        define('ADMIN_LOADED', true);
    } else {
        header('HTTP/1.1 403 Forbidden');
        exit('Access Denied');
    }
}

global $conn;



// 处理POST请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 处理编辑用户请求
    if (isset($_POST['action']) && $_POST['action'] === 'edit_user') {
        $user_id = intval($_POST['user_id']);
        $data = [
            'username' => isset($_POST['username']) ? trim($_POST['username']) : '',
            'level' => intval($_POST['levels_id']),
            'status' => $_POST['status'] ?? '1',
            'points' => intval($_POST['points'] ?? 0),
            'password' => isset($_POST['password']) ? trim($_POST['password']) : '',
            'email' => isset($_POST['email']) ? trim($_POST['email']) : ''
        ];

        if (empty($data['username'])) {
            echo json_encode(['success' => false, 'message' => '用户名不能为空']);
            exit;
        }

        echo json_encode(updateUser($conn, $user_id, $data));
        exit;
    }

    // 处理删除用户请求
    if (isset($_POST['delete_user'])) {
        $result = deleteUser($conn, intval($_POST['delete_user']));
        echo $result === true ? '用户已成功删除' : $result;
        exit;
    }
}

// 处理GET请求（用于AJAX）
if (isset($_GET['delete_user'])) {
    $result = deleteUser($conn, intval($_GET['delete_user']));
    if ($result === true && !isset($_GET['ajax'])) {
        echo '<script>showToast("用户已成功删除！", "success", 2000);setTimeout(() => window.location.reload(), 2000);</script>';
    } else {
        echo $result === true ? 'success' : $result;
    }
    exit;
}

if (isset($_GET['action']) && $_GET['action'] === 'edit_user') {
    $data = [
        'username' => isset($_GET['username']) ? trim($_GET['username']) : '',
        'level' => intval($_GET['levels_id']),
        'status' => $_GET['status'] ?? '1',
        'points' => intval($_GET['points'] ?? 0),
        'password' => isset($_GET['password']) ? trim($_GET['password']) : '',
        'email' => isset($_GET['email']) ? trim($_GET['email']) : ''
    ];

    if (empty($data['username'])) {
        echo json_encode(['success' => false, 'message' => '用户名不能为空']);
        exit;
    }

    echo json_encode(updateUser($conn, intval($_GET['user_id']), $data));
    exit;
}



// 获取用户列表
$total_users = getUsersWithPasswords($search, 1, 1, true);
$total_pages = max(1, ceil($total_users / $posts_per_page));
$users = getUsersWithPasswords($search, $current_page, $posts_per_page);
?>

<?php if ($active_tab == 'users'): ?>
    <div class="section-header">
        <h2>用户管理</h2>
    </div>
    <div class="admin-card">
        <div class="table-container">
            <table class="admin-table user-manage">
                <thead>
                    <tr>
                        <th class="id-column">ID</th>
                        <th>头像</th>
                        <th>用户名</th>
                        <th>等级</th>
                        <th>注册时间</th>
                        <th>积分</th>
                        <th>状态</th>
                        <th class="text-right">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($users)): ?>
                        <tr>
                            <td colspan="8" style="text-align:center !important;height:75px;line-height:75px;font-size:16px;color:#64748b;">当前列表暂无数据</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($users as $user):
                            $status = $user['status'] ?? 1;
                            $avatar_src = !empty($user['avatar']) ? (string)$user['avatar'] : DEFAULT_AVATAR_PATH;
                            if (stripos(ltrim($avatar_src), '<svg') === 0) {
                                $avatar_src = 'data:image/svg+xml;utf8,' . rawurlencode($avatar_src);
                            } else {
                                $avatar_src = str_replace('\\', '/', $avatar_src);
                                if (stripos($avatar_src, 'uploads/') === 0) {
                                    $avatar_src = '/' . $avatar_src;
                                }
                                $avatar_src = preg_replace('#^(https?://[^/]+)?/admin/uploads/#i', '/uploads/', $avatar_src);
                                $avatar_src = preg_replace('#^(https?://[^/]+)?uploads/#i', '/uploads/', $avatar_src);
                            }
                        ?>
                            <tr>
                                <td class="id-column"><?php echo $user['id']; ?></td>
                                <td>
                                    <div class="user-avatar">
                                        <img src="<?php echo escape($avatar_src); ?>" alt="<?php echo escape($user['username']); ?>">
                                    </div>
                                </td>
                                <td><?php echo escape($user['username']); ?></td>
                                <td><?php echo escape($user['level_name']); ?></td>
                                <td><?php echo date('Y-m-d H:i', strtotime($user['created_at'])); ?></td>
                                <td><?php echo escape($user['points']); ?></td>
                                <td>
                                    <span class="<?php echo $status == 1 ? 'text-success' : 'text-danger'; ?>">
                                        <?php echo $status == 1 ? '正常' : '已封禁'; ?>
                                    </span>
                                </td>
                                <td class="action-column">
                                    <button type="button" onclick='editUser(<?php echo $user["id"]; ?>, <?php echo json_encode((string)$user["username"], JSON_UNESCAPED_UNICODE); ?>, <?php echo $user["levels_id"]; ?>, <?php echo $status; ?>, <?php echo $user["points"]; ?>, <?php echo json_encode((string)($user["email"] ?? ""), JSON_UNESCAPED_UNICODE); ?>);' class="btn btn-sm btn-primary">编辑</button>
                                    <button type="button" onclick="deleteUserConfirm(<?php echo $user['id']; ?>, <?php echo $user['levels_id']; ?>);" class="btn btn-sm btn-danger">删除</button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <style>
            .modal-content {
                position: relative;
                background-color: white;
                border-radius: 8px;
                box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
                width: 100%;
                max-width: 550px;
                max-height: 550px;
                overflow-y: auto;
                transform: scale(0.95);
                opacity: 0;
                transition: transform 0.3s ease, opacity 0.3s ease;
                margin: 15% auto;
            }

            .modal-content.modal-visible {
                transform: scale(1);
                opacity: 1;
            }

            .modal-content .submit-button {
                width: 100%;
                padding: 12px;
                background-color: var(--primary-color);
                color: white;
                border: none;
                border-radius: 4px;
                font-size: 16px;
                font-weight: 500;
                cursor: pointer;
                transition: background-color 0.2s ease;
                margin: 0;
                display: block;
            }

            .modal-content .submit-button:hover {
                background-color: var(--primary-color-dark, #6d28d9);
            }

            .user-avatar {
                width: 36px;
                height: 36px;
                border-radius: 50%;
                overflow: hidden;
            }

            .user-avatar img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }

            .empty-data {
                text-align: center;
                padding: 30px;
            }

            .admin-table.user-manage .id-column {
                width: 80px !important;
                min-width: 80px !important;
                max-width: 80px !important;
            }

            .action-column {
                text-align: right !important;
                min-width: 150px;
            }

            .action-column .btn-sm {
                margin-left: 5px !important;
            }

            .action-column .btn-sm:first-child {
                margin-left: 0 !important;
            }

            .modal-actions {
                padding: 5px 30px 20px;
            }

            .admin-table.user-manage .user-avatar {
                margin: 0 !important;
                vertical-align: middle;
                display: inline-block;
                line-height: normal !important;
            }

            .admin-table.user-manage .user-avatar img {
                vertical-align: middle;
                line-height: normal !important;
            }

            .admin-table.user-manage th:nth-child(4),
            .admin-table.user-manage td:nth-child(4) {
                width: 120px !important;
                min-width: 120px !important;
                max-width: 120px !important;
            }


            .admin-table.user-manage th:nth-child(6),
            .admin-table.user-manage td:nth-child(6) {
                width: 120px !important;
                min-width: 120px !important;
                max-width: 120px !important;
            }

            .admin-table.user-manage th:nth-child(7),
            .admin-table.user-manage td:nth-child(7) {
                min-width: 110px !important;
                width: 110px !important;
                max-width: 110px !important;
            }



            .modal-body {
                padding: 30px;
                padding-bottom: 15px;
            }

            @media (max-width: 768px) {
                .admin-table.user-manage {
                    width: 100% !important;
                    font-size: 14px !important;
                    table-layout: auto !important;
                    min-width: auto !important;
                }

                .admin-table.user-manage .id-column {
                    width: 50px !important;
                    min-width: 50px !important;
                    max-width: 50px !important;
                }

                .admin-table.user-manage th,
                .admin-table.user-manage td {
                    padding: 0 6px !important;
                    font-size: 14px !important;
                }

                .admin-table.user-manage th:nth-child(5),
                .admin-table.user-manage td:nth-child(5),
                .admin-table.user-manage th:nth-child(6),
                .admin-table.user-manage td:nth-child(6) {
                    display: none !important;
                }

                .admin-table.user-manage th:last-child,
                .admin-table.user-manage td:last-child {
                    min-width: 120px !important;
                    max-width: 120px !important;
                    text-align: right !important;
                    white-space: nowrap !important;
                }
            }
        </style>
        <script>
            function resolveUserAvatarSrc(avatar) {
                let val = (avatar || '').toString().trim();
                if (!val) return '/assets/images/avatar.png';
                if (/^<svg[\s>]/i.test(val)) return 'data:image/svg+xml;utf8,' + encodeURIComponent(val);
                val = val.replace(/\\/g, '/');
                if (/^uploads\//i.test(val)) val = '/' + val;
                val = val.replace(/^(https?:\/\/[^/]+)?\/admin\/uploads\//i, '/uploads/');
                val = val.replace(/^(https?:\/\/[^/]+)?uploads\//i, '/uploads/');
                return val;
            }

            function formatCreatedAtToMinute(createdAt) {
                const val = (createdAt || '').toString().trim();
                if (!val) return '-';
                const normalized = val.replace('T', ' ').replace(/\.\d+$/, '');
                if (/^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}(:\d{2})?$/.test(normalized)) {
                    return normalized.slice(0, 16);
                }
                const d = new Date(val);
                if (isNaN(d.getTime())) return val;
                const y = d.getFullYear();
                const m = String(d.getMonth() + 1).padStart(2, '0');
                const day = String(d.getDate()).padStart(2, '0');
                const hh = String(d.getHours()).padStart(2, '0');
                const mm = String(d.getMinutes()).padStart(2, '0');
                return `${y}-${m}-${day} ${hh}:${mm}`;
            }

            function renderUsersList(data) {
                const tbody = document.querySelector('.user-manage tbody');
                if (!tbody) return;

                if (!data.users || data.users.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="8" style="text-align:center !important;height:75px;line-height:75px;font-size:16px;color:#64748b;">当前列表暂无数据</td></tr>';
                    return;
                }

                tbody.innerHTML = data.users.map(user => `
                    <tr>
                        <td class="id-column">${user.id}</td>
                        <td>
                            <div class="user-avatar">
                                <img src="${resolveUserAvatarSrc(user.avatar)}" alt="${user.username}">
                            </div>
                        </td>
                        <td>${user.username}</td>
                        <td>${user.level_name || '-'}</td>
                        <td>${formatCreatedAtToMinute(user.created_at)}</td>
                        <td>${user.points || 0}</td>
                        <td><span class="${user.status == 1 ? 'text-success' : 'text-danger'}">${user.status == 1 ? '正常' : '已封禁'}</span></td>
                        <td class="action-column">
                            <button type="button" onclick='editUser(${user.id}, ${JSON.stringify(user.username || "")}, ${user.levels_id}, ${user.status || 1}, ${user.points || 0}, ${JSON.stringify(user.email || "")});' class="btn btn-sm btn-primary">编辑</button>
                            <button type="button" onclick="deleteUserConfirm(${user.id}, ${user.levels_id});" class="btn btn-sm btn-danger">删除</button>
                        </td>
                    </tr>
                `).join('');
            }
        </script>
    <?php endif; ?>

    <div id="editUserModal" class="modal">
        <div class="modal-backdrop"></div>
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">编辑用户</h3>
                <button type="button" class="modal-close" onclick="window.closeModal()">&times;</button>
            </div>
            <div class="modal-body">
                <form id="editUserForm">
                    <input type="hidden" id="editUserId" name="user_id">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="editUsername">用户名</label>
                            <input type="text" class="form-control" id="editUsername" name="username" readonly>
                        </div>
                        <div class="form-group">
                            <label for="editPassword">密码（留空表示不修改）</label>
                            <input type="text" class="form-control" id="editPassword" name="password" placeholder="请输入新密码">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="editLevel">用户等级</label>
                            <select class="form-control" id="editLevel" name="levels_id">
                                <option value="1">游客</option>
                                <option value="2">VIP</option>
                                <option value="3">管理员</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="editPoints">用户积分</label>
                            <input type="number" class="form-control" id="editPoints" name="points" placeholder="请输入用户积分">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="editEmail">绑定邮箱</label>
                            <input type="text" class="form-control" id="editEmail" name="email" placeholder="请输入邮箱">
                        </div>
                        <div class="form-group">
                            <label for="editStatus">用户状态</label>
                            <select class="form-control" id="editStatus" name="status">
                                <option value="1">正常</option>
                                <option value="0">已封禁</option>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-actions">
                <button type="button" class="submit-button" onclick="saveUserEdit();">立即保存</button>
            </div>
        </div>
    </div>

    <script>
        function handleUsersAjaxResult(rawText, successMessage, onSuccess) {
            let result = null;

            try {
                result = JSON.parse(rawText);
            } catch (e) {}

            if (result && result.success === false) {
                showToast(result.message || result.error || '演示账号无权限操作', 'error');
                return;
            }

            if (result && result.success === true) {
                showToast(successMessage, 'info', 2000);
                if (typeof onSuccess === 'function') {
                    onSuccess();
                }
                return;
            }

            if (typeof rawText === 'string' && (rawText.includes('成功') || rawText.includes('SUCCESS'))) {
                showToast(successMessage, 'info', 2000);
                if (typeof onSuccess === 'function') {
                    onSuccess();
                }
                return;
            }

            showToast((result && (result.message || result.error)) || ('操作失败: ' + rawText), 'error');
        }

        function resetUserForm() {
            const fields = {
                'editUserId': '',
                'editUsername': '',
                'editPassword': '',
                'editLevel': '1',
                'editStatus': '1',
                'editPoints': '',
                'editEmail': ''
            };

            Object.entries(fields).forEach(([id, value]) => {
                const el = document.getElementById(id);
                if (el) {
                    el.value = value;
                    el.disabled = false;
                    el.removeAttribute('disabled');
                    el.style.cssText = '';
                }
            });
        }

        function setFieldDisabled(id, disabled) {
            const el = document.getElementById(id);
            if (!el) return;

            if (disabled) {
                el.disabled = true;
                el.setAttribute('disabled', 'disabled');
                el.style.cssText = 'pointer-events:none;background-color:#e9ecef;cursor:not-allowed;opacity:0.65;';
            } else {
                el.disabled = false;
                el.removeAttribute('disabled');
                el.style.cssText = '';
            }
        }

        function editUser(userId, username, level, status, points, email) {
            resetUserForm();

            const fields = {
                'editUserId': userId,
                'editUsername': username,
                'editLevel': level,
                'editStatus': status,
                'editPoints': points,
                'editEmail': email || ''
            };

            Object.entries(fields).forEach(([id, value]) => {
                const el = document.getElementById(id);
                if (el) el.value = value;
            });

            if (level == 3 || userId == 1) {
                setFieldDisabled('editLevel', true);
                setFieldDisabled('editStatus', true);
            }

            const modal = document.getElementById('editUserModal');
            if (modal) {
                modal.style.display = 'flex';
                requestAnimationFrame(() => modal.classList.add('modal-visible'));
            }
        }

        function deleteUserConfirm(userId, level) {
            if (level == 3 || userId == 1) {
                showToast('管理员账号无法删除', 'error');
                return;
            }

            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/admin/users.php', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function() {
                if (xhr.status >= 200 && xhr.status < 300) {
                    handleUsersAjaxResult(xhr.responseText, '用户删除成功', function() {
                        if (typeof HeaderPagination !== 'undefined') {
                            HeaderPagination.load();
                        }
                    });
                } else {
                    showToast('网络请求失败，请重试', 'error');
                }
            };
            xhr.onerror = () => showToast('网络连接错误，请检查您的网络', 'error');
            xhr.send('delete_user=' + userId);
        }

        function saveUserEdit() {
            const formData = new FormData();
            formData.append('user_id', document.getElementById('editUserId').value);
            formData.append('username', document.getElementById('editUsername').value);
            formData.append('levels_id', document.getElementById('editLevel').value);
            formData.append('status', document.getElementById('editStatus').value);
            formData.append('points', document.getElementById('editPoints').value);
            formData.append('email', document.getElementById('editEmail').value);

            const password = document.getElementById('editPassword').value;
            if (password) formData.append('password', password);
            formData.append('action', 'edit_user');

            fetch('/admin/users.php', {
                    method: 'POST',
                    body: formData
                })
                .then(r => r.text())
                .then(data => {
                    handleUsersAjaxResult(data, '用户信息更新成功！', function() {
                        window.closeModal();
                        if (typeof HeaderPagination !== 'undefined') {
                            HeaderPagination.load();
                        }
                    });
                })
                .catch(() => showToast('保存失败，请稍后重试', 'error'));
        }

        window.closeModal = function() {
            document.querySelectorAll('.modal').forEach(modal => {
                if (modal.classList.contains('modal-visible')) {
                    modal.classList.remove('modal-visible');
                    setTimeout(() => {
                        modal.style.display = 'none';
                        if (modal.id === 'editUserModal') resetUserForm();
                    }, 300);
                }
            });
        };
    </script>
