<?php
require_once dirname(__DIR__) . '/config.php';
require_once dirname(__DIR__) . '/includes/mail_helper.php';

header('Content-Type: application/json');

$email = trim($_POST['email'] ?? '');

if (empty($email)) {
    echo json_encode(['success' => false, 'message' => '请输入邮箱']);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'message' => '邮箱格式不正确']);
    exit;
}

// 检查邮箱是否存在
$user = $db->fetchOne("SELECT id, username FROM users WHERE email = '$email'");
if (!$user) {
    echo json_encode(['success' => false, 'message' => '该邮箱未注册']);
    exit;
}

// 检查发送频率（60秒内只能发送一次）
$lastRecord = $db->fetchOne("SELECT created_at FROM email_verify_codes WHERE email = '$email' AND type = 'reset' ORDER BY id DESC LIMIT 1");
if ($lastRecord) {
    $lastTime = strtotime($lastRecord['created_at']);
    if (time() - $lastTime < 60) {
        $wait = 60 - (time() - $lastTime);
        echo json_encode(['success' => false, 'message' => "请等待 {$wait} 秒后再试"]);
        exit;
    }
}

// 生成验证码
$code = sprintf("%06d", mt_rand(0, 999999));
$expired_at = date('Y-m-d H:i:s', strtotime('+10 minutes'));

// 删除旧的未使用验证码
$db->query("DELETE FROM email_verify_codes WHERE email = '$email' AND type = 'reset' AND used = 0");

// 保存验证码
$db->query("INSERT INTO email_verify_codes (email, code, type, expired_at) VALUES ('$email', '$code', 'reset', '$expired_at')");

// 发送邮件
$subject = "找回密码 - " . getSiteConfig('site_name') ?? '授权系统';
$content = '
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
    <div style="max-width: 500px; margin: 0 auto; background: #f9fafb; border-radius: 16px; overflow: hidden;">
        <div style="background: linear-gradient(135deg, #667eea, #764ba2); padding: 30px; text-align: center;">
            <h2 style="color: white; margin: 0;">🔐 找回密码</h2>
        </div>
        <div style="padding: 30px;">
            <p>尊敬的用户，您好！</p>
            <p>您正在申请找回密码，验证码如下：</p>
            <div style="text-align: center; margin: 30px 0;">
                <span style="font-size: 36px; font-weight: bold; letter-spacing: 5px; background: #f3f4f6; padding: 12px 24px; border-radius: 12px;">' . $code . '</span>
            </div>
            <p style="color: #6b7280; font-size: 14px;">验证码有效期为 <strong>10分钟</strong>，请尽快完成密码重置。</p>
            <p style="color: #6b7280; font-size: 14px;">如果这不是您本人操作，请忽略此邮件。</p>
        </div>
    </div>
</body>
</html>';

if (sendMail($email, $subject, $content)) {
    echo json_encode(['success' => true, 'message' => '验证码已发送到您的邮箱']);
} else {
    echo json_encode(['success' => false, 'message' => '邮件发送失败，请稍后再试']);
}