<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/21
 * Time: 17:39
 */

include_once (WWWROOT.'/vendor/autoload.php');
use sngrl\PhpFirebaseCloudMessaging\Client;
use sngrl\PhpFirebaseCloudMessaging\Message;
use sngrl\PhpFirebaseCloudMessaging\Recipient\Device;
use sngrl\PhpFirebaseCloudMessaging\Notification;
use sngrl\PhpFirebaseCloudMessaging\Recipient\Topic;

class ModelFirebase
{
    private $_server_key = [
        'AAAAwSTdJJQ:APA91bGHYd9LFuSfFZ7gPm5lbAvdb-1xoW4h4l1vbRMcn3aB7u8OhIXIWgLw58xZpuSINmmb_4v0ZkZZ2cO7lwKMu_kDuliTP8I1PovhSD4LSiUv4toAqnHFt60pGGbJ30z1-3Vi3a1X', // crazy Spin
        'AAAAUHHAsMY:APA91bFYCxoaTb0J0XW2hNsWD6gLVn0UwXncw-gr4Ww8_Mh1LJbarOAhRWGR14WAEWE_MyCfOonUnE1bl-qA0nOTux_b2L-n00h-Vg_tpZGx-bBl85FG6g5LnOUtxba9pNc8Tse_Igje', // crazy Coin
    ];

    /**
     * 设置API秘钥
     * @param $key
     * Created by: Owen
     * Created on: 2020/5/23 15:08
     */
    public function setServerKey($key){
        $this->_server_key = $key;
    }

    /**
     * 通过设备发送推送
     * @param $token
     * @param $title
     * @param $body
     * @param array $dataVal
     * @param int $sid // ios 推送应用 OS only, will add smal red bubbles indicating the number of notifications to your apps icon
     * @return bool
     */
    public function sendToDevice($token, $title, $body, $dataVal = [],$sid = 1){
        if(empty($token)){
            return false;
        }
        if(empty($dataVal)){
            $dataVal = [];
        }
        $flag = true;
        foreach ($this->_server_key as $serKey){
            $client = new Client();
            $client->setApiKey($serKey);
            $client->injectGuzzleHttpClient(new \GuzzleHttp\Client());
            $message = new Message();
            $message->setPriority('high');
            $message->addRecipient(new Device($token));
            $notification = new Notification($title, $body);
            $sid == 2 && $notification->setBadge(1);
            $message->setNotification($notification)->setData($dataVal);
            $response = $client->send($message);
            if($response->getStatusCode() != 200){
                $flag = false;
            }
        }
        return $flag;
    }


    /**
     * 通过主题发送推送
     * @param $topic
     * @param $title
     * @param $body
     * @param array $dataVal
     * @return bool
     * Created by: Owen
     * Created on: 2020/3/3 11:26
     */
    public function sendToTopic($topic, $title, $body, $dataVal = []){
        if(empty($topic) || empty($body)){
            return false;
        }
        $flag = true;
        foreach ($this->_server_key as $serverKey){
            $client = new Client();
            $client->setApiKey($serverKey);
            $client->injectGuzzleHttpClient(new \GuzzleHttp\Client());
            $message = new Message();
            $message->setPriority('high');
            $message->addRecipient(new Topic($topic));
            $message->setNotification(new Notification($title, $body))->setData($dataVal);
            $response = $client->send($message);
            if($response->getStatusCode() != 200){
                $flag = false;
            }
        }
        return $flag;
    }


    /**
     * 订阅主题
     * @param $topic
     * @param $tokenList
     * @return bool
     */
    public function subscribeTopic($topic, $tokenList){
        if(!is_array($tokenList)){
            $tokenList = array($tokenList);
        }
        if(empty($tokenList)){
            return false;
        }
        $flag = true;
        foreach ($this->_server_key as $serverKey){
            $client = new Client();
            $client->setApiKey($serverKey);
            $client->injectGuzzleHttpClient(new \GuzzleHttp\Client());
            $response = $client->addTopicSubscription($topic, $tokenList);
            if($response->getStatusCode() != 200){
                $flag = false;
            }
        }
        return $flag;
    }

    /**
     * 取消订阅
     * @param $topic
     * @param $tokenList
     * @return bool
     * Created by: Owen
     * Created on: 2020/3/3 11:36
     */
    public function removeSubscribeTopic($topic, $tokenList){
        if(!is_array($tokenList)){
            $tokenList = array($tokenList);
        }
        if(empty($tokenList)){
            return false;
        }
        $flag = true;
        foreach ($this->_server_key as $serverKey){
            $client = new Client();
            $client->setApiKey($serverKey);
            $client->injectGuzzleHttpClient(new \GuzzleHttp\Client());
            $response = $client->removeTopicSubscription($topic, $tokenList);
            if($response->getStatusCode() != 200){
                $flag =  false;
            }
        }
        return $flag;
    }

    /**
     * 刷新用户语言主题订阅 -- 多人
     * @param $uidList
     * @return bool
     * Created by: Owen
     * Created on: 2020/3/3 11:35
     */
    public function refreshUsersTopicByLang($uidList){
        if(empty($uidList)){
            return false;
        }
        if(!is_array($uidList)){
            $uidList = [$uidList];
        }
        $userDataList = oo::commonOprModel('push')->getPushMultByUids($uidList);
        $langCommonKey = okeys::FireBaseTopic();
        $cancelTopic    = [];
        $subscribeTopic = [];
        foreach ($userDataList as $user=>$row){
            $curLangTopic = okeys::FireBaseTopic($row['lang']);
            if(!empty($row['topic'])){
                $topics = explode(',',$row['topic']);
                $flag = false;
                foreach ($topics as $key=>$topic){
                    if(strpos($topic,$langCommonKey) !== false && $topic != $curLangTopic){
                        unset($topics[$key]);
                        $cancelTopic[$topic][] = $row['token'];
                        $flag = true;
                    }
                }
                if(!in_array($curLangTopic,$topics)){
                    $subscribeTopic[$curLangTopic][] = $row['token'];
                    $flag = true;
                    $topics[] = $curLangTopic;
                }

                if($flag){
                    sort($topics);
                    $userDataList[$user]['topic'] = implode(',',array_unique($topics));
                }
            }else{
                $subscribeTopic[$curLangTopic][] = $row['token'];
                $userDataList[$user]  = implode(',',[$curLangTopic]);
            }
        }
        $ret = $ret2 =  false;
        foreach ($cancelTopic as $key=>$row){
            $ret = self::removeSubscribeTopic($key,$row);
        }
        foreach ($subscribeTopic as $key=>$row){
            $ret2 = self::subscribeTopic($key,$row);
        }
        if($ret && $ret2){
            $table = otable::xg_push();
            foreach ($userDataList as $key=>$row){
                $sql = "UPDATE {$table} SET topic='{$row['topic']}' WHERE uid = {$row['uid']} LIMIT 1 ";
                oo::commonOprDb('common')->query($sql,false);
            }
            return true;
        }
        return false;
    }

    /**
     * 刷新用户语言主题订阅 -- 单人
     * @param $uid
     * @return bool
     * Created by: Owen
     * Created on: 2020/3/4 15:21
     */
    public function refreshUserTopicByLang($uid){
        if(empty($uid)){
            return false;
        }
        $userData = oo::commonOprModel('push')->getPushTokenByUid($uid);
        $curLangTopic = okeys::FireBaseTopic($userData['lang']);
        $langCommonKey = okeys::FireBaseTopic();
        $flag = false;
        if(!empty($userData['topic'])) {
            $topics = explode(',',$userData['topic']);
            foreach ($topics as $key=>$topic){
                if(strpos($topic,$langCommonKey) !== false && $topic != $curLangTopic){
                    unset($topics[$key]);
                    $flag = true;
                    self::removeSubscribeTopic($topic,[$userData['token']]);
                }
            }
            $topics[] = $curLangTopic;
            $topics = array_unique($topics);
            $newTopic = implode(',',$topics);
        }else{
            $newTopic = implode(',',[$curLangTopic]);
            $flag = true;
        }
        if($flag){
            $ret = self::subscribeTopic($curLangTopic,[$userData['token']]);
            if($ret){
                $table = otable::xg_push();
                $sql = "UPDATE {$table} SET topic='{$newTopic}' WHERE uid={$uid} LIMIT 1 ";
                oo::commonOprDb('common')->query($sql,false);
                return true;
            }
        }
        return false;
    }

}
