<?php

/**
 * Yeepay 响应类
 *
 * @author Jeffrey
 * @version $Id: Response.php 42 2010-01-28 16:11:55Z jeffrey $
 */
abstract class Yeepay_Response
{
    /**
     * 签名字段和顺序
     *
     * @var Array
     */
    protected static $hashMap = array(
        'p0_Cmd' => 'command',
    );

    /**
     * 业务类型
     *
     * @var string(20)
     */
    protected $command;

    /**
     * 商户编号
     *
     * @var string(11)
     */
    protected $merchantId;

    /**
     * Yeepay 对象
     *
     * @var Yeepay
     */
    protected $yeepay;

    public function __construct(Yeepay $yeepay, Array $data)
    {
        $this->yeepay = $yeepay;
        $this->merchantId = $yeepay->getMerchantId();
        $this->setFromArray($data);
    }

    /**
     * 获取当前请求的 HMAC-MD5 信息
     *
     * @return string
     */
    public function getHmac()
    {
        return $this->yeepay->getHmac($this->getHashString());
    }

    /**
     * 使用数组对属性进行赋值
     *
     * @param Array $data
     */
    protected function setFromArray(Array $data)
    {
        $class = get_class($this);
        foreach ($data as $key => $value)
        {
            if (key_exists($key, $class::$hashMap))
            {
                $k = $class::$hashMap[$key];
                $this->$k = $value;
            }
        }
    }

    /**
     * 检验订单返回情况
     * @return void
     */
    public function verify()
    {
        $this->verifyHmac();
        
        if (11 == $this->code)
        {
            throw new Yeepay_Exception('充值订单重复了，这可能是系统过于繁忙的缘故，请返回重试');
        }
        else if (2 == $this->code)
        {
            throw new Yeepay_Exception('您的卡已经被使用过，不能再用');
        }
        else if (66 == $this->code)
        {
            throw new Yeepay_Exception('支付金额有误');
        }
        else if (-1 == $this->code)
        {
            throw new Yeepay_Exception('系统出错了，支付签名有误，请马上联系网站管理人员解决');
        }
    }

    /**
     * 检验订单签名
     * @throws Yeepay_Exception
     * @return void
     */
    public function verifyHmac()
    {
        if ($this->hmac != $this->getHmac())
        {
            throw new Yeepay_Exception('不正确的签名数据，请确认你是否从本站进行的订单提交');
        }
    }
    
    /**
     * 获取签名属性字符串
     * @return string
     */
    protected function getHashString()
    {
        $class = get_class($this);
        $result = '';

        foreach ($class::$hashMap as $key => $property)
        {
            if ('hmac' != $key)
            {
                $value = $this->$property;
                // 参数为null需要转换成空
                if (is_null($value))
                {
                    $value = "";
                }
                $result .= iconv('UTF-8', 'GBK', $value);
            }
        }

        return $result;
    }
}