<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class BuyChapterAction extends MemberAction
{
    public function run()
    {
        $bookId = S::gp('bid', 'G', 2);
        $chapterId = S::gp('cid', 'G', 2);
        $book = fetchBookInfo($bookId);
        if (empty($book))
        {
            throw new iSystemException('不存在的小说');
        }
        $chapter = Chapter::single()->getOne($chapterId);
        if (empty($chapter))
        {
            throw new iSystemException('不存在的章节');
        }
        if (!$chapter['isvip'])
        {
            iexit('非VIP章节，不能订阅！');
        }
        
        $iChapterOrder = new iChapterOrder($bookId);
        $money = $iChapterOrder->getPrice($chapter['size']);
        try
        {
            Members::single()->hasMoney($this->uid(), $money);
        }
        catch (NotEnoughMoneyException $exce)
        {
            throw new iSystemException($exce->getMessage());
        }
        iCredits::single($this->uid(), $this->userName())->consume($money);
        $this->db()->insert($iChapterOrder->getTable())->value(array('uid'=>$this->uid(),'bid'=>$bookId,'cid'=>$chapterId,'date'=>CDATE,'createdate'=>CTIME,'price'=>$money))->q();
        
        iforward(url('read', array('bid'=>$bookId,'cid'=>$chapterId)));
    }
}