<?php

namespace App\Jobs;

use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use Davibennun\LaravelPushNotification\Facades\PushNotification ;

use DB ;
use Log;

class Gcm_notification_send extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    protected $device_id ;
    protected $notification_id ;
    protected $user_id ;
    protected $device_type ;
    protected $id ;
//    protected $data ;


    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($device_id , $notification_id , $user_id , $device_type, $send_id )
    {
        //
        $this->device_id = $device_id ;
        $this->notification_id = $notification_id ;
        $this->user_id = $user_id ;
        $this->device_type = $device_type ;
        $this->id = $send_id ;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        $data = DB::table('gcm_notification_type')
            ->select('data' , 'type' , 'category' ,'desc' )
            ->where('id' , '=' , $this->notification_id)
            ->first();


        # $data['data'] = '';
        $arrResp = array();
        if($this->device_type == "android")
        {
            if($data['data'] == '' || $data['data'] == NULL || !isset($data['data']) || empty($data['data'])) {
                $msg = '';
            } else if($data['data'] != '') {
                $msg = json_decode($data['data'],true);
            }
            $randid = rand(0,100000);
            $msg = array(
                "id" => $randid,
                "message" 	=> $msg ,
                "type" => $data['type'] ,
                "category" => $data['category'] ,
                "title"		=> $data["desc"],
                "subtitle"     => $data["desc"],
                "custom_data"     => $data["desc"],
                "tickerText"	=> $data["desc"],
                "vibrate"	=> 1,
                "sound"		=> 1,
                "largeIcon" => 'large_icon',
                "smallIcon" => 'small_icon'
            );

            $fields = array
            (
                'registration_ids' 	=> array($this->device_id)  ,
                'data'			=> $msg
            );

            $headers = array
            (
                'Authorization: key=' . env('GCM_API_KEY'),
                'Content-Type: application/json'
            );

            $ch = curl_init();
            curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/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, false );
            curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
            $result = curl_exec($ch );
            curl_close( $ch );

            $result = json_decode($result);
            if ( $result->failure >= 1) {
                $error = "Android Push notification Error: gcm_token: $this->device_id. \tError: $result->results\tData: $data" ; Log::error($error);
            } else {
                $error = "Android Push notification Sent: gcm_token: $this->device_id. \tError: $result->results\tData: $data" ; Log::error($error);
            }
        }
        elseif($this->device_type == "ios")
        {
            $message = PushNotification::Message( 'Message Text' ,array(
                'badge' => 1 ,
                'sound' => 'default',

                'actionLocKey' => 'Action button title!',
                'locKey' => $data['desc'],
                'custom' => array(
                    "type" => $data['type'] ,
                    "category" => $data['category'] ,
                    "data" => json_decode($data['data'] , true )
                )
            ));

            $res = PushNotification::app('ios')
                ->to($this->device_id)
                ->send($message);

            $error = "iOS Push notification Reponse: gcm_token: $this->device_id. \tError: $res\tData: $data" ; Log::error($error);
        }
        return $arrResp;
    }
}
