<?php

require_once __DIR__ . '/common.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}


if (!rate_limit_cooldown('comment_submit', 5)) {
    http_response_code(429);
    echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>操作太频繁</title></head><body style="margin:0;padding:0;">';
    echo '<p>操作太频繁，请稍后再试。</p>';
    echo '<p><a href="index.php">返回首页</a></p>';
    echo '</body></html>';
    exit;
}

$pdo = db();


if (!csrf_check($_POST['csrf_token'] ?? null)) {
    echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>发表评论失败</title></head><body style="margin:0;padding:0;">';
    echo '<p>请求无效，请刷新页面后重试。</p>';
    echo '<p><a href="index.php">返回首页</a></p>';
    echo '</body></html>';
    exit;
}


if (is_ip_blacklisted()) {
    echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>评论失败</title></head><body style="margin:0;padding:0;">';
    echo '<p>当前 IP 暂时被限制发表评论，如有疑问请联系站长。</p>';
    echo '</body></html>';
    exit;
}

$articleId = isset($_POST['article_id']) ? (int)$_POST['article_id'] : 0;
$parentId  = isset($_POST['parent_id']) ? (int)$_POST['parent_id'] : 0;
$content   = trim((string)($_POST['content'] ?? ''));
$captcha   = (string)($_POST['captcha'] ?? '');
$from      = isset($_POST['from']) ? (string)$_POST['from'] : '';

$redirectUrl = 'index.php';
if ($articleId > 0) {
    if ($from === 'home') {
        
        $redirectUrl = 'index.php?home_id=' . $articleId . '#home-comments';
    } else {
        
        $redirectUrl = 'post.php?id=' . $articleId . '#comments';
    }
}


function comment_error_exit(string $msg, string $redirectUrl): void
{
    echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>发表评论失败</title></head><body style="margin:0;padding:0;">';
    echo '<p>' . h($msg) . '</p>';
    echo '<p><a href="' . h($redirectUrl) . '">返回</a></p>';
    echo '</body></html>';
    exit;
}

if ($articleId <= 0) {
    comment_error_exit('文章不存在。', $redirectUrl);
}




try {
    $stmt = $pdo->prepare("SELECT id, status FROM articles WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $articleId]);
    $article = $stmt->fetch();
    if (!$article || $article['status'] !== 'published') {
        comment_error_exit('文章不存在或尚未发布，不能评论。', $redirectUrl);
    }
} catch (Throwable $e) {
    
    comment_error_exit('系统尚未初始化或出现错误，暂时无法发表评论。', $redirectUrl);
}

if ($content === '') {
    comment_error_exit('评论内容不能为空。', $redirectUrl);
}


if (mb_strlen($content, 'UTF-8') > 1000) {
    comment_error_exit('评论内容过长，请控制在 1000 字以内。', $redirectUrl);
}

$userId  = current_user_id();
$isGuest = $userId ? 0 : 1;


if (!$isGuest) {
    try {
        $stmt = $pdo->prepare("SELECT status, is_comment_banned FROM users WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $userId]);
        $uRow = $stmt->fetch();
        if (!$uRow || $uRow['status'] !== 'active') {
            comment_error_exit('账号状态异常或已被禁用，无法发表评论。', $redirectUrl);
        }
        if (!empty($uRow['is_comment_banned'])) {
            comment_error_exit('你的账号已被禁止评论，如有疑问请联系站长。', $redirectUrl);
        }
    } catch (Throwable $e) {
        
    }
}


if ($isGuest) {
    $captchaKey = 'comment_' . $articleId;
    if (!verify_captcha($captchaKey, $captcha)) {
        comment_error_exit('验证码错误，请返回重新输入。', $redirectUrl);
    }
}


$allowGuest        = get_setting('comment.allow_guest', '1') === '1';
$guestAutoApprove  = get_setting('comment.guest_auto_approve', '0') === '1';
$memberFilter      = get_setting('comment.member_filter_sensitive', '0') === '1';

if ($isGuest && !$allowGuest) {
    comment_error_exit('当前系统设置为不允许匿名评论。', $redirectUrl);
}


if ($isGuest) {
    $status = $guestAutoApprove ? 'approved' : 'pending';
} else {
    
    $status = 'approved';
}


try {
    $words = [];
    $stmt = $pdo->query("SELECT word FROM sensitive_words WHERE is_enabled = 1");
    while ($row = $stmt->fetch()) {
        if (!empty($row['word'])) {
            $words[] = $row['word'];
        }
    }
    foreach ($words as $w) {
        if ($w !== '' && mb_stripos($content, $w, 0, 'UTF-8') !== false) {
            $status = 'pending';
            break;
        }
    }
} catch (Throwable $e) {
    
}


if (!$memberFilter && !$isGuest) {
    
    $status = 'approved';
}


$rootId = null;
$depth  = 0;

if ($parentId > 0) {
    try {
        $stmt = $pdo->prepare("
            SELECT id, parent_id, root_id, depth
            FROM comments
            WHERE id = :pid AND article_id = :aid
            LIMIT 1
        ");
        $stmt->execute([':pid' => $parentId, ':aid' => $articleId]);
        $parent = $stmt->fetch();
        if ($parent) {
            if ($parent['root_id']) {
                $rootId = (int)$parent['root_id'];
            } else {
                $rootId = (int)$parent['id'];
            }
            $depth = (int)$parent['depth'] + 1;
            if ($depth > 12) {
                $depth = 12;
            }
        } else {
            
            $parentId = 0;
        }
    } catch (Throwable $e) {
        $parentId = 0;
        $rootId = null;
        $depth = 0;
    }
}

if ($parentId <= 0) {
    $parentId = null;
    $rootId   = null;
    $depth    = 0;
}


$guestName = null;
if ($isGuest) {
    $prefixes = ['远山', '清风', '夜雨', '木叶', '斜阳', '清晨', '微风', '晚霞'];
    $suffixes = ['行者', '旅人', '过客', '听雨', '看云', '读者', '访客', '星辰'];
    $p = $prefixes[array_rand($prefixes)];
    $s = $suffixes[array_rand($suffixes)];
    $guestName = $p . $s . '（匿名）';
}


try {
    $now = time();
    $ip  = $_SERVER['REMOTE_ADDR'] ?? '';
    $ua  = $_SERVER['HTTP_USER_AGENT'] ?? '';

    $stmt = $pdo->prepare("
        INSERT INTO comments
            (article_id, user_id, is_guest, guest_name,
             parent_id, root_id, depth,
             content, status, like_count, ip, user_agent,
             created_at, updated_at)
        VALUES
            (:article_id, :user_id, :is_guest, :guest_name,
             :parent_id, :root_id, :depth,
             :content, :status, 0, :ip, :user_agent,
             :created_at, :updated_at)
    ");

    $stmt->execute([
        ':article_id' => $articleId,
        ':user_id'    => $isGuest ? null : $userId,
        ':is_guest'   => $isGuest ? 1 : 0,
        ':guest_name' => $guestName,
        ':parent_id'  => $parentId,
        ':root_id'    => $rootId,
        ':depth'      => $depth,
        ':content'    => $content,
        ':status'     => $status,
        ':ip'         => $ip,
        ':user_agent' => $ua,
        ':created_at' => $now,
        ':updated_at' => $now,
    ]);

    
    if ($status === 'approved') {
        try {
            $stmt2 = $pdo->prepare("
                UPDATE articles
                SET comment_count = comment_count + 1
                WHERE id = :id
            ");
            $stmt2->execute([':id' => $articleId]);
        } catch (Throwable $e) {
            
        }
    }
} catch (Throwable $e) {
    comment_error_exit('发表评论失败：' . $e->getMessage(), $redirectUrl);
}


header('Location: ' . $redirectUrl);
exit;

