<?php

namespace MzPush;
class Application
{
    private $appid;
    private $appkey;
    private $appsecret;


    public function __construct()
    {
        $this->appid = \pushConfig::MZ_APP_ID;
        $this->appkey = \pushConfig::MZ_APP_KEY;
        $this->appsecret = \pushConfig::MZ_APP_SECRET;

    }

    public function pushTag($title,$content,$tag){
        $url = "http://server-api-push.meizu.com/garcia/api/server/push/pushTask/pushToTag";
        $header[] = "Content-Type:application/x-www-form-urlencoded;charset=UTF-8";
        $data['appId'] = $this->appid;
        //$data['pushIds'] = "18606715209";
        $data['pushType'] = 0;
        $data['tagNames'] = $tag;
        $data['scope'] = 0;
        $data['messageJson'] = json_encode([
            'noticeBarInfo' =>[
                'title' => $title,
                'content' =>$content,

            ],
            'pushTimeInfo' =>[
                'offLine' =>1,
                'validTime' =>24
            ]

        ]);

        $data['sign'] = $this->getSign($data);
        return   $res = $this->curl_https_post($url,http_build_query($data),$header);


    }

    private function curl_https_post($url, $data = array(), $header = array())
    {

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // check verify
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_POST, 1); // regular post request
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Post submit data

        $ret = @curl_exec($ch);
        if ($ret === false) {
            return null;
        }
        curl_close($ch);
        return $ret;
    }


    //生成签名
    public function getSign($data){

        ksort($data); //字典序排序
        $sign = '';
        foreach($data as $k =>$v){
            $sign.=$k."=".$v;
        }
        return md5($sign.$this->appsecret);


    }


}