<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class VoteAction extends BbsAction
{
    public function run()
    {
        $this->getController()->isLogin();
        $tid = $this->getTid();
        $thread = $this->getExistsThread($tid);
        $permissions = Members::single()->getPermissions($this->uid());
        !$permissions['isvote'] && $this->NoPermission();
        $do = S::gp('do','G');
        
        try
        {
        	$polls = Polls::single()->getOne($tid, $this->uid());
        }
        catch (PollsNotExistsException $exce)
        {
            throw new iSystemException($exce->getMessage());
        }
        if ($polls['havevote'])
        {
            throw new iSystemException('您已经投过票了');
        }
        
        $closeTime = $thread['createdate'] + ($polls['days'] * 24 * 3600);
        if (CTIME > $closeTime)
        {
            throw new iSystemException('该投票已经结束');
        }
        
        $options = unserialize($polls['options']);
        if ('single' == $do)
        {
            $pid = S::gp('pid','G',2);
            if (!key_exists($pid, $options))
            {
                throw new iSystemException('无效的投票选项');
            }
            $options[$pid][1] += 1;
            $this->db()->insert(Voter::table())->value(array('tid'=>$tid,'uid'=>$this->uid(),'username'=>$this->userName(),'vote'=>$pid,'time'=>CTIME))->q();

            $this->_updateVoterCount($tid, $options);

        }
        else if (!empty($_POST))
        {
            $select = array();
            foreach ($_POST as $key => $post)
            {
                if ($post && preg_match('/^option_(\d+)$/i', $key, $match))
                {
                    $pid = $match[1];
                    if (!key_exists($pid, $options))
                    {
                        throw new iSystemException('无效的投票选项');
                    }
                    $select[$pid] = $post;
                    $options[$pid][1] += 1;
                }
            }
            if (empty($select))
            {
                throw new iSystemException('请选择要投的选项');
            }
            if ($polls['max'] < count($select))
            {
                throw new iSystemException('本次投票最多只能选择'.$polls['max'].'项');
            }
            
            foreach ($select as $key => $value)
            {
                $this->db()->insert(Voter::table())->value(array('tid'=>$tid,'uid'=>$this->uid(),'username'=>$this->userName(),'vote'=>$key,'time'=>CTIME))->q();
            }

            $this->_updateVoterCount($tid, $options);
        }
        
        iforward(url('system',array('s'=>'bbs','a'=>'thread','tid'=>$tid)));
    }

    private function _updateVoterCount($tid, $options)
    {
        $sql = 'SELECT COUNT(*) AS c,vote FROM '.Voter::table().' WHERE tid = '.S::sqlEscape($tid).' GROUP BY vote';
        $voters = $this->db()->setQueryString($sql)->find();
        if ($voters)
        {
            $voterCount = 0;
            foreach ($voters as $voter)
            {
                $count = $voter['c'];
                $options[$voter['vote']][1] = $count;
                $voterCount += $count;
            }
            $sql = 'UPDATE '.Polls::table().' SET options='.S::sqlEscape(serialize($options)).',voters = '.S::sqlEscape($voterCount).' WHERE tid='.S::sqlEscape($tid);
            $this->db()->query($sql);
        }
    }
}