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

// 初始化消息变量
$errorMessage = '';
$successMessage = '';

// 验证码及重置密码逻辑
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_password'])) {
    session_start();
    $email = trim($_POST['email'] ?? '');
    $mobile = trim($_POST['mobile'] ?? '');
    $verification_code = $_POST['verification_code'] ?? '';
    $new_password = $_POST['new_password'] ?? '';

    // 确保验证码匹配
    if ($_SESSION['verification_code'] != $verification_code) {
        $errorMessage = '验证码不正确。';
    } else {
        // 确保邮箱或手机号至少有一个填写
        if (!$email && !$mobile) {
            $errorMessage = '请填写邮箱或手机号。';
            mysqli_close($conn);
            exit;
        }

        // 加密新密码
        $new_password_hashed = password_hash($new_password, PASSWORD_BCRYPT); // 加密新密码

        // 使用预处理语句更新用户密码
        if ($email) {
            $updateSql = "UPDATE " . table('users') . " SET password = ? WHERE email = ?";
            $identifier = $email;
        } elseif ($mobile) {
            $updateSql = "UPDATE " . table('users') . " SET password = ? WHERE mobile = ?";
            $identifier = $mobile;
        }

        $stmt = mysqli_prepare($conn, $updateSql);
        if ($stmt) {
            mysqli_stmt_bind_param($stmt, "ss", $new_password_hashed, $identifier); // 绑定参数

            // 执行更新操作并检查结果
            if (mysqli_stmt_execute($stmt)) {
                // 检查实际影响的行数
                if (mysqli_stmt_affected_rows($stmt) > 0) {
                    $successMessage = '密码重置成功！';
                    unset($_SESSION['verification_code']); // 清除验证码
                } else {
                    $errorMessage = '没有找到匹配的用户，密码没有被更新。请检查邮箱或手机号是否正确。';
                }
            } else {
                $errorMessage = '密码重置失败：' . mysqli_stmt_error($stmt);
                error_log("SQL Error: " . mysqli_stmt_error($stmt)); // 记录错误信息
            }

            mysqli_stmt_close($stmt);
        } else {
            $errorMessage = '准备查询失败：' . mysqli_error($conn);
            error_log("SQL Prepare Error: " . 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/jquerymin.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 class="container mt-5">
    <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>

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

        <div class="tab-content" id="myTabContent">
            <div class="tab-pane fade show active" role="tabpanel">
                <form method="post" id="forgotPasswordForm">
                    <?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>
                    <?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>
                    <?php endif; ?>

                    <button type="button" name="send_code" class="btn btn-primary mt-4" style="width: 100%;"
                        onclick="sendVerificationCode()">发送验证码</button>
                </form>

                <form method="post" action="forgot_pass.php" id="resetPasswordForm" class="mt-3">
                    <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="new_password" class="form-label">新密码:</label>
                        <input type="password" class="form-control" name="new_password" id="new_password" required>
                    </div>

                    <input type="hidden" name="email" id="hidden_email">
                    <input type="hidden" name="mobile" id="hidden_mobile">

                    <button type="submit" name="reset_password" class="btn btn-primary mt-4" 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() {
            var email = $('#email').val();
            var mobile = $('#mobile').val();
            var button = $("button[onclick='sendVerificationCode()']");

            if (email && mobile) {
                alert('请填写邮箱或手机号，但不要同时填写两者。');
                return;
            } else if (!email && !mobile) {
                alert('请填写邮箱或手机号。');
                return;
            }

            var secretKey = "<?php echo $secretKey; ?>";

            var dataToSend = {
                ...(email ? { email: email } : {}),
                ...(mobile ? { mobile: mobile } : {}),
                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);
                }
            });

            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>
