<?php
/**
 * Created by PhpStorm.
 * User: varun_2
 * Date: 04-02-2016
 * Time: 18:10
 */

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use App\Http\Controllers\Action\notification ;
use App\Jobs\Gcm_notification_send ;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Auth\authentication ;
use Davibennun\LaravelPushNotification\Facades\PushNotification ;

use DB ;

class notificationController extends Controller
{
    /**
     * Set notification to
     */
    public function notification_set(Request $request){

        $user_id = '' ;
        if($request->has('token'))
        {
            if($request->has('token'))
            {
                $token = $request->input('token');
                $auth = new authentication();
                $user_id = $auth->authToken($token);
                if (!$user_id)
                    abort(403, 'Unauthorized action. Token access denied');
            }
        }

        if($request->has('device_id') && $request->has('device') && $request->has('status'))
        {
            if($request->status == 'enable' || $request->status == 'disable')
            {
                if( $request->device == 'android' || $request->device == 'ios')
                {
					$exists = array();
                    $exists = DB::table('gcm_device')
                        ->where('device_id', '=' , trim($request->device_id) )
                        ->where('device' , '=' , $request->device)
                        ->first();

                    if(empty($exists)) 
					{ 
						return new JsonResponse( array(
							"status#" => "0",
							"message" => "Device not registered"
						));

					} else {
	                    $query = DB::table('gcm_device')
							->where('device_id', '=' , trim($request->device_id) )
							->where('device' , '=' , $request->device)
							->update(["status" => $request->status ]) ;

	                    return new JsonResponse( array(
		                    "status#" => "1"
			            ));
					}
                }
                else
                    abort(206, "Partial Input, device accepted value (android/ios)" ) ;
            }
            else
                abort(206, "Partial Input, status accepted value (enable/disable)" ) ;

        }
        else
            abort( 206, "Partial Input, request with device_id, device, and status" ) ;
    }
    /**
     * Called by mobile to register itself
     * @param Request $request
     */
    public function registerDevice(Request $request)
    {
	
		if($request->has('debug')){
			/* if($request->has('token'))
			{
				$token = $request->input('token');
				$auth = new authentication();
				$user_id = $auth->authToken($token);
				if (!$user_id){
					///abort(403, 'Unauthorized action. Token access denied');
					return new JsonResponse(array(
							"status#" =>"403",
							"message#" => "Unauthorized action. Token access denied :".$user_id,
							"latest_app_version_in_play_store" => "5.8.9",
							"allow_copy_news" => "0"
						)) ;
				}
			}else{ */
			$token = '';
			if($request->has('token'))
				$token = $request->input('token');
			$fields = array
			(
				'FCM_tag_copy'  => 'ios',
				'token'  => $token,
				'device'  => $request->input('device'),
				'physical_id'  => '',
				'deviceInfo'  => '',
				'device_id'  => $request->input('device_id'),
				'delay_while_idle' => true
			);
				
			$url = "https://www.steelmint.com/api/pre_function/reg_process_steps.php";
			$ch=curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
			$output=curl_exec($ch);
			curl_close($ch);
			//print_r ($fields);
			//print_r ($output); dd();
			return $output;
			//}
			//return 1;
		}else{
		
			if($request->has('device')
				&& $request->has('device_id')
			)
			{
                //by tanvi 06 jun 18 start
                    /*new code for ADmod by tanvi*/
                
                $recoveredData_admob = file_get_contents('/home/steelmin/public_html/images/manage_banner/images/admob.json');
                if($recoveredData_admob!='')
                    $get_data_admob = unserialize($recoveredData_admob);

                /*if(isset($get_data_admob['video']['url']))
                    $video_url=$get_data_admob['video']['url'];
                else
                    $video_url="";*/

                if(isset($get_data_admob['image']['image']))
                    $file_path_img="https://www.steelmint.com/images/manage_banner/images/admob/image/".$get_data_admob['image']['image'];
                else
                    $file_path_img="";

                /*if($video_url!='')
                    $type='video';
                else if($file_path_img!='')
                    $type='image';*/

                /*new code for ADmod by tanvi*/

                //by tanvi 06 jun 18 end
				$user_id = '' ;
				if($request->has('token'))
				{
					$token = $request->input('token');
					$auth = new authentication();
					$user_id = $auth->authToken($token);
					if (!$user_id)
						abort(403, 'Unauthorized action. Token access denied');
				}

				if( $request->input('device') == 'android' || $request->input('device') == 'ios')
				{
					$device_id = $request->input('device_id') ;
					$device_id = trim($device_id ) ;
					$gcm = array(
						"device" => $request->input('device') ,
						"device_id" => $device_id ,
						"user_id" => $user_id ,
					);
					
					$_app_ver="8.0";//7.4 missing 				
					if($request->has('appType') && strtoupper($request->input('appType')) == 'CM'){ 
						$_app_ver="1.3";	
					}
                    
					$device_id = $request->input('device_id') ;
                    $sel_admob=DB::table('gcm_device')->where("device" , "=" , $request->input('device'))->where("device_id" , "=" , $device_id )->first();

  $show_admob='Y';
$file_path_img = "https://www.steelmint.com/fileForMail/CoalMint_Mobile_App_500x800.png";

					if($sel_admob)
					{
                        $show_admob=$sel_admob['admob'];
                        $show_admob='N';
						DB::table('gcm_device')
							->where("device" , "=" , $request->input('device') )
							->where("device_id" , "=" , $device_id )
							->update(["user_id" => $user_id ]) ;
						return new JsonResponse(array(
							"status#" =>"1",
							"message#" => "Device already registered",
							"latest_app_version_in_play_store" => $_app_ver,
							"allow_copy_news" => "0",
							"translate_to" => array('en'=> "English",
										'hi'=> "Hindi",
										'ja'=> "Japanese",
										'zh-CN'=> "Chinese",
										'ru'=> "Russian",
									),
                            "show_admob" =>'Y',
                            "image_url" => "https://www.steelmint.com/fileForMail/CoalMint_Mobile_App_500x800.png",
                            "type" => 'image',
                            "event_id"=>'17'
						)) ;
					} else {
						$sel_admob_1 = '';
						if( $user_id > 0 ){
							$sel_admob_1 = DB::table('gcm_device')
											->where("device" , "=" , $request->input('device'))
											->where("user_id" , "=" , $user_id )
											->first();
						}
						if($sel_admob_1 != ''){
							DB::table('gcm_device')
								->where("device" , "=" , $request->input('device') )
								->where("user_id" , "=" , $user_id )
								->update(["device_id" => $device_id ]) ;
						} else {
							DB::table('gcm_device')
								->insert($gcm) ;
						}
					}

					return new JsonResponse(array(
						"status#" =>"1",
						"latest_app_version_in_play_store" => $_app_ver,
						"allow_copy_news" => "0",
						"translate_to" => array('en'=> "English",
										'hi'=> "Hindi",
										'ja'=> "Japanese",
										'zh-CN'=> "Chinese",
										'ru'=> "Russian",
									),
                        "show_admob" =>'Y',
                        "image_url" => "https://www.steelmint.com/fileForMail/CoalMint_Mobile_App_500x800.png",
                        "type" => 'image',
                        "event_id"=>'17'
					)) ;
				}
				else
					abort( 206, "Device not detected" ) ;

			}
		}
    }

    /**
     * Called by mobile to deregister itself
     * @param Request $request
     */
    public function deregisterDevice(Request $request)
    {
        if($request->has('device')
            && $request->has('device_id')
        )
        {
            $user_id = '' ;
            if($request->has('token'))
            {
                $token = $request->input('token');
                $auth = new authentication();
                $user_id = $auth->authToken($token);
                if (!$user_id)
                    abort(403, 'Unauthorized action. Token access denied');
            }
            else
                abort(404 , "Authentication failure") ;

            if( $request->input('device') == 'android' || $request->input('device') == 'ios')
            {

                DB::table('gcm_device')
                    ->where("device" , "=" , $request->input('device'))
                    ->where("device_id" , "=" , $request->input('device_id'))
                    ->where("user_id" , "=" , $request->input('user_id'))
                    ->delete();

                return new JsonResponse(array(
                    "status#" =>"1"
                )) ;
            }
            else
                abort( 206, "Device not detected" ) ;

        }
    }
    /**
     * Get notification ack
     * @param $device: Get device id and other things in array
     * @param $notification: Notification string which has to be send
     */
    public function getNotificationAck(Request $request)
    {

        if($request->has('device_id') && $request->has('notification_id') )
        {
            $user_id = '' ;
            if($request->has('token'))
            {
                $token = $request->input('token');
                $auth = new authentication();
                $user_id = $auth->authToken($token);
                if (!$user_id)
                    abort(403, 'Unauthorized action. Token access denied');
            }

            $not = new notification() ;
            $not->changeStatus(
                $request->has('notification_id') ,
                $request->has('device_id') ,
                "ack" ,
                $user_id
            );

        }
    }

    /**
     * Get all notification devices only
     * @param Request $request
     * @return mixed
     */
    public function get_all_device( Request $request )
    {

        $query =  DB::table('gcm_device')
            ->leftJoin('tbl_members' , 'gcm_device.user_id' , '=' , 'tbl_members.id')
            ->leftJoin('gcm_notification_send' , 'gcm_device.device_id' , '=' , 'gcm_notification_send.device_id'  )
            ->select(
                "tbl_members.name" , 'tbl_members.email' , 'tbl_members.phoneno'   , //from member table
                'gcm_device.device' ,
                DB::raw('COUNT(gcm_device.device_id) as notification'))
            ->groupBy('gcm_device.device_id') ;

        $query->where('gcm_device.status' , '=' , 'enable') ;

        if($request->has('orderBy'))
        {
            if( $request->has('orderType') )
                $query->orderBy($request->input('orderBy') , $request->input('orderType')) ;
            else
                $query->orderBy($request->input('orderBy')  , "asc") ;
        }

        if($request->has('limit'))
            $query->take($request->input('limit')) ;
        if ($request->has('skip'))
            $query->skip($request->input('skip')) ;

        $data = array(
            "devices" => $query->get()
        );

//        return view('notification/view_device' ,$data );
        return new JsonResponse($data) ;
    }

    /**
     * Get all notification send to mobile and its status
     * @param Request $request
     */
    public function get_all_notification(Request $request)
    {
        $query = DB::table('gcm_notification_send')
            ->leftJoin('gcm_notification_type' , 'gcm_notification_send.notification_id' , '=' , 'gcm_notification_type.id')
            ->select(
                "device_id" , "user_id" , "gcm_notification_type.type as type" , "gcm_notification_type.category as category"
            )
            ->get() ;

        return new JsonResponse(array(
            "status#" => "1" ,
            "data#" => $query
        )) ;
    }

    public function get_all_notification_type(Request $request)
    {
        $query = DB::table('gcm_notification_type')
            ->select('type' , 'id' , 'category' , 'data', 'desc')
            ->get() ;
        for($i = 0 ; $i < count($query) ; $i ++ )
            $query[$i]['data'] = json_decode(html_entity_decode($query[$i]['data'], ENT_QUOTES)) ;
		//print_r ($query);
        return new JsonResponse(array(
            "status#" => "1" ,
            "data#" => $query
        )) ;
    }

    public function empty_error_log_entry(Request $request) {
        $file = "/tmp/log.notification.txt";
        chmod($file, 0644);
        file_put_contents($file, '');
    }

    public function read_error_log_entry(Request $request) {
        $file = "/tmp/log.notification.txt";
        chmod($file, 0644);
        echo file_get_contents($file);
    }

    public function error_log_entry($msg = '', $file = '', $type = FILE_APPEND) {
        $file = "/tmp/".$file;
        chmod($file, 0644);
        if(file_put_contents($file, $msg, $type)) {
           //echo "write";
        } else {
           //echo "writefail";
        }
    }

	function specialChartoHTML($str)
	{
		//return htmlspecialchars_decode(htmlspecialchars($str));
		return html_entity_decode($str, ENT_QUOTES);
	}

    function androidSend($arrNotificationData = array()) {

        if(empty($arrNotificationData) || empty($arrNotificationData['device_id']) || $arrNotificationData['desc'] == '') {
			$resultArr['success'] = 2;
	        $this->error_log_entry("Notification Failed : - ".date('YmdHis')." - ".serialize($resultArr)."\n", "log.notification.txt");
	        return $resultArr;
        }

        /*Array
        (
            [data] =>
            [type] => transactional
            [category] => news
            [desc] => India: Ferro Silicon Prices Continues to be Unchanged M-o-M
            [post_id] => 67362
            [device_id] => cUAGer_U-G4:APA91bHOP1i853G_EPignATctnThRh_MVlamxaj8ZGFRbLDrYQb6jODRxNTOKHV0BqIFPkbByc9WnH_C50BmX39Y2rSP9vKv6jhuZ_HkRJVh_1qFoubBLjUkdchNXOjk5zN8g9wv0-c6
            [notification_id] => 1029
            [user_id] => 0
            [device] => android
            [id] => 359092
        )*/


        ini_set('memory_limit','64M');
        set_time_limit(0);
        //define('API_ACCESS_KEY', 'AIzaSyC_jxAWNZGL8rm0DYtVae-uBjwSAZ-UF5g');
       // define('API_ACCESS_KEY', 'AIzaSyAbeHrrkL9Pei7LvaxExKKCMAem_HSCYa0');
        //define('API_ACCESS_KEY', 'AIzaSyAbtmt94beyjUwpDHJGvdd8tK51ekRAct4');
       // define('API_ACCESS_KEY', 'AIzaSyD-kLb5eqfuuFILUv_YzRHGjDSIVm3DbC0');
        define('API_ACCESS_KEY', 'AIzaSyAbeHrrkL9Pei7LvaxExKKCMAem_HSCYa0');
        $time = str_replace('.','',microtime(true));
        $msg = array
        (
            "id"        => $time,
            "type"      => strtolower($arrNotificationData['type']) , //promotional
            "category"  => strtolower($arrNotificationData['category']),
            'message'   => array("id" => $arrNotificationData['post_id']),
            'title'     => $this->specialChartoHTML($arrNotificationData['desc']),
            'subtitle'  => $this->specialChartoHTML($arrNotificationData['desc']),
            'tickerText'=> $this->specialChartoHTML($arrNotificationData['desc']),
            'vibrate'   => 1,
            'sound'     => 1,
            'custom_data'=> $this->specialChartoHTML($arrNotificationData['desc']),
            'largeIcon' => 'large_icon',
            'smallIcon' => 'small_icon'
        );

        /*
		$fields = array
        (
            'registration_ids'  => (array) $arrNotificationData['device_id'],
            'data'          => $msg,
			'delay_while_idle' => true
        );
		*/

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

        usleep(100000);
		//echo "<br>All Ids<pre>"; print_r($arrNotificationData['device_id']);
		$resultArr = $this->multiThreadCurlRequest($headers, $msg, $arrNotificationData['device_id'], 4);

		/*
        $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, true));
        $result = curl_exec($ch );
        curl_close( $ch );
        $resultArr = (array) json_decode($result);
        echo "<pre>";print_r($resultArr);
		*/
        # $this->error_log_entry("Notification: - ".date('YmdHis'). " - \n", "log.notification.txt");
        echo "tarun";
		return $resultArr;
    }

	function multiThreadCurlRequest($headers, $msg, $arrDeviceId, $thread_width) {
		$threads = 0;
		$master = curl_multi_init();
		$curl_opts = array(
			CURLOPT_URL => 'https://android.googleapis.com/gcm/send',
			CURLOPT_FOLLOWLOCATION => TRUE,
			CURLOPT_MAXREDIRS => 5,
			CURLOPT_CONNECTTIMEOUT => 15,
			CURLOPT_TIMEOUT => 15,
			CURLOPT_POST => TRUE,
			CURLOPT_HTTPHEADER => $headers,
			CURLOPT_RETURNTRANSFER => TRUE,
			CURLOPT_SSL_VERIFYPEER => FALSE
		);

		$results = array();
		$processRec = 5;

		$count = 0;
		while(count($arrDeviceId) > 0)
		{
			$popIds = $popDeviceId = $popDevice = array();
			//echo "<br>LL<pre>"; print_r($arrDeviceId);
			for( $i = 0 ; $i < $processRec; $i++) {
				$popDeviceId = array();
				$popDeviceId = array_pop($arrDeviceId);
				if($popDeviceId['id'] != '' && $popDeviceId['device_id'] != '') {
					$popIds[] = $popDeviceId['id'];
					$popDevice[] = $popDeviceId['device_id'];
				}
			}

			//$popDeviceId = array_filter($popDeviceId);

			//echo "Android Device Ids List<br><hr><pre>"; print_r($popIds);  echo "<br>"; print_r($popDevice); //die;

			$ch = curl_init();
			$url = 'https://android.googleapis.com/gcm/send';
			$fields = array();
			$fields = array
			(
				'registration_ids'  => $popDevice,
				'data'          => $msg,
				'delay_while_idle' => true
			);
			$curl_opts[CURLOPT_URL] = 'https://android.googleapis.com/gcm/send';
			$curl_opts[CURLOPT_POSTFIELDS] = json_encode($fields, true);

			curl_setopt_array($ch, $curl_opts);
			curl_multi_add_handle($master, $ch); //push URL for single rec send into curl stack

			$results[$count] = array("url" => $url, "handle" => $ch, 'ids' => json_encode($popIds, true));
			$threads++;
			$count++;
			if($threads >= $thread_width) { //start running when stack is full to width
				while($threads >= $thread_width) {
					usleep(100);
					while(($execrun = curl_multi_exec($master, $running)) === -1){}
					curl_multi_select($master);
					// a request was just completed - find out which one and remove it from stack
					while($done = curl_multi_info_read($master)) {
						foreach($results as &$res) {
							if($res['handle'] == $done['handle']) {
								$res['result'] = curl_multi_getcontent($done['handle']);
								$results['result'][] = $res['result'];
							}
						}
						curl_multi_remove_handle($master, $done['handle']);
						curl_close($done['handle']);
						$threads--;
					}
				}
			}
		}

		
		do { //finish sending remaining queue items when all have been added to curl
			usleep(100);
			$count++;
			while(($execrun = curl_multi_exec($master, $running)) === -1){}
			curl_multi_select($master);
			while($done = curl_multi_info_read($master)) {
				foreach($results as &$res) {
					if($res['handle'] == $done['handle']) {
						$res['result'] = curl_multi_getcontent($done['handle']);
						$results[$count][] = $res['result'];
					}
				}
				curl_multi_remove_handle($master, $done['handle']);
				curl_close($done['handle']);
				$threads--;
			}
		} while($running > 0); 


		curl_multi_close($master);
		return $results;
	}


    function iosSend($arrNotificationData = array())
    {
        //ini_set('memory_limit','8M');
		header('Content-Type: application/json');
        set_time_limit(0);

        if(empty($arrNotificationData) || empty($arrNotificationData['device_id']) || $arrNotificationData['desc'] == '') {
			$resultArr['success'] = 2;
			$this->error_log_entry("Notification Failed: - ".date('YmdHis') . " - " . serialize($resultArr) ."\n", "log.notification.txt");
			return $resultArr;
        }

        if($arrNotificationData['data'] != '' && $arrNotificationData['data'] != 'null') {
            $correctData = json_decode($arrNotificationData['data'], true);
        } else {
            $correctData = json_decode('{"id":"'.$arrNotificationData['post_id'].'"}',true);
        }
		usleep(100000);
		# --------------------------------------------------------------------------
		echo $pushmsg = $this->specialChartoHTML($arrNotificationData['desc']); // $_GET or $_POST
		$badge = 3; // int
		$sound = 'default'; // string - sound name

		$payload = array();
		$payload['aps'] = array(
					'alert' => $pushmsg,
					'badge' => intval($badge),
					'sound' => $sound
					);
		$payload["type"] = $arrNotificationData['type'];
		$payload["category"] = $arrNotificationData['category'];
		$payload["data"] = $correctData;
		$payload = json_encode($payload);

		$apns_url = 'gateway.push.apple.com'; // Set Later
		$apns_cert = '/home/steelmin/public_html/api/ck.pem'; // Set Later
		$apns_port = 2195;

		//  You will need to put your device tokens into the $device_tokens array yourself

		$device_tokens = $arrNotificationData['device_id']; // tokens!!!
		//echo "Device Token<br><pre>"; print_r($device_tokens);
		$finalArr = array();

		$count = 0;
		$processRec = 300;
		if(count($device_tokens) > 0)
		{
			$popIds = $popDeviceId = $popDevice = array();
			for( $i = 0 ; $i < $processRec; $i++) {
				if(empty($device_tokens)) break;
				$popDeviceId = array();
				$popDeviceId = array_pop($device_tokens);
				if($popDeviceId['id'] != '' && $popDeviceId['device_id'] != '') {
					$popIds[] = $popDeviceId['id'];
					$popDevice[] = $popDeviceId['device_id'];
				}
			}			

			//echo "IOS Device Ids List<br><hr><pre>"; print_r($popIds);  echo "<br>"; print_r($popDevice);
			echo "<br>IOS Connection: ".++$count."<hr>";
			$stream_context = stream_context_create();
			stream_context_set_option($stream_context, 'ssl','local_cert',$apns_cert);
			$apns = stream_socket_client('ssl://'.$apns_url.':'.$apns_port, $error, $error_string, 2, STREAM_CLIENT_CONNECT, $stream_context);

			foreach($popDevice as $key => $deviceIds) {
				$apns_message = chr(0).chr(0).chr(32).pack('H*',str_replace('    ','',$deviceIds)).chr(0).chr(strlen($payload)).$payload;
				$result = fwrite($apns, $apns_message);
				$finalArr[] = array('result'=>$result,'device_id'=>$popIds[$key]);
			}
			
			@socket_close($apns);
			@fclose($apns);
		}
		//die;

		/*
		foreach($device_tokens as $device_token) {
			$apns_message = chr(0).chr(0).chr(32).pack('H*',str_replace('    ','',$device_token['device_id'])).chr(0).chr(strlen($payload)).$payload;
			$result = fwrite($apns, $apns_message);
			$finalArr[] = array('result'=>$result,'device_id'=>$device_token['id']);
		}
		*/
		
		@socket_close($apns);
		@fclose($apns);
		# --------------------------------------------------------------------------

        return $finalArr;
    }

    /**
     * To post notification to particular device_id with notification_id
     * @param Request $request
     */

public function post_notification(Request $request)
{
		$varSuccess = 0;
		$varFail = 0;
		if($request->has('notification_id') && $request->has('device_id'))
		{
			# echo "<pre>";
			# print_r($request->input('device_id'));
			# echo $request->input('notification_id');
			# die;
			$success_device = $fail_device = $input = $dataArr = $arrAndroidDevice = $arrIOSDevice = array(); $input = '';
			$input = (array) $request->input('device_id');
			$dataArr = (array) explode(",",implode(",",$input));
			echo "<br>All Post Device Ids<pre>";
			print_r($dataArr);

			if(!empty($dataArr)) {
				/**
				 * Check notification id
				 */
				$arrNotificationData = DB::table('gcm_notification_type')
				->select('data' , 'type' , 'category' ,'desc', 'post_id')
				->where('id' , '=' , $request->input('notification_id'))
				->first();

				$arrNotificationData['notification_id'] = $request->input('notification_id');
				$arrNotificationData['data']            = '';
			}

			if(is_array($dataArr) && !empty($dataArr))
			{
				$deviceAll = DB::table('gcm_device')
					->select('id', 'device_id' ,'device' , 'user_id' )
					->whereIn('id', $dataArr)
					->where('status', '=', 'enable')
					->get();
					//->first();
				# echo "<pre>";
				# print_r($deviceAll);
				# echo "<br><hr><br>";
				foreach($deviceAll as $device) {
					if(is_array($device))
					{
						/**
						 * Update table about notification
						 */
						$status = "pending" ;
						$insert = array(
							"device_id" =>  $device['device_id'] ,
							"notification_id" => $request->input('notification_id') ,
							"user_id" => $device['user_id'] ,
							"status" => $status
						);

						$id = DB::table('gcm_notification_send')
						->insertGetId($insert);

						$arrNotificationData['id'] = $id;
						if($device['device'] == 'android')	$arrAndroidDevice[]	= array('id' => $device['id'], 'device_id' => $device['device_id']);
						if($device['device'] == 'ios')		$arrIOSDevice[]		= array('id' => $device['id'], 'device_id' => $device['device_id']);
					}
				}
			} else {
				$varFail = 1;
				$fail_device['error'][] = array("success"=>$res['success'] , "device_id" => json_encode($dataArr, true) , "result" => "Device Id Not Found");
			}
			# echo "<pre>";
			# print_r($arrAndroidDevice);
			# print_r($arrIOSDevice);
			# die;

			if(!empty($arrAndroidDevice)) {
				# For Android Devices
				$arrAndroidDevice = array_filter($arrAndroidDevice);
				$arrNotificationData['device_id'] = $arrAndroidDevice;
				$res = $this->androidSend($arrNotificationData);
				echo "<br>Android<hr><br><pre>";
				print_r($res);
				if(isset($res)) {
					$varSuccess = 1;
					//$success_device['android'][] = array("device_id"=> json_encode($arrAndroidDevice,true) , "result"=> $res);
				} else {
					$varFail = 1;
					//$fail_device['android'][] = array("success" => 0, "result" => "No Android Device Found");
				}
			}

			if(!empty($arrIOSDevice)) {
				# For IOS Devices
				$arrIOSDevice = array_filter($arrIOSDevice);
				$arrNotificationData['device_id'] = $arrIOSDevice;
				$res = $this->iosSend($arrNotificationData);
				echo "<br>IOS<hr><br><pre>";
				print_r($res);
				if(isset($res)) {
					$varSuccess = 1;
					//$success_device['ios'][] = array("device_id"=> json_encode($arrIOSDevice,true) , "result"=> $res);
				} else {
					$varFail = 1;
					//$fail_device['ios'][] = array("success" => 0, "result" => "No IOS Device Found");
				}
			}
		}
        else
        {
            $fail_device['error'][] = array("success"=>0 , "device_id" => 0 , "result" => "Incomplete Notification Params - Send device_id as array, notification_id as integer.");
			$varFail = 1;
        }

	//$this->error_log_entry("\n-------------------------------------------\n Notification Result - " . date('YmdHis') . "\n-------------------------------------------\n". " Success: " . COUNT($success_device) . " - Failed: "  . COUNT($fail_device) . " - \n", "log.notification.txt");
	echo "<br><hr><br>";

	return new JsonResponse(array(
			"success" => $varSuccess ,
			"fail" => $varFail ,
	));

	/*
	return new JsonResponse(array(
			"success" => $success_device ,
			"fail" => $fail_device ,
	));
	*/
}

	public function post_notification_old(Request $request)
    {
        if( $request->has('notification_id')
            && $request->has('device_id')
        )
        {
            /**
             * Loop for multiple devices
             */
            $success_device = array() ;
            $fail_device = array() ;
            $input = array();
            $dataArr = array();
            $input = '';

            $input = (array) $request->input('device_id');
            $dataArr = (array) explode(",",implode(",",$input));
			//print_r($dataArr);

            foreach($dataArr as $ky => $device_id )
            {
                 /**
                 * Check if valid device
                 */

                $device = DB::table('gcm_device')
                    ->select('device_id' ,'device' , 'user_id' )
                    ->where('id' , '=' , $device_id )
                    ->first() ;
                //var_dump( $device);

                if( is_array($device ) )
                {

                    /**
                     * Check notification id
                     */
                    $arrNotificationData = DB::table('gcm_notification_type')
                        ->select('data' , 'type' , 'category' ,'desc', 'post_id')
                        ->where('id' , '=' , $request->input('notification_id'))
                        ->first();

                    /**
                     * Update table about notification
                     */
                    $status = "pending" ;
                    $insert = array(
                        "device_id" =>  $device_id ,
                        "notification_id" => $request->input('notification_id') ,
                        "user_id" => $device['user_id'] ,
                        "status" => $status
                    );

                    $id = DB::table('gcm_notification_send')
                        ->insertGetId( $insert );


                    if(is_array($arrNotificationData))
                    {

                        if($arrNotificationData['data'] == '' || $arrNotificationData['data'] == NULL || !isset($arrNotificationData['data']) || empty($arrNotificationData['data'])) {
                            $arrNotificationData['data'] = '';
                        } else if($arrNotificationData['data'] != '') {
                            $arrNotificationData['data'] = json_decode($arrNotificationData['data'],true);
                        }

                        $arrNotificationData['device_id']       = $device['device_id'];
                        $arrNotificationData['notification_id'] = $request->input('notification_id');
                        $arrNotificationData['user_id']         = $device['user_id'];
                        $arrNotificationData['device']          = $device['device'];
                        $arrNotificationData['id']              = $id;

                        /**
                         * Send the notification to mobile
                         */
                        if($device['device'] == 'android') // || $device['device'] == 'ios'
                        {

                            /**
                             * Send notification to device
                             */
                            /*$result = $this->dispatch(new Gcm_notification_send( $device['device_id'] ,
                                $request->input('notification_id'),
                                $device['user_id'] ,
                                $device['device'] ,
                                $id  ));*/
                            $res = $this->androidSend($arrNotificationData);

                            /*
                            #Response
                            $res = Array ([multicast_id] => 6653715181338628301 [success] => 1 [failure] => 0 [canonical_ids] => 0 [results] => Array ( [0] => stdClass Object ( [message_id] => 0:1472150501425327%bddaf211f9fd7ecd)))
							*/

                            if($res['success'] == 1) {
                                $success_device[] = array("success"=>$res['success'], "device_id"=>$device_id, "result"=>$res['multicast_id']);
                            } else {
                                $fail_device[] = array("success"=>$res['success'] , "device_id" => $device_id , "result" => "Notification failed on android device");
                            }

                        } else if($device['device'] == 'ios') {

							$res = $this->iosSend($arrNotificationData);
                            if($res['success'] == 1) {
                                $success_device[] = array("success"=>$res['success'], "device_id"=>$device_id , "result"=>"success");
                            } else {
                                $fail_device[] = array("success"=>$res['success'] , "device_id" => $device_id , "result" => "Notification failed on ios device");
                            }
                        }
                        else
                        {
                            $fail_device[] = array("success"=>0 , "device_id" => $device_id , "result" => "Notification of this device type is not configured");
                        }
//                      abort(500 , "Notification of this device type is not configured") ;
                    }
                    else {
                        //abort(206 , "notification id not registered") ;
                    }
                }
                else {
                    $fail_device[] = array( "id" => $device_id , "error" => "Device not registered");
                }
//                    abort(206 , "Device not registered") ;
            }
        }
        else
        {
            $fail_device[] = array("success"=>0 , "device_id" => 0 , "result" => "Incomplete Notification Params - Send device_id as array, notification_id as integer.");
        }

        $this->error_log_entry("\n-------------------------------------------\n Notification Result - " . date('YmdHis') . "\n-------------------------------------------\n". " Success: " . COUNT($success_device) . " - " . serialize($success_device) . " - Failed: "  . COUNT($fail_device) . " - " . serialize($fail_device) ."\n", "log.notification.txt");
        return new JsonResponse(array(
                "success" => $success_device ,
                "fail" => $fail_device ,
            )) ;
        abort('206', "Request with notification_id and device_id");
    }

    public function getdeviceID(Request $request){
        $id = DB::table('gcm_device')
            ->where('device_id' , $request->id)
            ->first();
        return new JsonResponse(array(
            "id" => $id
        ));
    }


    /**
     * To create notification
     * @param Request $request
     */
    public function create_notification(Request $request)
    {
        if(
            $request->has('type')
            && $request->has('category')
            && $request->has('desc')
        )
        {
            if($request->input('type') == "transactional")
            {
                if(! $request->has('data'))
                    abort(206 , "Please input data") ;

            }
//            var_dump(($request->input('data')) ) ;
//            die ;
            $insert = array(
                "data" => json_encode($request->input('data')),
                "type" => $request->input('type') ,
                "category" => $request->input('category'),
                "desc" =>  $request->input('desc') ,
            ) ;
            $id = DB::table('gcm_notification_type')
                ->insertGetId($insert) ;

            return new JsonResponse(array(
                "status#" => "1" ,
                "id#" => $id
            )) ;
        }
        abort(206, "Pratial input") ;
    }
	
	
	public function post_notificationSend(Request $request)
    {
		
		$arrNotificationData = json_decode(file_get_contents("php://input"),true);
		if(!empty($arrNotificationData) && !empty($arrNotificationData['emailOther']) && !empty($arrNotificationData['email'])) {
			$query =  DB::table('gcm_device')
				->leftJoin('tbl_members' , 'gcm_device.user_id' , '=' , 'tbl_members.id')
				->select(
					"tbl_members.name" , 'gcm_device.device_id' ,'gcm_device.device') ;

			$query->where('tbl_members.email' , '=' , $arrNotificationData['emailOther'])->first() ;

			$data = array(
				"device" => $query->get()
			);
			$result = $data['device'][0];
			//print_r($data['device'][0]);
			$badge = 0; // int
			$sound = 'default'; // string - sound name
			$alert = $arrNotificationData['alert']; // string
			$chat = 'true'; // string
			$emailId = $arrNotificationData['email']; // string

			
			
			$device_token = $result['device_id']; // token!!!
			$device_type = $result['device']; // token!!!
			
			if($device_type == "ios"){
				$payload = array();
				$payload['aps'] = array(
						'alert' => $alert,
						'badge' => $badge,
						'chat' => $chat,
						'emailId' => $emailId,
						'sound' => $sound
						);
				$payload = json_encode($payload);
				$payload = str_replace("*****+++*****","\\",$payload);
				$apnsHost='gateway.push.apple.com'; // Set Later
				$apnsPort=2195;
				$apnsCert='/home/steelmin/public_html/api/ck.pem'; // Set Later
				$passphrase = '1234';
				$streamContext=stream_context_create();
				stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
				stream_context_set_option($streamContext, 'ssl', 'passphrase', $passphrase);
				$apns=stream_socket_client('ssl://'.$apnsHost.':'.$apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
				if (!$apns) {
					// print "Failed to connect $error $errorString";
					// exit;
				}
				else {
					//print "Notification send\n";			
				}
				//var_dump($apns);
				$apnsMessage=chr(0).chr(0).chr(32).pack('H*' , str_replace(' ', '', $device_token)).chr(0).chr(strlen($payload)).$payload;
				//var_dump($apnsMessage);
				//log_message('info', 'device-token-'.(string)$apnsMessage);
				fwrite($apns, $apnsMessage);
				@socket_close($apns);
				@fclose($apns);
			}
			elseif($device_type == "android"){
				
				$url = 'https://android.googleapis.com/gcm/send'; 
				$registrationIds = array( $device_token );
				$msg = array
						(
						'alert' => $alert,
						'badge' => $badge,
						'chat' => $chat,
						'emailId' => $emailId,
						'sound' => $sound
						);
			   $fields = array(
				   'registration_ids' => $registrationIds,
				   'data' => $msg,
			   );

			   $headers = array(
				   'Authorization: key=' . 'AAAAXh72C-8:APA91bE6sfXuL9PrgF7oKwczoAaOoiSGO4dAmRXbSF1-oGj6liOjszw3inktNS2gp-ZEBCIq6xs6Eg0Zimt6ZJ4o-AKifOtht4z90tr6DPhbAXVNS70jXT8nEo4nSBA0ezKtS-etYbao',
				   'Content-Type: application/json'
			   );
			   // Open connection
			   $ch = curl_init();

			   // Set the url, number of POST vars, POST data
			   curl_setopt($ch, CURLOPT_URL, $url);

			   curl_setopt($ch, CURLOPT_POST, true);
			   curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

			   // Disabling SSL Certificate support temporarly
			   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

			   curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

			   // Execute post
			   $result = curl_exec($ch);
			   if ($result === FALSE) {
				   die('Curl failed: ' . curl_error($ch));
			   }

			   // Close connection
			   curl_close($ch);
			}
		}
    }
}