<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class CreditAction extends ForumAction
{
    public function run()
    {
        $this->isManager();
        $forum = fetchBookForum($this->id());
        if (empty($forum))
        {
            throw new iSystemException('不存在的书会');
        }
        if (!$forum['income'] || 0 > $forum['income'])
        {
            throw new iSystemException('当前书会已破产');
        }
        
        $forumLevel = $this->forumLevel($this->level());
        if (!$forumLevel['iscredit'])
        {
            throw new iSystemException('当前书会等级不够，不能发分');
        }
        
        $todayForumCredits = BookCreditsLog::single()->todayForumCredits($this->id());
        $levelMap = BookForum::levelMap($this->level());
        $creditSet = $levelMap['credits'];
        $today = $creditSet > $todayForumCredits ? $creditSet - $todayForumCredits : 0;
        $today = $today > $forum['income'] ? $forum['income'] : $today; 
        
        if (!$today)
        {
            throw new iSystemException('今日书会可单独操作的积分已经用完');
        }
        
        if (isset($_POST['credit']))
        {
            $credit = S::gp('credit','P',2);
            if ($credit < 0)
            {
                throw new iSystemException('奖励的积分必须大于0');
            }
            if ($forum['income'] <= $credit)
            {
                throw new iSystemException('书会积分不足，不能发放');
            }
            if ($credit > $today)
            {
                throw new iSystemException('今日所剩积分为'.$today);
            }
            
            $type = S::gp('type','P');
            $m = S::gp('member','P');
            $where = '';
            switch ($type)
            {
                case 'username':
                    $where = 'm.username='.S::sqlEscape($m);
                    break;
                case 'uid':
                    $where = 'm.uid='.S::sqlEscape(intval($m));
                    break;
                default:
                    $where = 'm.uid='.S::sqlEscape(intval($m));
            }
            
            $sql = 'SELECT m.*, mf.* FROM '.Members::table().' m
                    LEFT JOIN '.Memberfields::table().' mf ON mf.uid=m.uid
                    LEFT JOIN '.UserGroups::table().' u ON u.groupid=m.groupid
                    WHERE '.$where;
            $member = $this->db()->setQueryString($sql)->find(true);
            if(!$member) 
            {
                throw new iSystemException('用户不存在');
            }
            if ($this->uid() === $member['uid'])
            {
                throw new iSystemException('书管不能给自己加积分');
            }
            
            $permissions = Members::single()->getPermissions($member['uid']);
            if (!$permissions['isforumcredit'])
            {
                throw new iSystemException('当前用户的等级组不能获得书会发分');
            }
            
            $creditLimit = $permissions['forumcreditlimit'];
            if (BookForum::single()->isMember($this->id(), $member['uid']))
            {
                if ($creditLimit && $forumLevel['mcreditlimit'] && $creditLimit < $forumLevel['mcreditlimit'])
                {
                    $creditLimit = $forumLevel['mcreditlimit'];
                }
            }
            
            $icredit = iCredits::single($member['uid'], $member['username']);
            if ($creditLimit)
            {
                $todayCredit = $icredit->todayCredit($this->id());
                if ($todayCredit && $todayCredit >= $creditLimit || ($todayCredit + $credit > $creditLimit) || $credit > $creditLimit)
                {
                    throw new iSystemException('已经超过当前用户组日最大书会发分数');
                }
            }
            $icredit->addMoney($credit);
            
            $this->db()->insert(BookCreditsLog::table())->value(array('date'=>CDATE,'createdate'=>CDATETIME,'bid'=>$this->id(),'uid'=>$member['uid'],'username'=>$member['username'],'operater_id'=>$this->uid(),'operater'=>$this->userName(),'credit'=>$credit))->q();
            $this->db()->update(BookForum::table())->decrField(array('income'=>$credit))->where(array('bookid'=>$this->id()))->q();
 
            $logData = array(
                'uid' => $member['uid'],
                'ouid' => $this->uid(),
                'bookid' => $this->id(),
                'type' => 'CreditMember',
                'credit' => $credit,
                'message' => '书友[uid='.$member['uid'].']被[uid='.$this->uid().']奖励'.$credit.setting('creditname'),
            );
            BookManageLog::single()->create($logData);

            updateBookForum($this->id());

            $message[] = '积分奖励成功';
            $message[] = '返回'.ilink('管理',url('system',array('s'=>'forum','c'=>'manage','id'=>$this->id()))).'.'.forumLink($this->id());
            $this->showMessage($message);
        }
        
        $uid = isset($_GET['uid']) ? S::gp('uid','G',2) : '';
        $this->getController()->render('credit', array(
                'bookid' => $this->id(),
                'forum' => $forum,
                'uid' => $uid,
                'today' => $today,
            )
        );
    }
}