<?php

namespace App\Services;
use App\Models\Challenge;
use App\Models\User;
use App\Models\Company;
use App\Models\CompanyAdmin;
use App\Models\CompanyLocationAdmin;
use App\Models\CompanyEmployee;
use App\Models\CompanyEmployeeLocation;
use App\Models\ChallengeCategory;
use App\Models\ChallengeTakingType;
use App\Models\ChallengeQuestionAnswer;
use App\Models\CompanyLocation;
use App\Models\CompanyChallengeLocations;
use App\Models\CompanyChallengeLocationEmployee;
use App\Models\Companychallenges;
use App\Models\UserDeviceToken;
use App\Models\PushNotification;
use Log;

class getDeviceTokenService {
    public function getDeviceToken($userIdArr,$msg_arr,$paramArr){
        $androidUserArr = [];
        $iosUserArr     = [];

        /*$file_path = '';
        if (env('APP_ENV', null) == "development") {
            $file_path = 'pem/employee_pem_dev/4eClientPushcert.pem';
           // $file_path = 'storage/pem/employee_pem_dev/4epushcert.pem';
        }
        else if(env('APP_ENV', null) == "production") {
            $file_path = 'pem/employee_pem_dev/4eClientProductionPushcert.pem';
            //$file_path = 'storage/pem/employee_pem_dev/4epushcert.pem';
        }
        log::info('storage pem file link retret'.print_r(storage_path($file_path)));*/

        $file_path = 'pem/employee_pem_dev/4eClientProductionPushcert.pem';

        if(is_array($userIdArr)){  
             $pushNotifyArr = [];     
            foreach($userIdArr as $key => $user){                
                
                $iosuserDeviceToken = UserDeviceToken::where('user_id',$user)
                                            ->where('device_type','iOS')
                                            ->where('device_token','!=','')
                                            ->whereNotNull('device_token')
                                            ->where('user_role','employee')
                                            ->where('login_status',1)
                                            ->pluck('device_token');

                $iosuserDeviceToken = objectToArray($iosuserDeviceToken);
               // dd($iosuserDeviceToken );
                if(!empty($iosuserDeviceToken) && isset($iosuserDeviceToken)){
                // $iosUserArr = array_merge($iosUserArr, $iosuserDeviceToken);                   
                    $iosUserArr[0]['user_id']      = $user;
                    $iosUserArr[0]['device_token'] = $iosuserDeviceToken[0];
                    $iosUserArr[0]['device_type'] =  'iOS';

                    $apn_response  =  $this->getPushNotification($iosUserArr,$msg_arr, $paramArr);                    
                    //$apn_response  =  $this->APN( $file_path, $iosUserArr, $msg_arr, $paramArr);                    
                    $pushNotiArr['user_id'] =  $user;
                    $pushNotiArr['device_type']   =  'iOS';
                    $pushNotiArr['date_time']    = date("Y-m-d H:i:s");
                    $pushNotiArr['message_slug'] = $paramArr['type'];                   
                    $pushNotiArr['message']      = '';
                    $pushNotiArr['delivery_status'] = 0;
                    $pushNotiArr['apn_response'] = NULL;
                    $pushNotiArr['is_active']       = 1;
                    $pushNotiArr['created_at']      = date("Y-m-d H:i:s");
                    $pushNotiArr['updated_at']      = date("Y-m-d H:i:s");

                    $pushNotifyArr[] = $pushNotiArr;
                }                

                //$check_androiduserDeviceToken
                $androiduserDeviceToken = UserDeviceToken::where('user_id',$user)
                                            ->where('device_type','Android')
                                            ->where('device_token','!=','')
                                            ->whereNotNull('device_token')
                                            ->where('user_role','employee')
                                            ->where('login_status',1)
                                            ->pluck('device_token');

                $androiduserDeviceToken = objectToArray($androiduserDeviceToken);
                if(!empty($androiduserDeviceToken) && isset($androiduserDeviceToken)){
                 //$androidUserArr = array_merge($androidUserArr, $androiduserDeviceToken);
                    //dd($androiduserDeviceToken[0]);
                    $androidUserArr[0]['device_type'] =  'Android';
                    $androidUserArr[0]['user_id']      = $user;
                    $androidUserArr[0]['device_token'] = $androiduserDeviceToken[0];
                    $push_response                     = $this->getPushNotification($androidUserArr,$msg_arr, $paramArr);
                        //dd($push_response );
                    /*$androidUserArr[$key]['user_id']        = $androiddeviceToken->user_id;
                    $androidUserArr[$key]['device_token']   = $androiddeviceToken->device_token;
                    $push_response                          =  $this->getPushNotification($androidUserArr,$msg_arr, $paramArr);*/
                    $pushNotiArr['user_id']         =  $user;
                    $pushNotiArr['device_type']     =  'Android';
                    $pushNotiArr['date_time']       =  date("Y-m-d H:i:s");
                    $pushNotiArr['message_slug']    =  $paramArr['type'];
                    $pushNotiArr['message']         =  $push_response??'';
                    $pushNotiArr['is_active']       =  1;
                    $pushNotiArr['created_at']      =  date("Y-m-d H:i:s");
                    $pushNotiArr['updated_at']      =  date("Y-m-d H:i:s");

                    $pushNotifyArr[] = $pushNotiArr;
                }


            }

            if(!empty($pushNotifyArr)){
                $save_data =  $this->savePushNotification( $pushNotifyArr);
            }
        }else{
            // if (env('APP_ENV', null) == "development") {
            //     $file_path = 'storage/pem/employee_pem_dev/4epushcert.pem';
            // }
            // else if(env('APP_ENV', null) == "production") {
            //     $file_path = 'storage/pem/employee_pem_dev/4epushcert.pem';
            // }

            $androiduserDeviceToken = UserDeviceToken::where('user_id',$userIdArr)->where('device_type','Android')->where('device_token','!=','')->where('user_role','employee')->where('login_status',1)->get();
            $iosuserDeviceToken = UserDeviceToken::where('user_id',$userIdArr)->where('device_type','iOS')->where('device_token','!=','')->where('user_role','employee')->where('login_status',1)->get();
            $pushNotifyArr = [];
                foreach($iosuserDeviceToken as $key=> $iosdeviceToken){
                    $iosUserArr[$key]['user_id']            = $iosdeviceToken->user_id;
                    $iosUserArr[$key]['device_token']       = $iosdeviceToken->device_token;
                    $apn_response                           =  $this->APN( $file_path, $iosUserArr, $msg_arr, $paramArr);
                    $pushNotifyArr[$key]['user_id']         =  $iosdeviceToken->user_id;
                    $pushNotifyArr[$key]['device_type']     =  $iosdeviceToken->device_type;
                    $pushNotifyArr[$key]['date_time']       = date("Y-m-d H:i:s");
                    $pushNotifyArr[$key]['message_slug']    = $paramArr['type'];
                    $pushNotifyArr[$key]['message']         = $apn_response['response']??'';
                    $pushNotifyArr[$key]['delivery_status'] = $apn_response['status']==1 ? $apn_response['status'] : 0;
                    $pushNotifyArr[$key]['apn_response']    = $apn_response['apn_response']??NULL;
                    $pushNotifyArr[$key]['is_active']       = 1;
                    $pushNotifyArr[$key]['created_at']      = date("Y-m-d H:i:s");
                    $pushNotifyArr[$key]['updated_at']      = date("Y-m-d H:i:s");
                }
            
            foreach($androiduserDeviceToken as $key=>$androiddeviceToken){
                $androidUserArr[$key]['user_id']        = $androiddeviceToken->user_id;
                $androidUserArr[$key]['device_token']   = $androiddeviceToken->device_token;
                $push_response                          =  $this->getPushNotification($androidUserArr,$msg_arr, $paramArr);
                $pushNotifyArr[$key]['user_id']         =  $androiddeviceToken->user_id;
                $pushNotifyArr[$key]['device_type']     =  $androiddeviceToken->device_type;
                $pushNotifyArr[$key]['date_time']       = date("Y-m-d H:i:s");
                $pushNotifyArr[$key]['message_slug']    = $paramArr['type'];
                $pushNotifyArr[$key]['message']         = $push_response??'';
                $pushNotifyArr[$key]['is_active']       = 1;
                $pushNotifyArr[$key]['created_at']      = date("Y-m-d H:i:s");
                $pushNotifyArr[$key]['updated_at']      = date("Y-m-d H:i:s");
            }
            if(!empty($pushNotifyArr)){
                $save_data =  $this->savePushNotification( $pushNotifyArr);
            }
        }
        
       
    }

    public function savePushNotification($pushArr){
       return(PushNotification::insert($pushArr));
    }

    public function APN($file_path, $deviceTokenArr = [], $messageArr = [], $paramArr = []){

            log::info('storage pem file link'.print_r(storage_path($file_path)));
            $passphrase = '';        
            if(!file_exists(storage_path($file_path))) {
                log::info('storage pem file found');
                return 0;
            }     
            $ctx = stream_context_create();
            stream_context_set_option($ctx, 'ssl', 'local_cert', storage_path($file_path));
            stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

            if (env('APP_ENV', null) == "development") {
                $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); // developement
            }
            else if(env('APP_ENV', null) == "production" || true) {
                $fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); // production
            }

            if(!$fp) {
                return ['response' => "Connection failed.", "status" => 0];
            }

            $alert['title'] = $messageArr['title']??'';
            $alert['body'] = $messageArr['body']??'';

            $body['aps'] = array('alert' => $alert,'sound' => 'default');
            $body['data'] = $paramArr?:(object) [];
            $payload = json_encode($body);

            $status = 0;
            $apn_response = '';
            if($deviceTokenArr) {
                foreach ($deviceTokenArr as $key => $deviceToken) {
                    $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken['device_token']) . pack('n', strlen($payload)) . $payload;
                    $result = fwrite($fp, $msg, strlen($msg));

                    if($result) {
                        $status = 1;
                        $apn_response = $result;
                    }
                }
            }

            fclose($fp);

            return array("response" => $payload, 'status' => $status, 'apn_response' => $apn_response);
    } 

    public function getPushNotification($deviceTokenArr,$msg_arr, $paramArr){
    
        if($deviceTokenArr) {
           foreach ($deviceTokenArr as $key => $deviceToken) {   
           //dd( $deviceToken);         
              // $registrationIds= 'fub-CPqoQUizkHwrLTZvBE:APA91bG-HMtyVzRExdXCMCEDsMzDBQxQkLgPBq41i0AKDXNxXYUP74BbPqKViVctMwhCevilSAnobPmsSZa-0ON6f13q0VTOHbccSpXvvYFXb9FseCRE6jRE8i1qCFnucy7hHRACCUIS';
               $registrationIds= $deviceToken['device_token'];

               if( $deviceToken['device_type'] == 'iOS'){
                    $arrNotification= array(); 
                    $arrNotification["body"] = $msg_arr['body'];
                    $arrNotification["title"] = $msg_arr['title'];
                    $arrNotification["sound"] = "default";
                    $arrNotification["type"] = 1;
                    $fields = array(
                    'to' => $registrationIds,
                    'notification' => $arrNotification
                    );
               }else{
                   $postdata['Notification_text'] =  $msg_arr['title'];
                   $postdata['notification_detail_content'] =  $msg_arr['body'];
                   $postdata['body']  = $msg_arr['body'];
                   $postdata['tag']  = $paramArr['type'];
                   $postdata['name']  = 'Challenge Added';
                   $postdata['image']  = 'Challenge Added';
                   $fields = array
                    (
                        'to'  => $registrationIds,
                        'data'          => $postdata,
                        'android'=> array('priority'=>'high'),
        
                    );
                }               

               $headers = array
               (
                   'Authorization: key=' . 'AAAAU63dEIE:APA91bHBFXrkr5OTnD5yJGiqV8Jy81r9KWxPVCwLJ1OP8OJpUQh7_nBXoLG3qaXjL9K9VfYWE31HVwZeYrhLF2mEshmIF689Y3PCIwAmpnEgUEtmQ923K4Aey1xAvl8JFVBSP5q2qt-G',
                   'Content-Type: application/json'
               );

               $ch = curl_init();
               curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
               curl_setopt( $ch,CURLOPT_POST, true );
               curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
               curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
               curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, true );
               curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields));
               $result = curl_exec($ch );                        
               return $result;

           }
       }

   }
}