<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;

function Mirai_hideCheckReply($cid, $uid, $attrs, $widget, $index = 0) {
    // 获取主题设置：是否允许游客评论
    $guestAllowed = true;
    try {
        $options = \Widget\Options::widget();
        $guestAllowed = !isset($options->commentsGuestAllowed) || !empty($options->commentsGuestAllowed);
    } catch (Exception $e) {
    } catch (Throwable $e) {
    }

    // 如果不允许游客评论且未登录，返回需要登录
    if (!$guestAllowed && $uid <= 0) {
        return ['allowed' => false, 'reason' => 'not_logged_in'];
    }

    $db = \Typecho\Db::get();

    // 已登录用户：检查是否评论过
    if ($uid > 0) {
        $row = $db->fetchRow($db->select('coid')->from('table.comments')
            ->where('cid = ? AND authorId = ? AND status = ?', $cid, $uid, 'approved')
            ->limit(1));

        if (!empty($row)) {
            return ['allowed' => true];
        }
        return ['allowed' => false, 'reason' => 'not_commented'];
    }

    // 游客：通过 Cookie 判断是否评论过
    $cookieKey = 'mirai_hide_reply_' . $cid;
    if (isset($_COOKIE[$cookieKey]) && $_COOKIE[$cookieKey] === '1') {
        return ['allowed' => true];
    }

    // 游客 Cookie 不存在时，通过 Typecho 记住的邮箱查询数据库
    $rememberMail = '';
    if (class_exists('\Typecho\Cookie')) {
        try {
            $rememberMail = trim((string)\Typecho\Cookie::get('__typecho_remember_mail', ''));
        } catch (Exception $e) {
        }
    }
    if ($rememberMail !== '') {
        $row = $db->fetchRow($db->select('coid')->from('table.comments')
            ->where('cid = ? AND mail = ? AND status = ?', $cid, $rememberMail, 'approved')
            ->limit(1));
        if (!empty($row)) {
            if (PHP_VERSION_ID >= 70300) {
                setcookie($cookieKey, '1', [
                    'expires' => time() + 86400 * 365,
                    'path' => '/',
                    'samesite' => 'Lax'
                ]);
            } else {
                setcookie($cookieKey, '1', time() + 86400 * 365, '/');
            }
            $_COOKIE[$cookieKey] = '1';
            return ['allowed' => true];
        }
    }

    return ['allowed' => false, 'reason' => 'not_commented'];
}
