<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class FavoriteThreadAction extends MemberAction
{
    public function run()
    {
        $sort = empty($_GET['sort']) ? 'DESC' : 'ASC';
        $field = S::gp('f', 'G', 2) ? 'f.fid' : 'lastpost';

        if ('delete' == $_GET['do'])
        {
            $id = S::gp('id','G',2);
            if (1 == $_GET['confirm'])
            {
                $this->db()->delete(Ufavorites::table())->where(array('uid'=>$this->uid(),'id'=>$id))->q();
                Ufavorites::single()->updateThreadFavorites($id);
            }
            else
            {
                $message[] = '确定要删除吗？删除后将不可恢复！';
                $message[] = ilink('删除',url('system',array('s'=>'member','c'=>'my','a'=>'ft','do'=>'delete','id'=>$id,'confirm'=>1))).'|'.ilink('取消',url('system',array('s'=>'member','c'=>'my','a'=>'ft')));
                $this->showMessage($message);
            }
        }
        
        $orderBy = ' ORDER BY '.$field . ' ' . $sort;
        $count = $this->db()->getValue('SELECT COUNT(*) AS c FROM '.Ufavorites::table().' WHERE uid = '.S::sqlEscape($this->uid()).' AND type='.S::sqlEscape('thread'));

        $pagination = new iPage();
        $pagination->setPageSize(10);
        $pagination->setTotalRecord($count);
        
        $sql = 'SELECT f.id,t.uid,subject,lastpost,lastpost_user,hits,replies,isdigest,favors FROM '.Ufavorites::table() . ' AS f INNER JOIN '.Threads::table().' AS t ON t.id = f.id WHERE f.uid='.S::sqlEscape($this->uid()).' AND f.type='.S::sqlEscape('thread') . ' ' . $orderBy . S::sqlLimit($pagination->getOffset(),$pagination->getPageSize());
        $threads = $this->db()->setQueryString($sql)->find();
        $floor = $pagination->getFloor();

        $this->getController()->render('ft',array(
                'pagination' => $pagination,
                'floor' => $floor,
                'threads' => $threads,
                'sort' => $sort,
                'field' => $field,
            )
        );
    }
}