<?php
// 不需要再次启动会话，因为主index.php已经启动了
// session_start();
require_once '../config/config.php';
require_once '../includes/functions.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => '方法不允许']);
    exit;
}

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

if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['error' => '请输入有效的邮箱地址']);
    exit;
}

$settings = getSettings();

// 检查是否需要邮箱验证
if (!$settings['comment']['require_email_verification']) {
    echo json_encode(['success' => true, 'message' => '无需验证']);
    exit;
}

// 生成验证码
$code = generateVerificationCode($settings['comment']['verification_code_length']);

// 保存验证码
if (!saveVerificationCode($email, $code)) {
    http_response_code(500);
    echo json_encode(['error' => '验证码生成失败']);
    exit;
}

// 发送邮件
if (sendVerificationEmail($email, $code)) {
    echo json_encode(['success' => true, 'message' => '验证码已发送到您的邮箱']);
} else {
    http_response_code(500);
    echo json_encode(['error' => '邮件发送失败，请检查邮件配置']);
}
?>