<?php
/**
 * 发送验证码 API
 * 请求方式：POST
 * 参数：email, type (register/login)
 */

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

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

// 只接受 POST 请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => '请求方式错误']);
    exit;
}

// 获取参数
$email = trim($_POST['email'] ?? '');
$type = trim($_POST['type'] ?? 'register');

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

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

// 验证类型
if (!in_array($type, ['register', 'login'])) {
    echo json_encode(['success' => false, 'message' => '验证码类型错误']);
    exit;
}

// 防刷：检查发送频率（60秒内只能发送一次）
$lastRecord = $db->fetchOne("SELECT created_at FROM email_verify_codes WHERE email = '$email' AND type = '$type' 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;
    }
}

// 发送验证码
if ($type === 'register') {
    $result = sendRegisterCode($email);
} else {
    $result = sendLoginCode($email);
}

echo json_encode($result);
?>