<?php
declare(strict_types=1);

/**
 * /functional/comment/create.php
 * Єдиний endpoint створення коментаря.
 */

require_once dirname(__DIR__, 2) . '/includes/start.php';
require_once __DIR__ . '/_lib.php';
require_once dirname(__DIR__, 2) . '/includes/security_antispam.php';

$__ntfLib = dirname(__DIR__) . '/notifications/_lib.php';
if (is_file($__ntfLib)) {
    require_once $__ntfLib;
}
unset($__ntfLib);

if (!function_exists('comment_create_t')) {
    function comment_create_t(string $uk, string $ru, string $en): string
    {
        $lang = function_exists('lang') ? (string)lang() : (string)($_SESSION['lang'] ?? 'uk');
        if (!in_array($lang, ['uk', 'ru', 'en'], true)) {
            $lang = 'uk';
        }

        return match ($lang) {
            'ru' => $ru,
            'en' => $en,
            default => $uk,
        };
    }
}

if (!function_exists('comment_create_notification_url')) {
    function comment_create_notification_url(string $back, int $commentId): string
    {
        $back = comment_safe_back_url($back);
        if ($back === '') $back = '/';
        if ($commentId <= 0) return $back;

        if (str_contains($back, '#')) {
            return $back;
        }

        return $back . '#comment-' . $commentId;
    }
}

if (!function_exists('redirect')) {
    function redirect(string $to): never
    {
        header('Location: ' . $to);
        exit;
    }
}

if (!function_exists('flash_set')) {
    function flash_set(string $key, string $msg): void
    {
        $_SESSION['flash'][$key] = $msg;
    }
}

if (!function_exists('csrf_check')) {
    function csrf_check(?string $token): bool
    {
        if (function_exists('vm_csrf_check')) {
            try {
                return (bool)vm_csrf_check((string)$token);
            } catch (Throwable $e) {
            }
        }
        if (empty($_SESSION['csrf_token'])) return false;
        return hash_equals((string)$_SESSION['csrf_token'], (string)$token);
    }
}

if (!function_exists('is_post')) {
    function is_post(): bool
    {
        return strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) === 'POST';
    }
}

if (!headers_sent()) {
    header('X-Robots-Tag: noindex, nofollow, noarchive', true);
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0', true);
}

require_login();

$pdo = isset($pdo) && $pdo instanceof PDO ? $pdo : db();
$me  = isset($me) && is_array($me) ? $me : current_user();
$meId = (int)($me['id'] ?? 0);

$back = comment_safe_back_url((string)($_POST['back'] ?? ($_SERVER['HTTP_REFERER'] ?? '/')));
if ($back === '') {
    $back = '/';
}

if (!is_post()) {
    http_response_code(405);
    echo 'Method Not Allowed';
    exit;
}

$csrf = (string)($_POST['csrf'] ?? $_POST['csrf_token'] ?? '');
if (!csrf_check($csrf)) {
    flash_set(
        'err',
        function_exists('t')
            ? (string)t('bad_csrf')
            : comment_create_t('Невірний CSRF токен.', 'Неверный CSRF токен.', 'Invalid CSRF token.')
    );
    redirect($back);
}

$commentRestrictionState = function_exists('ar_get_state') ? ar_get_state($pdo, $meId) : [];
if (is_array($commentRestrictionState) && function_exists('ar_is_action_blocked') && ar_is_action_blocked($commentRestrictionState, 'comments')) {
    flash_set(
        'err',
        function_exists('ar_action_error')
            ? ar_action_error($commentRestrictionState, 'comments')
            : comment_create_t('Вам тимчасово заборонено писати коментарі.', 'Вам временно запрещено писать комментарии.', 'You are temporarily not allowed to comment.')
    );
    redirect($back);
}

$postId = (int)($_POST['post_id'] ?? $_POST['comment_post_id'] ?? 0);

$parentRaw = $_POST['parent_id'] ?? $_POST['reply_to_comment_id'] ?? null;
$parentId = null;
if ($parentRaw !== null && $parentRaw !== '' && is_numeric((string)$parentRaw)) {
    $parentId = (int)$parentRaw;
    if ($parentId <= 0) {
        $parentId = null;
    }
}

$body = comment_normalize_text((string)($_POST['body'] ?? $_POST['comment'] ?? ''));

$uploadField = null;
foreach (['attachments', 'files', 'comment_files'] as $field) {
    if (isset($_FILES[$field])) {
        $uploadField = $field;
        break;
    }
}

$username = (string)($me['username'] ?? ('user_' . (int)($me['id'] ?? 0)));

try {
    $uploadedRows = $uploadField !== null
        ? comment_handle_uploads($_FILES[$uploadField], $username)
        : [];

    $commentId = comment_create_core($pdo, $me, $postId, $body, $parentId, $uploadedRows);

    if ($commentId > 0 && function_exists('ntf_dispatch_comment_reply') && function_exists('ntf_dispatch_post_comment')) {
        try {
            $eventUrl = comment_create_notification_url($back, $commentId);

            $postRow = comment_find_post($pdo, $postId);
            $postOwnerId = (int)($postRow['user_id'] ?? 0);

            $parentAuthorId = 0;
            if ($parentId !== null && $parentId > 0 && function_exists('ntf_get_comment_brief')) {
                $parentRow = ntf_get_comment_brief($pdo, $parentId);
                $parentAuthorId = (int)($parentRow['user_id'] ?? 0);
            }

            if ($parentAuthorId > 0 && $parentAuthorId !== $meId) {
                ntf_dispatch_comment_reply($pdo, $commentId, (int)$parentId, $meId, $parentAuthorId, $eventUrl);
            }

            if ($postOwnerId > 0 && $postOwnerId !== $meId && $postOwnerId !== $parentAuthorId) {
                ntf_dispatch_post_comment($pdo, $commentId, $postId, $meId, $postOwnerId, $eventUrl);
            }
        } catch (Throwable $e) {
            error_log('comment/create.php notification error: ' . $e->getMessage());
        }
    }

    try {
        $flag = antispam_evaluate_content($pdo, $meId, 'comment', $body);
        if ($flag) {
            antispam_flag_user(
                $pdo,
                $meId,
                (string)($flag['status'] ?? 'bot'),
                (string)($flag['reason_code'] ?? 'comment_rule'),
                (string)($flag['reason_text'] ?? 'Антиспам: підозрілий коментар'),
                is_array($flag['details'] ?? null) ? $flag['details'] : [],
                null,
                false
            );
        }
    } catch (Throwable $e) {
        error_log('comment/create.php antispam error: ' . $e->getMessage());
    }

    flash_set(
        'ok',
        comment_create_t('Коментар додано.', 'Комментарий добавлен.', 'Comment added.')
    );
    redirect($back);
} catch (Throwable $e) {
    $msg = trim($e->getMessage());
    if ($msg === '') {
        $msg = comment_create_t(
            'Не вдалося додати коментар.',
            'Не удалось добавить комментарий.',
            'Failed to add comment.'
        );
    }

    flash_set('err', $msg);
    redirect($back);
}
