<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class DedicateAction extends ForumAction
{
    public function run()
    {
        $forum = fetchBookForum($this->id());
        
        $isDedicate = false;
        if ($this->uid())
        {
            $iorange = $this->iorange();
            $iCredit = iCredits::single($this->uid(), $this->userName());
            $moneyField = $iCredit->getMoneyField();
            $money = $iorange['user'][$moneyField];
            $permissions = Members::single()->getPermissions($this->uid());
            $permissions['isdedicate'] && $isDedicate = true;
        }
        
        if (isset($_POST['credit']))
        {
            $credit = max(0, S::gp('credit','P',2));
            $this->getController()->isLogin();

            !$isDedicate && $this->NoPermission();
            if ($credit < 1)
            {
                throw new iSystemException('捐赠的积分必须大于0');
            }
            try
            {
                Members::single()->hasMoney($this->uid(), $credit, $this->userName());
            }
            catch (NotEnoughMoneyException $exce)
            {
                throw new iSystemException('您当前'.setting('creditname').'不足' . $credit . '，不能捐献');
            }
            
            $credit1 = ($this->id() == 13089) ? $credit : $credit * 0.8;
            $iCredit->consume($credit);
            $this->db()->update(BookForum::table())->incrField(array('income'=>$credit1))->where("bookid={$this->id()}")->q();
            
            $logs = '书友' . $this->userName() . '[ID:' . $this->uid() . ']向书会捐献' . $credit . '积分';
            $this->db()->insert(BookManageLog::table())
                 ->value(array('bookid'=>$this->id(),'uid'=>$this->uid(),'username'=>$this->userName(),'message'=>$logs,'createdate'=>date("Y-m-d H:i:s")))
                 ->q();
            
            $message[] = '积分捐献成功';
            $message[] = forumLink($this->id(), '返回书会');
            $this->showMessage($message);
        }
        
        $this->getController()->render('dedicate', array(
                'bookid' => $this->id(),
                'forumInfo' => $this->forumInfo(),
                'forum' => $forum,
                'money' => $money,
                'isDedicate' => $isDedicate,
            )
        );
    }
}