<?php
// 确保没有BOM和空行
if (ob_get_length()) ob_clean();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once 'includes/init.php';
require_once 'includes/PHPMailer/PHPMailer.php';
require_once 'includes/PHPMailer/SMTP.php';
require_once 'includes/PHPMailer/Exception.php';
require_once 'includes/mail_helper.php';
use PHPMailer\PHPMailer\PHPMailer;

// 处理发送验证码请求（必须放在最顶部）
if (isset($_POST['send_code']) && $_POST['send_code'] == 1) {
    if (ob_get_length()) ob_clean(); // 清空缓冲区，防止多余输出
    header('Content-Type: text/plain; charset=UTF-8');
    $email = trim($_POST['email'] ?? '');
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo '[[[START]]]'.json_encode(['success'=>false, 'msg'=>'请输入正确的邮箱地址']).'[[[END]]]';
        exit;
    }
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    if (!$user) {
        echo '[[[START]]]'.json_encode(['success'=>false, 'msg'=>'该邮箱未注册']).'[[[END]]]';
        exit;
    }
    $code = rand(100000, 999999);
    $expires = date('Y-m-d H:i:s', time() + 300); // 5分钟有效
    $type = 'reset_password';
    $pdo->prepare("DELETE FROM email_codes WHERE email = ?")->execute([$email]);
    $pdo->prepare("INSERT INTO email_codes SET email=?, code=?, type=?, is_used=0, expires_at=?, created_at=NOW()")
        ->execute([$email, $code, $type, $expires]);
    $subject = '重置密码验证码：' . $code;
    $body = "您的重置密码验证码为：$code，有效期5分钟。";
    require_once 'includes/mail_helper.php';
    $errorInfo = '';
    if (send_mail($email, $subject, $body, $errorInfo, 'password_reset', null, null)) {
        echo '[[[START]]]'.json_encode(['success'=>true, 'msg'=>'验证码已发送到您的邮箱，请查收。']).'[[[END]]]';
    } else {
        echo '[[[START]]]'.json_encode(['success'=>false, 'msg'=>'邮件发送失败：' . var_export($errorInfo, true)]).'[[[END]]]';
    }
    exit;
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $code = trim($_POST['code'] ?? '');
    $password = trim($_POST['password'] ?? '');
    if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !$code || !$password) {
        $error = '请填写所有信息';
    } else {
        if (!function_exists('checkEmailCode')) require_once __DIR__ . '/includes/email_code_helper.php';
        // 使用与发送时一致的类型 'reset_password'，避免类型不匹配导致“验证码过期”
        if (!checkEmailCode($email, $code, $pdo, 'reset_password')) {
            $error = '验证码错误或已过期';
        } else {
            $password_hash = Encryption::getInstance()->hashPassword($password);
            $stmt = $pdo->prepare("UPDATE users SET password=? WHERE email=?");
            $stmt->execute([$password_hash, $email]);
            $uid = 0;
            try {
                $st = $pdo->prepare('SELECT id FROM users WHERE email=? LIMIT 1');
                $st->execute([$email]);
                $uid = (int) $st->fetchColumn();
            } catch (Throwable $e) {
                $uid = 0;
            }
            require_once __DIR__ . '/includes/login_lockout_helper.php';
            if (is_file(__DIR__ . '/includes/security_ban_helper.php')) {
                require_once __DIR__ . '/includes/security_ban_helper.php';
            }
            $unlock = ggai_login_lockout_unlock_after_password_reset($email, $uid);
            $success = !empty($unlock['permanent_ban'])
                ? '密码已更新，但账号处于永久封禁，无法登录，请联系客服。'
                : '密码重置成功，请登录。';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>重置密码</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #232526 0%, #414345 100%);
            min-height: 100vh;
            margin: 0;
            overflow-x: hidden;
        }
        .center-box {
            max-width: 410px;
            margin: 60px auto;
            background: rgba(20, 24, 36, 0.98);
            border-radius: 18px;
            box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37), 0 1.5px 8px 0 #00f2fe44;
            padding: 44px 36px 36px 36px;
            border: 1.5px solid rgba(0,242,254,0.18);
            position: relative;
            overflow: hidden;
        }
        .center-box:before {
            content: '';
            position: absolute;
            top: -60px; left: -60px;
            width: 180px; height: 180px;
            background: radial-gradient(circle, #00f2fe55 0%, transparent 70%);
            z-index: 0;
        }
        h1 {
            text-align: center;
            color: #00f2fe;
            margin-bottom: 32px;
            letter-spacing: 2px;
            font-weight: 700;
            text-shadow: 0 0 8px #00f2fe88, 0 2px 8px #232526;
        }
        .form-group { margin-bottom: 22px; position: relative; z-index: 1; }
        .form-label {
            display: block;
            margin-bottom: 7px;
            color: #b2b8c6;
            font-size: 1.05em;
            letter-spacing: 1px;
        }
        .form-input {
            width: 100%;
            padding: 12px 14px;
            border: 1.5px solid #00f2fe55;
            border-radius: 7px;
            background: rgba(36, 40, 56, 0.92);
            color: #eaf6fb;
            font-size: 1.08em;
            outline: none;
            transition: border-color 0.2s, box-shadow 0.2s;
            box-shadow: 0 0 0 0 #00f2fe44;
        }
        .form-input:focus {
            border-color: #00f2fe;
            box-shadow: 0 0 8px 0 #00f2fe88;
        }
        .form-btn {
            width: 100%;
            padding: 13px 0;
            background: linear-gradient(90deg, #43e97b 0%, #38f9d7 100%);
            color: #232526;
            border: none;
            border-radius: 7px;
            font-size: 1.13em;
            font-weight: bold;
            cursor: pointer;
            margin-top: 10px;
            box-shadow: 0 2px 12px 0 #00f2fe33;
            letter-spacing: 1px;
            transition: background 0.2s, box-shadow 0.2s, color 0.2s;
            position: relative;
            z-index: 1;
        }
        .form-btn:hover, .form-btn:focus {
            background: linear-gradient(90deg, #00f2fe 0%, #4facfe 100%);
            color: #fff;
            box-shadow: 0 0 16px 0 #00f2fe99;
        }
        .error {
            color: #ff4757;
            text-align: center;
            margin-bottom: 15px;
            font-weight: bold;
            letter-spacing: 1px;
        }
        .success {
            color: #2ecc40;
            text-align: center;
            margin-bottom: 15px;
            font-weight: bold;
            letter-spacing: 1px;
        }
        .code-row {
            display: flex;
            gap: 10px;
        }
        #sendCodeBtn {
            width: auto;
            min-width: 110px;
            padding: 0 18px;
            background: linear-gradient(90deg, #00f2fe 0%, #4facfe 100%);
            color: #232526;
            border: none;
            border-radius: 7px;
            font-size: 1em;
            font-weight: bold;
            cursor: pointer;
            box-shadow: 0 2px 8px 0 #00f2fe33;
            transition: background 0.2s, color 0.2s, box-shadow 0.2s;
        }
        #sendCodeBtn:hover, #sendCodeBtn:focus {
            background: linear-gradient(90deg, #43e97b 0%, #38f9d7 100%);
            color: #232526;
            box-shadow: 0 0 12px 0 #43e97b99;
        }
        a {
            color: #00f2fe;
            text-decoration: none;
            font-weight: 500;
            letter-spacing: 1px;
            transition: color 0.2s;
        }
        a:hover {
            color: #43e97b;
        }
        @media (max-width: 500px) {
            .center-box { padding: 24px 8px; }
        }
    </style>
</head>
<body>
    <div class="center-box">
        <h1>重置密码</h1>
        <?php if ($error): ?><div class="error"><?php echo $error; ?></div><?php endif; ?>
        <?php if ($success): ?><div class="success"><?php echo $success; ?></div><?php endif; ?>
        <form method="post" id="resetForm" autocomplete="off">
            <div class="form-group">
                <label class="form-label">注册邮箱</label>
                <input type="email" name="email" id="email" class="form-input" required value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
            </div>
            <div class="form-group">
                <label class="form-label">验证码</label>
                <div class="code-row">
                    <input type="text" name="code" class="form-input" required style="flex:1;" value="<?php echo htmlspecialchars($_POST['code'] ?? ''); ?>">
                    <button type="button" id="sendCodeBtn" class="form-btn">发送验证码</button>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label">新密码</label>
                <input type="password" name="password" class="form-input" required>
            </div>
            <button type="submit" class="form-btn">重置密码</button>
        </form>
        <div style="text-align:center;margin-top:18px;z-index:1;position:relative;">
            <a href="login.php">返回登录</a>
        </div>
    </div>
</body>
<script src="/assets/js/jquery-3.7.1.min.js"></script>
<script>
$(function(){
    var wait = 60;
    var timer = null;
    function startCountdown() {
        var btn = $('#sendCodeBtn');
        btn.prop('disabled', true);
        timer = setInterval(function() {
            if (wait <= 0) {
                clearInterval(timer);
                btn.text('发送验证码').prop('disabled', false);
                wait = 60;
            } else {
                btn.text('重新发送(' + wait + 's)');
                wait--;
            }
        }, 1000);
    }
    $('#sendCodeBtn').click(function(){
        var email = $('#email').val().trim();
        if (!email) {
            alert('请先输入注册邮箱');
            return;
        }
        $.post('reset_password.php', {email: email, send_code: 1}, function(res){
            var start = res.indexOf('[[[START]]]');
            var end = res.indexOf('[[[END]]]');
            if (start !== -1 && end !== -1) {
                var jsonStr = res.substring(start + 11, end);
                try {
                    var data = JSON.parse(jsonStr);
                    alert(data.msg);
                    if(data.success) startCountdown();
                } catch(e) {
                    alert('发送失败，请重试');
                }
            } else {
                alert('发送失败，请重试');
            }
        });
    });
});
</script>
</html> 