<?php


namespace App\Http\AppFlyerEvent;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AppflyerEvent
{
    const Token = 'aoRrdANBXaid2HX77FxE6P';

    /**
     * @param $user_id
     * @param $appsflyer_id
     * @param string $appsflyer_event
     * @param int $value
     * @return mixed
     */

    public function event($user_id, $appsflyer_id, $appsflyer_event = '', $value = 0)
    {
        $packag_name = DB::connection('write')->table('QPRecordDB.dbo.RecordPackageName')
                ->where('UserID', $user_id)
                ->select('PackgeName')
                ->first()->PackgeName ?? '';

        // 充值用
        if (empty($appsflyer_id)) {

            $appsflyer_id = DB::connection('write')->table('QPRecordDB.dbo.RecordUserIDAdid')
                    ->where('UserID', $user_id)
                    ->select('adid')
                    ->first()->adid ?? '';
        }

        if (empty($appsflyer_id)) {
            return 'false';
        }

        $purchase_event = array(
            'appsflyer_id' => $appsflyer_id,
        );

        $purchase_event['eventName'] = $appsflyer_event;

        if ($appsflyer_event == 'af_purchase_new') {

            $data['af_revenue'] = $value;
            $data['af_currency'] = 'INR';
            $purchase_event['eventValue'] = \GuzzleHttp\json_encode($data);
        }

        $data_string = json_encode($purchase_event);

        if (is_string($data_string)) {
            Log::channel('AppflyerEvent')->info('af请求数据：' . $data_string);
        }

        $res = $this->curl($packag_name, $data_string);
        Log::channel('AppflyerEvent')->info('af返回结果：' . $res);


        // 中大R事件
        //$this->zdR($user_id, $appsflyer_id, $value, $packag_name);

        return $res;
    }

    // 中大R事件
    public function zdR($user_id, $appsflyer_id, $value)
    {

        $packag_name = DB::connection('write')->table('QPRecordDB.dbo.RecordPackageName')
                ->where('UserID', $user_id)
                ->select('PackgeName')
                ->first()->PackgeName ?? '';

        // 充值用
        if (empty($appsflyer_id)) {

            $appsflyer_id = DB::connection('write')->table('QPRecordDB.dbo.RecordUserIDAdid')
                    ->where('UserID', $user_id)
                    ->select('adid')
                    ->first()->adid ?? '';
        }

        if (empty($appsflyer_id)) {
            return 'false';
        }

        // 传中大R事件
        $first = DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
            ->where('UserID', $user_id)
            ->select('Recharge')
            ->first();

        if ($first) {
            $Recharge = (int)$first->Recharge;


            if ($Recharge > 0 && $Recharge < 1000) {
                $af_purchase_r1000['appsflyer_id'] = $appsflyer_id;
                $af_purchase_r1000['eventName'] = 'af_purchase_r1000';
                $af_purchase_r1000Data['af_revenue'] = $value;
                $af_purchase_r1000Data['af_currency'] = 'INR';
                $af_purchase_r1000['eventValue'] = \GuzzleHttp\json_encode($af_purchase_r1000Data);
                $data_string = json_encode($af_purchase_r1000);
                if (is_string($data_string)) {
                    Log::channel('AppflyerEvent')->info($packag_name.'af小于1000 请求数据：' . $data_string);
                }

                $r = $this->curl($packag_name, $data_string);
                Log::channel('AppflyerEvent')->info($packag_name.'af小于1000返回结果：' . $r);
            }


            if ($Recharge >= 1000) {
                $af_purchase_Rr['appsflyer_id'] = $appsflyer_id;
                $af_purchase_Rr['eventName'] = 'af_purchase_Rr';
                $af_purchase_RrData['af_revenue'] = $value;
                $af_purchase_RrData['af_currency'] = 'INR';
                $af_purchase_Rr['eventValue'] = \GuzzleHttp\json_encode($af_purchase_RrData);
                $data_string = json_encode($af_purchase_Rr);
                if (is_string($data_string)) {
                    Log::channel('AppflyerEvent')->info($packag_name.'af中R请求数据：' . $data_string);
                }

                $r = $this->curl($packag_name, $data_string);
                Log::channel('AppflyerEvent')->info($packag_name.'af中R返回结果：' . $r);
            }


            if ($Recharge >= 10000) {
                $af_purchase_R['appsflyer_id'] = $appsflyer_id;
                $af_purchase_R['eventName'] = 'af_purchase_R';
                $af_purchase_RData['af_revenue'] = $value;
                $af_purchase_RData['af_currency'] = 'INR';
                $af_purchase_R['eventValue'] = \GuzzleHttp\json_encode($af_purchase_RData);

                $data_string = json_encode($af_purchase_R);
                if (is_string($data_string)) {
                    Log::channel('AppflyerEvent')->info($packag_name.'af大R请求数据：' . $data_string);
                }

                $r = $this->curl($packag_name, $data_string);
                Log::channel('AppflyerEvent')->info($packag_name.'af大R返回结果：' . $r);
            }
        }


        // 当日注册当日充值的玩家的付费事件

        $AccountsInfo = DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo as ai')
            ->join('agent.dbo.order as o','ai.UserID','=','o.user_id')
            ->where('ai.UserID',$user_id)
            ->lock('with(nolock)')
            ->where('pay_status',1)
            ->whereDate('RegisterDate',date('Y-m-d'))
//            ->whereDate('RegisterDate','2021-11-01')
            ->count();

        if ($AccountsInfo == 1) {
            $af_purchase_Registration['appsflyer_id'] = $appsflyer_id;
            $af_purchase_Registration['eventName'] = 'af_purchase_Registrationday';
            $af_purchase_RegistrationData['af_revenue'] = $value;
            $af_purchase_RegistrationData['af_currency'] = 'INR';
            $af_purchase_Registration['eventValue'] = \GuzzleHttp\json_encode($af_purchase_RegistrationData);
            $data_string = json_encode($af_purchase_Registration);
            if (is_string($data_string)) {
                Log::channel('AppflyerEvent')->info($packag_name.'当日注册当日充值的玩家的付费事件 请求数据：' . $data_string);
            }

            $r = $this->curl($packag_name, $data_string);
            Log::channel('AppflyerEvent')->info($packag_name.'当日注册当日充值的玩家的付费事件：' . $r);
        }


        // 所有玩家（包括以前注册的玩家）首次充值的付费事件 af_purchase_First charge
        $order = DB::connection('write')->table('agent.dbo.order')
            ->where('user_id',$user_id)
            ->where('pay_status',1)
            ->count();

        if ($order == 1) {
            $af_purchase_First['appsflyer_id'] = $appsflyer_id;
            $af_purchase_First['eventName'] = 'af_purchase_Firstcharge';
            $af_purchase_FirstData['af_revenue'] = $value;
            $af_purchase_FirstData['af_currency'] = 'INR';
            $af_purchase_First['eventValue'] = \GuzzleHttp\json_encode($af_purchase_FirstData);
            $data_string = json_encode($af_purchase_First);
            if (is_string($data_string)) {
                Log::channel('AppflyerEvent')->info($packag_name.'所有玩家（包括以前注册的玩家）首次充值的付费事件 请求数据：' . $data_string);
            }

            $r = $this->curl($packag_name, $data_string);
            Log::channel('AppflyerEvent')->info($packag_name.'所有玩家（包括以前注册的玩家）首次充值的付费事件：' . $r);
        }

    }


    public function curl($packag_name, $data_string,$devKey= null)
    {
        $url = "https://api2.appsflyer.com/inappevent/" . $packag_name;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'authentication:' . ($devKey??self::Token),
                'Content-Length: ' . strlen($data_string))
        );
        curl_exec($ch);

        $res = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return $res;
    }
}
