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

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

            $uid = S::gp('uid', 'P', 2);
            $content = trim(S::gp('message', 'P'));
            $days = S::gp('num', 'P', 2);

            if (empty($uid))
            {
                throw new iSystemException('请输入接受者的UID');
            }
            
            $member = $this->db()->select()->from(Members::table())->where('uid='.$uid)->find(true);
            if (empty($member))
            {
                throw new iSystemException('接受者不存在，请确定UID是否正确');
            }
            if (!$member['verify'])
            {
                throw new iSystemException('未通过短信验证的用户不能接受赠送');
            }
            if ($days > 30 || $days < 1)
            {
                throw new iSystemException('购买天数不能大于30或小于1');
            }
            if (!$iorange['user']['verify'])
            {
                throw new iSystemException('未通过短信验证的用户不能赠送');
            }

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

            $pid = PropertyHandsel::single()->create(array('uid'=>$this->uid(),'getuid'=>$uid,'medalid'=>$medalId,'days'=>$days,'pid'=>10));
            $subject = '[系统消息]获得勋章赠送';
            $content = '书友《'.$this->userName().'》向您赠送勋章，[PropertyHandsel='.$pid.']接受[/PropertyHandsel]|[PropertyHandsel='.$pid.']拒绝[/PropertyHandsel]？'."\n".(!empty($content) ? '附加留言:'.$content : '');
            Members::sendMessage($subject,$content,$this->uid(),$this->userName(),$uid);
            iCredits::single($this->uid(), $this->userName())->consume($money);

            $message[] = '勋章赠送成功';
            $message[] = '返回'.memberLink().'.'.indexLink();
            $this->showMessage($message);
        }
        else
        {
            $this->getController()->render('handsel',array(
                'medal' => $medal,
                'medalId' => $medalId,
            ));
        }
    }
}