<?php
session_name('user_session');
session_start();
require '../include/common.php';

// 处理登出操作
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy(); // 销毁会话
    header("Location: login.php"); // 跳转到登录页面
    exit();
}

// 处理登录操作
$error = '';
if (isset($_POST['username']) && isset($_POST['password'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // 检查验证码
    if (isset($currentSettings['captcha_interface']) && $currentSettings['captcha_interface'] == 'default') {
        if (empty($_POST['captcha'])) {
            $error = "请填写验证码！";
        } else {
            $input_captcha = $_POST['captcha'];
            if (!isset($_SESSION['captcha_code']) || strtolower($input_captcha) !== strtolower($_SESSION['captcha_code'])) {
                $error = "验证码错误！";
            }
        }
    }

    // 如果没有错误，继续验证用户身份
    if (empty($error)) {
        // 从数据库中查找用户
        $stmt = $pdo->prepare("SELECT * FROM " . table('users') . " WHERE username = :username");
        $stmt->execute(['username' => $username]);
        $user = $stmt->fetch();

        // 验证用户
        if ($user) {
            // 检查用户是否被封禁
            if ($user['role'] == 2) {
                $error = "该用户已被封禁，无法登录！";
            } else {
                // 验证密码
                if (password_verify($password, $user['password'])) {
                    // 原始密码验证成功
                    $_SESSION['user_id'] = $user['id']; // 存储用户 ID
                    $_SESSION['role'] = $user['role']; // 保存用户角色

                    // 记录登录日志
                    $ip_address = $_SERVER['REMOTE_ADDR'];
                    $login_time = date('Y-m-d H:i:s');
                    $logStmt = $pdo->prepare("INSERT INTO " . table('login_logs') . " (user_id, login_time, ip_address) VALUES (:user_id, :login_time, :ip_address)");
                    $logStmt->execute([
                        'user_id' => $user['id'],
                        'login_time' => $login_time,
                        'ip_address' => $ip_address
                    ]);

                    header("Location: index.php"); // 登录成功后跳转到用户管理页面
                    exit();
                } else {
                    $error = "用户名或密码错误！";
                }
            }
        } else {
            $error = "用户不存在！";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录页面</title>
    <link rel="stylesheet" href="../assets/css/bootstrap.min.css">
    <script src="../assets/libs/jquery/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<style>
    body {
            background: linear-gradient(135deg, #6a82fb, #fc5c7d);
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 15px;
            animation: gradient-animation 5s ease infinite;
        }
.btn-circle {
    width: 50px;  /* 圆形按钮的宽度 */
    height: 50px; /* 圆形按钮的高度 */
    border-radius: 50%; /* 圆角 */
    display: flex; /* 使用 Flexbox 来居中图标 */
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
    font-size: 24px; /* 图标大小 */
    text-decoration: none;
}

.text-center {
    display: flex;
    justify-content: center;
    align-items: center;
}
.alert {
    width: 100%;
    margin: 0 auto;
}

</style>


</head>

<body>
    <div class="container">
    <div class="row justify-content-center">
        <div class="col-md-4">
            <div class="card" style="border: none;">
                <h1 class="text-center mt-5">用户管理中心</h1>
                <?php if (isset($error) && $error): ?>
        <div class="alert alert-danger" role="alert">
            <?php echo $error; ?>
        </div>
    <?php endif; ?>
                <div class="card-body">
                    <form method="post" action="login.php" id="loginForm">
                        <div class="mb-3">
                            <label for="username" class="form-label">用户名:</label>
                            <input type="text" class="form-control" name="username" id="username" required placeholder="请输入用户名">
                        </div>
                        <div class="mb-3">
                            <label for="password" class="form-label">密码:</label>
                            <input type="password" class="form-control" name="password" id="password" required placeholder="密码">
                        </div>
                        <?php if (isset($currentSettings['captcha_interface']) && $currentSettings['captcha_interface'] == 'geetest'): ?>
                            <div id="captcha"></div>
                            <br>
                        <?php endif; ?>
                        <?php if (isset($currentSettings['captcha_interface']) && $currentSettings['captcha_interface'] == 'default'): ?>
                            <label for="captcha" class="form-label mr-2">验证码:</label>
                            <div class="mb-3 d-flex align-items-center">
                                <input type="text" class="form-control" name="captcha" id="captcha" required placeholder="请输入验证码" style="width: 80%;">
                                <img src="captcha.php" alt="验证码" class="captcha-img ms-2" style="width: 100px; height: auto; margin-left: 10px;" id="captchaImage" onclick="refreshCaptcha()">
                            </div>
                        <?php endif; ?>

                        <br>
                        <button type="button" class="btn btn-primary col-12" id="btn">登录</button>
                    </form>
                    <div class="mt-3 d-flex justify-content-between">
                        <a href="register.php" class="btn btn-success">注册</a>
                        <a href="forgot_pass.php" class="btn btn-danger">找回</a>
                    </div>
                    <div class="text-center mt-4 d-flex justify-content-center">
                        <a href="../other/oauth/uniauth/connect.php?type=qq" class="btn btn-circle btn-info mx-1" style="color: white;" title="QQ 登录">
                            <i class="fab fa-qq"></i>
                        </a>
                        <a href="../other/oauth/uniauth/connect.php?type=wx" class="btn btn-circle btn-success mx-1" title="微信 登录">
                            <i class="fab fa-weixin"></i>
                        </a>
                        <a href="../other/oauth/uniauth/connect.php?type=alipay" class="btn btn-circle btn-primary mx-1" title="支付宝 登录">
                            <i class="fab fa-alipay"></i>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="../assets/js/popper.min.js"></script>
<script src="../assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../assets/js/gt4.js"></script>

<script>
    // 判断使用极验验证码
    <?php if (isset($currentSettings['captcha_interface']) && $currentSettings['captcha_interface'] == 'geetest'): ?>
        initGeetest4({
            captchaId: '<?php echo $apiCredentials['captcha_id']; ?>',
            nativeButton: {
                width: '100%',
            },
            product: 'float'
        }, function (captcha) {
            captcha.appendTo("#captcha");

            $("#btn").click(function (event) {
                event.preventDefault();
                var result = captcha.getValidate();
                if (!result) {
                    return alert('请完成验证');
                }

                $('<input>').attr({
                    type: 'hidden',
                    name: 'captcha_id',
                    value: result.captcha_id
                }).appendTo('#loginForm');

                $('<input>').attr({
                    type: 'hidden',
                    name: 'captcha_value',
                    value: result.validate
                }).appendTo('#loginForm');

                $('#loginForm').submit();
            });
        });
    <?php else: ?>
        // 图像验证码刷新功能
        function refreshCaptcha() {
            const timestamp = new Date().getTime();
            document.getElementById('captchaImage').src = 'captcha.php?r=' + timestamp;
        }

        $("#btn").click(function (event) {
            event.preventDefault();
            $('#loginForm').submit();
        });
    <?php endif; ?>
</script>
