<?php
require 'session_init.php';
require '../include/common.php';


$errorMessage = '';
$successMessage = '';


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    $email = $_POST['email'] ?? '';
    $mobile = $_POST['mobile'] ?? ''; 
    $verification_code = $_POST['verification_code'] ?? '';
    $password = $_POST['password'] ?? '';

    session_name('user_session');
    session_start();
    if ($_SESSION['verification_code'] != $verification_code) {
        $errorMessage = '验证码不正确。';
    } else {
        
        $username = mysqli_real_escape_string($conn, $username);
        $password = password_hash($password, PASSWORD_BCRYPT); 

        
        if (!empty($email)) {
            
            $email = mysqli_real_escape_string($conn, $email);
            $checkSql = "SELECT * FROM " . table('users') . " WHERE username = '$username' OR email = '$email'";
        } elseif (!empty($mobile)) {
            
            $mobile = mysqli_real_escape_string($conn, $mobile);
            $checkSql = "SELECT * FROM " . table('users') . " WHERE username = '$username' OR mobile = '$mobile'";
        }

        
        $result = mysqli_query($conn, $checkSql);

        if (mysqli_num_rows($result) > 0) {
            $errorMessage = '用户名、邮箱或手机号已被注册。';
        } else {
            
            $sql = "INSERT INTO " . table('users') . " (username, email, mobile, password, created_at) VALUES ('$username', '$email', '$mobile', '$password', NOW())";

            if (mysqli_query($conn, $sql)) {
                $successMessage = '注册成功！';
            } else {
                $errorMessage = '注册失败：' . mysqli_error($conn); 
            }
        }

        mysqli_close($conn);
    }
}

$secretKey = bin2hex(random_bytes(16));
$_SESSION['secret_key'] = $secretKey;
?>

<!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/js/jquery.min.js"></script>
    <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;
        }

        @keyframes gradient-animation {
            0% {
                background-position: 0% 50%;
            }

            50% {
                background-position: 100% 50%;
            }

            100% {
                background-position: 0% 50%;
            }
        }

        .login-container {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 400px;
            margin: auto;
        }

        .btn-primary {
            background-color: rgba(81, 86, 190);
            border-color: rgba(81, 86, 190);
        }

        .btn-primary:hover {
            background-color: rgba(81, 86, 190);
            border-color: rgba(81, 86, 190);
        }

        .social-login {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }

        .social-login a {
            margin: 0 10px;
            color: rgba(81, 86, 190, 0.5);
            font-size: 24px;
        }

        .text-primary {
            color: rgba(81, 86, 190, 0.5) !important;
        }

        .alert {
            padding: 5px;
        }
    </style>
</head>

<body>
    <div class="login-container"
        style="min-height: 400px; max-width: 350px; padding: 20px; background-color: white; border-radius: 10px; box-shadow: 0px 0px 10px rgba(0,0,0,0.1);">
    <div class="text-center mb-4" style="display: flex; align-items: center; justify-content: center;">
        <img src="../assets/images/logo-sm.svg" style="width: 32px; height: 32px; margin-right: 10px;">
        <strong><?php echo $currentSettings['site_name']; ?></strong>
    </div>

    <h3 class="text-center mb-4">用户注册</h3>

    <div class="d-flex justify-content-between mb-4">
        <button class="btn btn-light border" onclick="window.location.href='register.php?type=email'" style="flex: 1; margin-right: 5px; background-color: #f8f9fa;">邮箱注册</button>
        <button class="btn btn-light border" onclick="window.location.href='register.php?type=phone'" style="flex: 1; margin-left: 5px; background-color: #f8f9fa;">手机号注册</button>
    </div>

    <?php if ($errorMessage): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($errorMessage); ?></div>
    <?php elseif ($successMessage): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($successMessage); ?></div>
    <?php endif; ?>

    <div class="tab-content" id="myTabContent">
        <div class="tab-pane fade show active" role="tabpanel">
            <form method="post" action="register.php" id="registerForm">
                <div class="mb-3">
                    <label for="username" class="form-label">用户名:</label>
                    <input type="text" class="form-control" name="username" id="username" required>
                </div>
                <?php if (isset($_GET['type']) && $_GET['type'] === 'phone'): ?>
                    <div class="mb-3">
                        <label for="mobile" class="form-label">手机号:</label>
                        <input type="text" class="form-control" name="mobile" id="mobile" required>
                    </div>
                    <div class="mb-3">
                        <button type="button" class="btn btn-primary mt-4" onclick="sendVerificationCode('mobile')"
                            style="width: 100%;">发送验证码
                        </button>
                    </div>
                <?php else: ?>
                    <div class="mb-3">
                        <label for="email" class="form-label">电子邮件:</label>
                        <input type="email" class="form-control" name="email" id="email" required>
                    </div>
                    <div class="mb-3">
                        <button type="button" class="btn btn-primary mt-4" onclick="sendVerificationCode('email')"
                            style="width: 100%;">发送验证码
                        </button>
                    </div>
                <?php endif; ?>

                <div class="mb-3">
                    <label for="verification_code" class="form-label">验证码:</label>
                    <input type="text" class="form-control" name="verification_code" id="verification_code" required>
                </div>

                <div class="mb-3">
                    <label for="password" class="form-label">密码:</label>
                    <input type="password" class="form-control" name="password" id="password" required>
                </div>

                <button type="submit" class="btn btn-primary" style="width: 100%;">注册</button>
            </form>

            <p class="mt-3 text-center">
                <a href="login.php" style="text-decoration: none;">已经注册？请登录</a>
            </p>
        </div>
    </div>
</div>


    <script>
        function sendVerificationCode(type) {
            var email = $('#email').val(); 
            var mobile = $('#mobile').val(); 
            var button = $("button[onclick^='sendVerificationCode()']");

            
            if (type === 'mobile' && !mobile) {
                alert('请填写手机号。');
                return;
            } else if (type === 'email' && !email) {
                alert('请填写电子邮件。');
                return;
            }
            var secretKey = "<?php echo $secretKey; ?>";
            
            var dataToSend = {
                ...(type === 'mobile' ? { mobile: mobile } : {}),
                ...(type === 'email' ? { email: email } : {}),
                 secret_key: secretKey
            };
            
            button.prop('disabled', true).addClass('btn-secondary').removeClass('btn-primary');

            
            $.ajax({
                url: 'ajax.php',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(dataToSend),
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        alert(response.message); 
                    } else {
                        alert('发送验证码失败: ' + response.message); 
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert('请求发生错误: ' + textStatus + ', ' + errorThrown); 
                }
            });
            console.log(dataToSend);
            
            var countdown = 60;
            button.text('请 ' + countdown + ' 秒后重试');
            var interval = setInterval(function () {
                countdown--;
                button.text('请 ' + countdown + ' 秒后重试');
                if (countdown <= 0) {
                    clearInterval(interval); 
                    button.prop('disabled', false).removeClass('btn-secondary').addClass('btn-primary').text('发送验证码'); 
                }
            }, 1000); 
        }

    </script>

</body>

</html>