<?php

namespace Api\PhpServices\PushToken;


use Api\PhpUtils\Http\Request;

class Ios extends Base
{
    /**
     * @param bool $err 引用类型，是否存在错误
     * @param $appid
     * @param $userid
     * @param $data
     */
    public static function save(&$err = false, $appid, $data, $userid=''){
        $new_token      = $data['new_token'] ?? "";
        $old_token      = $data['old_token'] ?? "";
        $token          = $data['new_token'] ?? $data['old_token'] ?? "";
        $version        = self::version($data['version'] ?? "");
        $personal_rec   = $data['personalRec'] ?? 1;
        $enable         = self::enable($data['enable'] ?? 1, $personal_rec);

        if (!self::valid_appid($appid)){
            return ["code"=> self::ERROR_CODE_PARAM, "msg" => "appid有误"];
        }

        if( empty($token) || !self::valid_ios_token($token) ){
            $err = true;
            return ["code"=> self::ERROR_CODE_PARAM, "msg" => "token有误"];
        }

        if( !$version ){
            $err = true;
            return ["code"=> self::ERROR_CODE_PARAM, "msg" => "version有误"];
        }

//        $action = explode('?', $_SERVER['REQUEST_URI'])[0];   // 与运营中台沟通，暂时写死成 website 路径，之后重构再调整
        $action = "/Website/push/BindingTokenAction.php";

        $send = [
            'action'        => $action,
            'userid'        => $userid,
            'appid'         => $appid,
            'request_time'  => intval($_SERVER['REQUEST_TIME']),
            'version'       => $version,
            'time_zone'     => $data["time_zone"] ?? "",
            'personal_rec'  => intval($personal_rec),
            'enable'        => $enable,
            'sound'         => $data["sound"] ?? "",
            'push_level'    => $data["push_level"] ?? "",
            'old_token'     => $old_token,
            'new_token'     => $new_token,
            'push_key'      => $data["push_key"] ?? "",
            'cv'            => $data["cv"] ?? "",
            'os'            => $data["os"] ?? "",
            'distribution'  => $data["distribution"] ?? "",
            'platform'      => "IOS"
        ];

        $send = array_filter ($send,function($v){if($v===''){return false;}else{return true;}});

        if(!self::sendKafka($send)){
            $err = true;
            return ["code"=> self::ERROR_CODE_KAFKA, "msg" => "send failed"];
        };

        $err = false;
        return true;
    }
}