<?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;
}

$post_id = sanitizeInput($_POST['post_id'] ?? '');
$nickname = sanitizeInput($_POST['nickname'] ?? '');
$content = sanitizeInput($_POST['content'] ?? '');
$email = sanitizeInput($_POST['email'] ?? '');
$verification_code = sanitizeInput($_POST['verification_code'] ?? '');

if (empty($post_id) || empty($nickname) || empty($content)) {
    http_response_code(400);
    echo json_encode(['error' => '请填写完整信息']);
    exit;
}

$settings = getSettings();

// 检查是否需要邮箱验证
if ($settings['comment']['require_email_verification']) {
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo json_encode(['error' => '请输入有效的邮箱地址']);
        exit;
    }
    
    if (empty($verification_code)) {
        http_response_code(400);
        echo json_encode(['error' => '请输入验证码']);
        exit;
    }
    
    if (!verifyCode($email, $verification_code)) {
        http_response_code(400);
        echo json_encode(['error' => '验证码错误或已过期']);
        exit;
    }
}

if (addComment($post_id, $nickname, $content, $email)) {
    echo json_encode(['success' => true, 'message' => '评论提交成功' . ($settings['comment']['auto_approve'] ? '' : '，等待审核')]);
} else {
    http_response_code(500);
    echo json_encode(['error' => '评论提交失败']);
}
?>
