<?php
$lid =1;
$sid =2;
define('IN_WEB', true);
include (dirname(__FILE__)."/../com.php");
$ts = date("Y-m-d H:i:s",time());
$uniqId = uniqid();
$iosData = file_get_contents('php://input');
oo::logs()->commlog(["time"=>$ts,"info"=>$iosData,"type"=>"join","uniqId"=>$uniqId,"sid"=>2],'ios-vip.log','logs/'.date('Ymd').'/');
$iosData = json_decode($iosData,true);
oo::logs()->commlog(["time"=>$ts,"info"=>$iosData,"type"=>"join","uniqId"=>$uniqId,"sid"=>2],'ios_vip_decode.log');
if(!empty($iosData)) {
    $transaction_id ="";
    $notification_type = $iosData['notification_type'];
    $original_transaction_id = $iosData['latest_receipt_info']['original_transaction_id'];
    $expires_date   = $iosData['latest_receipt_info']['expires_date'];
    $expires_date_New = $iosData['latest_receipt_info']['expires_date_ms']/1000;
    $thisOrderInfo = [];
    if(empty($original_transaction_id)){
        $tempIosData= $iosData['unified_receipt']['latest_receipt_info'];
        if(!empty($tempIosData[0])){//最新vip订单
            $thisOrderInfo = $tempIosData[0];
            $transaction_id = $tempIosData[0]['transaction_id'];
            $expires_date_New = $tempIosData[0]['expires_date_ms']/1000;
        }
        foreach ($tempIosData as $row){
            $original_transaction_id = $row['original_transaction_id'];
            $expires_date   = $row['expires_date_ms'];
            if(!empty($original_transaction_id) && !empty($expires_date)){
                break;
            }
        }
    }

    $latest_receipt = $iosData['latest_receipt'];
    if(empty($latest_receipt)){
        $latest_receipt = $iosData['unified_receipt']['latest_receipt'];
    }
    if($notification_type == "INITIAL_BUY") {
        $time = time();
        $tb = otable::subscription($sid);
        $ret = oo::commonOprDb('common')->query("INSERT INTO {$tb}(transaction_id, latest_receipt,`time`) VALUES('{$original_transaction_id}', '{$latest_receipt}',{$time})", false);
    } else if ($notification_type == "CANCEL") {
//        $tb = otable::summarylist();
//        $ret = oo::commonOprDb('common')->getOne("SELECT * FROM {$tb} WHERE sl_platform_serial_num='{$transaction_id}' LIMIT 1", MYSQLI_ASSOC);
//        if(!empty($ret)){
//            oo::commonOprModel('member')->getUserInfo($ret['sl_uid'], NULL, TRUE, ['svip'=>0]);
//            oo::commonOprModel('Workerman')->push($ret['sl_uid'],ocmd::$send['Vip_Rec'],['vipInfo'=>oo::commonOprModel('newvip')->getVipInfo($ret['sl_uid'])]);
//        }
        oo::commonOprRedis('common')->zDelete(okeys::VipMonitor(), $original_transaction_id);
    } else if ($notification_type == "RENEWAL" || $notification_type == "INTERACTIVE_RENEWAL" || $notification_type == "DID_RENEW" || $notification_type == "DID_CHANGE_RENEWAL_STATUS") {
//        $tb = otable::summarylist();
//        $ret = oo::commonOprDb('common')->getOne("SELECT * FROM {$tb} WHERE sl_platform_serial_num='{$transaction_id}' LIMIT 1", MYSQLI_ASSOC);
//        if(!empty($ret)){
//            /**
//             * vip 续订记录
//             */
//            oo::commonOprRedis('User')->incr(okeys::VipRenewTimes($ret['sl_uid'])) && oo::commonOprRedis('User')->expire(okeys::VipRenewTimes($ret['sl_uid']),15*24*60*60);
//            oo::commonOprModel('member')->getUserInfo($ret['sl_uid'], NULL, TRUE,['svip'=>1,'svip_expire'=>ceil($expires_date/1000)]);
//            oo::commonOprModel('Workerman')->push($ret['sl_uid'],ocmd::$send['Vip_Rec'],['vipInfo'=>oo::commonOprModel('newvip')->getVipInfo($ret['sl_uid'])]);
//            oo::async()->add('oo::commonOprModel("notice")->sendNoticeMsg',[$uid,"buyVip"]);//异步跑马灯消息
//        }
        //ios vip订阅
        if($expires_date_New<time()){
            oo::logs()->commlog(["time"=>$ts,"context"=>"过期时间异常","data"=>$iosData],"errorIosVip.log");
            die(oo::response(1));
        }
        if($transaction_id){
            $tb  = otable::orderNew(2022);
            $sql = "SELECT * FROM {$tb} WHERE external_order_id='{$transaction_id}' and status in(2,4)";
            $ret = oo::commonOprDb('payment')->getOne($sql,MYSQLI_ASSOC);
            if(empty($ret)&&$original_transaction_id){//没找到订单
                $tb2  = otable::subscription();
                $sql = "SELECT * FROM {$tb2} WHERE purchaseToken='{$original_transaction_id}'";
                $ret2 = oo::commonOprDb('payment')->getOne($sql,MYSQLI_ASSOC);
                if(!empty($ret2)){//找到原始订单id与uid对应关系时，创建订单
                    $now = time();
                    $insertData =[
                        "subscription_expire"=>date("Y-m-d H:i:s",$expires_date_New),
                        "created_at"=>date("Y-m-d H:i:s"),
                        "updated_at"=>date("Y-m-d H:i:s"),
                        "purchased_at"=>date("Y-m-d H:i:s",$thisOrderInfo['purchase_date_ms']/1000),
                        "status"=>2,
                        "uid"=>$ret2["uid"],
                        "sku"=>$thisOrderInfo["product_id"],
                        "external_order_id"=>$transaction_id,
                        "price"=>4.99,
                        "gid"=>801,
                        "sid"=>2,
                        "source"=>3,
                        "inner_order_id"=>"{$now}|{$ret2['uid']}|2774|801|0"
                    ];
                    $sql = funs::db_insertSQL($tb,$insertData);
                    $res = oo::commonOprDb('common')->query($sql,1);
                    oo::logs()->commlog(["time"=>$ts,"uid"=>$ret2['uid'],"context"=>"创建新订单结果:{$res}","external_order_id"=>$transaction_id,"data"=>$insertData],"successIosVip.log");
                }else{//未找到原始订单
                    oo::logs()->commlog(["time"=>$ts,"context"=>"未找到原始订单id:{$original_transaction_id}","data"=>$iosData],"errorIosVip.log");
                }
            }else{
                oo::logs()->commlog(["time"=>$ts,"uid"=>$ret['uid'],"context"=>"订单成功，已经创建了此订单,订阅过期时间：{$ret['subscription_expire']}","external_order_id"=>$transaction_id],"successIosVip.log");
            }
        }


//        if(!empty($ret)&&isset($ret['uid'])){
//            $sql = "UPDATE {$tb} SET updated_at=now(),status=2,subscription_expire=FROM_UNIXTIME({$expires_date_New}) where external_order_id='{$transaction_id}'";
//            $res2 = oo::commonOprDb('common')->query($sql,1);
//            oo::logs()->commlog(["uid"=>$ret['uid'],"external_order_id"=>$transaction_id,"data"=>$iosData],"successIosVip.log");
//        }else{
//            oo::logs()->commlog($iosData,"errorIosVip.log");
//        }
    }
}

//if(!IS_DEBUF){
//    file_get_contents("http://testapi.superant.cc/api/ios.php", false, stream_context_create(['http'=>['method'=>'POST','header'=>'Content-type:application/x-www-form-urlencoded','content'=>json_encode($iosData),'timeout'=> 60]]));
//}

die(oo::response(1));
?>