<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class FavoriteAction extends MemberAction
{
    public function run()
    {
        $fTable = Favorites::table();
        $bTable = Book::table();
        
        if ('down' == $_GET['do'])
        {
            $bid = S::gp('bid','G',2);
            if (1 == $_GET['confirm'])
            {
                $this->db()->delete($fTable)->where(array('memberid'=>$this->uid(),'bid'=>$bid))->q();
                Book::single()->updateFavorites($bid);
            }
            else
            {
                $message[] = '确定要删除吗？删除后将不可恢复！';
                $message[] = ilink('删除',url('system',array('s'=>'member','c'=>'my','a'=>'favorite','do'=>'down','bid'=>$bid,'confirm'=>1))).'|'.ilink('取消',url('system',array('s'=>'member','c'=>'my','a'=>'favorite')));
                $this->showMessage($message);
            }
        }
        
        $count = $this->db()->getValue('SELECT COUNT(*) FROM '.$fTable.' WHERE memberid = '.$this->uid());
        $pageObj = new iPage();
        $pageObj->setPageSize(10);
        $pageObj->setTotalRecord($count);
        
        $offset = $pageObj->getOffset();
        $sql = 'SELECT bid FROM '.$fTable.' WHERE memberid = '.$this->uid().' ORDER BY favoritesid DESC LIMIT '.$pageObj->getOffset().','.$pageObj->getPageSize();
        $result = $this->db()->setQueryString($sql)->find();
        $ids = array();
        if (!empty($result))
        {
            foreach ($result as $item)
            {
                $ids[] = $item['bid'];
            }
        
            $sql = 'SELECT bookid,typeid,bookname,lastchapterid,lastchaptername,updatedate,author,status FROM '.$bTable.' WHERE bookid IN ('.implode(',', $ids).') ';
            $favorites = $this->db()->setQueryString($sql)->find();
        }
        
        $floor = $pageObj->getFloor();
        
        $this->getController()->render('favorite',array(
                'favorites' => $favorites,
                'pageObj' => $pageObj,
                'floor' => $floor,
                'count' => $count,
            )
        );
    }
}