<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class BuyAction extends BaseAction
{
    public function run()
    {
        $medalId = S::gp('id', 'G', 2);
        $do = S::gp('do', 'G', 2);
        $medalObj = Medals::single();
        $medal = $medalObj->getOne($medalId);
        if (empty($medal))
        {
            throw new iSystemException('不存在的勋章');
        }

        if ($this->uid() && 1 != $do)
        {
            $this->getController()->hasMedal($this->uid(), 'medal2', $medalId);
        }

        if (isset($_POST['num']))
        {
            $this->getController()->isLogin();

            $property = $this->getController()->getProp('medal2');
            $iorange = $this->iorange();
            $days = S::gp('num', 'P', 2);
            if ($days > 30 || $days < 1)
            {
                throw new iSystemException('购买天数不能大于30或小于1');
            }
            if (!$iorange['user']['verify'])
            {
                throw new iSystemException('未通过短信验证的用户不能购买');
            }

            $money = $medalObj->getPrice() * $days;
            $this->getController()->hasMoney($this->uid(),$this->userName(),$money);
            iCredits::single($this->uid(), $this->userName())->consume($money);

            $expireTime = CTIME + ($days * 24 * 3600);
            if (false !== ($prop = $this->getController()->hasPropMemberLog($this->uid(), 'medal2')))
            {
                $option = unserialize($prop['option']);
                $option['expire'] = $expireTime = CTIME > $option['expire'] ? $expireTime : $option['expire'] + $days * 24 * 3600;
                $this->getController()->updatePropMemberLog($this->uid(), $this->userName(), $property['propertyid'], serialize($option));
            }
            else
            {
                $this->getController()->createPropMemberLog($this->uid(),$this->userName(), $property['propertyid'], serialize(array('class'=>2,'expire'=>$expireTime)));
            }
            $this->db()->update(Memberfields::table())->value(array('medals'=>$medalId.'|'.$expireTime))->where('uid='.$this->uid())->q();

            $data = array(
                'uid' => $this->uid(),
                'username' => $this->userName(),
                'amount' => $days,
                'price' => $money,
            );
            PropertyLog::single()->create($property['propertyid'],$data);

            Members::single()->updateOneCache($this->uid());
            $message[] = '购买成功';
            $message[] = '返回'.memberLink().'.'.indexLink();
            $this->showMessage($message);
        }
        else
        {
            $this->getController()->render('buy',array(
                'medal' => $medal,
                'do' => $do,
                'medalId' => $medalId,
            ));
        }
    }
}