<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class BookVote extends Model
{
	public static function single($className = __CLASS__)
	{
		return parent::single($className);
	}
	
	public static function table()
	{
		return 'ig_bookvote';
	}
	
	public static function optionTable()
	{
		return 'ig_bookvoteoption';
	}

	public function find($voteId, $options = false)
	{
		$vote = $this->_db->select()->from(self::table())->where(array('id'=>$voteId))->find(true);
		if (empty($vote))
		{
			return null;
		}
		
		if ($options)
		{
            $vote['options'] = $this->getOptions($voteId);
		}
		
		return $vote;
	}

    public function getOptions($voteId)
    {
        $options = $this->_db->select()->from(self::optionTable())->where(array('voteid'=>$voteId))->find();
        
		return $options;
    }

    public function getOption($optionId)
    {
        $option = $this->_db->select()->from(self::optionTable())->where(array('id'=>$optionId))->find(true);
        
        return $option;
    }

	public function update($voteId, $data)
	{
		$table = self::table();
		$sql = "UPDATE `$table` SET ";
		foreach ($data as $key => $value)
		{
			$update[] = self::getEscapeString($key, $value);
		}
		$sql .= implode(',', $update) . " WHERE `id` = $voteId";
		$this->_db->query($sql);
	}

	public function addVotes($optionId)
	{
		$this->_db->update(self::optionTable())->incrField(array('votes'=>1))->where(array('id'=>$optionId))->q();
	}
}
