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

function Mirai_pointsAddFree($uid, $value, $action, $targetType = null, $targetId = null, $remark = '', $maxCount = 0) {
    if (!$uid || $value <= 0) return ['success' => false, 'msg' => '参数无效'];
    if (!Mirai_pointsEnabled()) return ['success' => false, 'msg' => '积分功能未启用'];
    if (!Mirai_pointsIsAllowFree($uid)) return ['success' => false, 'msg' => '今日免费' . Mirai_pointsName() . '已达上限'];

    if ($targetType && $targetId) {
        $dedup = Mirai_pointsCheckDedup($uid, $targetType, $targetId, 'points_' . $action, $maxCount);
        if (!$dedup['allowed']) {
            return ['success' => false, 'msg' => '已获取过该' . Mirai_pointsName()];
        }
    }

    return Mirai_pointsAdjust($uid, $value, $action, $targetType, $targetId, $remark);
}

function Mirai_pointsOnRegister($uid) {
    $value = Mirai_pointsGetTaskValue('sign_up');
    if ($value <= 0) return;
    Mirai_pointsAddFree($uid, $value, 'sign_up', 'user', $uid, '首次注册', 1);
}

function Mirai_pointsOnLogin($uid) {
    $value = Mirai_pointsGetTaskValue('sign_in');
    if ($value <= 0) return;
    Mirai_pointsAddFree($uid, $value, 'sign_in', 'daily', 0, '每日登录', 1);
}

function Mirai_pointsOnPostPublish($cid, $authorId) {
    $value = Mirai_pointsGetTaskValue('post_new');
    if ($value <= 0) return;
    if (!$authorId) return;
    Mirai_pointsAddFree($authorId, $value, 'post_new', 'post', $cid, '发布文章', 1);
}

function Mirai_pointsOnComment($coid, $authorId, $cid) {
    $value = Mirai_pointsGetTaskValue('comment_new');
    if ($value <= 0) return;
    if (!$authorId) return;
    Mirai_pointsAddFree($authorId, $value, 'comment_new', 'comment', $coid, '发表评论', 1);
}

function Mirai_pointsOnLike($cid, $postAuthorId, $operatorUid) {
    $value = Mirai_pointsGetTaskValue('post_like');
    if ($value <= 0) return;
    if (!$postAuthorId || $operatorUid == $postAuthorId) return;
    Mirai_pointsAddFree($postAuthorId, $value, 'post_like', 'post', $cid, '文章获赞', 5);
}

function Mirai_pointsOnCollect($cid, $postAuthorId, $operatorUid) {
    $value = Mirai_pointsGetTaskValue('post_collect');
    if ($value <= 0) return;
    if (!$postAuthorId || $operatorUid == $postAuthorId) return;
    Mirai_pointsAddFree($postAuthorId, $value, 'post_collect', 'post', $cid, '文章被收藏', 5);
}
