<?php

class umengApi {
	// The host
	protected $host = "http://msg.umeng.com";

	// The upload path
	protected $uploadPath = "/upload";

	// The post path
	protected $postPath = "";

	// The app master secret
	protected $appMasterSecret = NULL;

	/*
	 * $data is designed to construct the json string for POST request. Note:
	 * 1)The key/value pairs in comments are optional.  
	 * 2)The value for key 'payload' is set in the subclass(AndroidNotification or IOSNotification), as their payload structures are different.
	 */ 
	protected $data = array(
			"appkey"           => NULL,
			"timestamp"        => NULL,
			"type"             => NULL,
			"production_mode"  => "true",
	);

	function __construct($appkey, $secret) {
		$this->data['appkey'] = $appkey;
		$this->data['timestamp'] = strval(time());
		$this->appMasterSecret = $secret;
	}
	
	// Set key/value for $data array, for the keys which can be set please see $DATA_KEYS, $PAYLOAD_KEYS, $BODY_KEYS, $POLICY_KEYS
	public function setPredefinedKeyValue($key, $value)
	{
		$this->data[$key] = $value;
	}

	//send the notification to umeng, return response data if SUCCESS , otherwise throw Exception with details.
	function get($postPath) {
		$this->postPath = $postPath;
        $url = $this->host . $this->postPath;
        $postBody = json_encode($this->data);
        $sign = md5("POST" . $url . $postBody . $this->appMasterSecret);
        $url = $url . "?sign=" . $sign;
  		$ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody );
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlErrNo = curl_errno($ch);
        $curlErr = curl_error($ch);
        curl_close($ch);
        if ($httpCode == "0") {
			return ["status"=>false, "data"=>$curlErr, "code"=>$curlErrNo];
        } else if ($httpCode != "200") {
			return ["status"=>false, "data"=>$result, "code"=>$httpCode];
        } else {
			$res = json_decode($result, true);
			if(!empty($res['ret']) && $res['ret'] == 'SUCCESS')
			{
				return ["status"=>true, "data"=>$res['data']];
			}
			else
			{
				return ["status"=>false, "data"=>$res['data']['error_msg'], "code"=>$res['data']['error_code']];
			}	
        }
    }
	
}