<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class BuyAction extends ForumAction
{
    public function run()
    {
        $postId = S::gp('cid','G',2);
        $url = url('system',array('s'=>'forum','c'=>'advance','a'=>'read','id'=>$this->id(),'cid'=>$postId));
        
        $thread = BookPostReply::single()->getThread($postId);
        if (empty($thread))
        {
            throw new iSystemException('不存在的主题');
        }
        if (!$thread['price'])
        {
            iforward($url);
        }
        if (in_array($this->uid(), explode(',', $thread['buyer'])))
        {
            throw new iSystemException('请不要重复购买');
        }
        try
        {
            Members::single()->hasMoney($this->uid(), $thread['price'], $this->userName());
        }
        catch (NotEnoughMoneyException $exce)
        {
            throw new iSystemException($exce->getMessage());
        }
    
        $creditObj = iCredits::single($this->uid(), $this->userName());
        $creditObj->consume($thread['price']);
    
        $creditObj->setUid($thread['uid']);
        $creditObj->setUserName($thread['username']);
        $creditObj->addMoney($thread['price']);
    
        $subject = '[系统消息]有书友购买了您的收费贴';
        $message = '书友'.$this->uid().'购买了您发的收费贴《'.$thread['subject'].'》';
        Members::sendMessage($subject, $message, 1, 'admin', $thread['uid']);
        
        $buyers = $thread['buyer'] . ','.$this->uid();
        $this->db()->update(BookPostReply::table())->value(array('buyer'=>$buyers))->where(array('postid'=>$postId,'isfirst'=>1))->q();
        iforward($url);
    }
}