<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Promotion extends CI_Controller {
    function __construct()
 	{
	    parent::__construct();
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->model('common');
		$this->load->library('session');
		$this->load->database();
		$this->load->library(array('form_validation','template'));
		define( 'API_ACCESS_KEY1', 'AAAAFqAjjzI:APA91bGlwApVaPeYiBww8P8N5vRKAqV5L2HMgC2lEtwS_9RdQfaK_9_SXoLfGJ9SJ3anynELX5gt-S8Vf8I-34QMkx84UB73LWIkI4j2pNeRzNhA3IG2F-JP9H3FRr-brdWU3Ht4DSUA');
	}

	public function index()   
	{
//echo "yes";
		$data["promotions"] = $this->common->readdatafromcollectionwhereclause("Promotions");
	
		$this->template->template_render('promotion', $data); 
	}

	public function notification(){
		$data["promotions"] = $this->common->readdatafromcollectionwhereclause("Notification","senderType","==","admin");
	
		$this->template->template_render('notification', $data); 
	}


public function updatenotificationdata(){
	//	$firebase = $this->firebase->init();
	//	$storage = $firebase->createStorage();
		//$defaultBucket = $storage->getBucket();
		$data=$this->input->post();
		$id=$data['id'];
		$data["promotions"] = $this->common->updatedatamodel("Notification",$id,$data);
		$this->session->set_flashdata('successmessage', 'Notification has been updated successfully');

		redirect('promotion/notification');
	}
public function updatepromodata($id=""){
	//	$firebase = $this->firebase->init();
	//	$storage = $firebase->createStorage();
		//$defaultBucket = $storage->getBucket();
		$data=$this->input->post();
		$id=$data['id'];

		$data['Percentage']=(float)$data['Percentage'];
		$data["startTime"] = strtotime($data["startTime"]) * 1000;
		$data["endTime"] = strtotime($data["endTime"]) * 1000;

		$data["promotions"] = $this->common->updatedatamodel("Promotions",$id,$data);
		$this->session->set_flashdata('successmessage', 'Promotion has been updated successfully');

		redirect('promotion');
	}
	public function editPromotion($id){


		$data['id']=$id;
		$data["promotions"] = $this->common->readdatadocument("Promotions",$id);

		 $this->template->template_render('addPromopage', $data); 
	
	}
	public function addPromopage(){


		//$data['promotions']="";
		$this->template->template_render('addPromopage',$data); 
	
	}
public function addNotification(){
	$data=array();
		$this->template->template_render('addnotificationpage',$data); 
}
	public function editNotification($id){


		$data['id']=$id;
		$data["promotions"] = $this->common->readdatadocument("Notification",$id);

		 $this->template->template_render('addnotificationpage', $data); 
	
	}

 public function sendToOne()
    {
        $token = 'your-device-token-here';
        $title = 'Test Notification';
        $body = 'This is a test push to one device.';
        $data = ['type' => 'alert'];

        $result = $this->firebase->sendPushNotification($token, $title, $body, $data);

        echo json_encode($result);
    }
public function addnotificationdata()   
	{
		
		$data = $this->input->post();
		$id="notification".time();
		$data["id"] = $id;
		$data["time"] = time() * 1000;
		$data['senderID']="RJb43Hc4PjSST6mRMzXtFYVd6t93";
		$data['type']="adminnotification";
		$data['senderType']="admin";
		// echo "<pre>";
		// print_r($data);
		// echo "</pre>";
		// exit;

		
		$listofid=array();
		$tokenlist=array();
		$userlist=$this->common->readdatafromcollectionbetween("Users","userRole","===","user");
		foreach($userlist as $u=>$j){
			array_push($listofid,$u);
			if($j['token'] !=""){
				array_push($tokenlist,$j['token']);
			}

		}
		$data['userID']=$listofid;
		$data['tokenlist']=$tokenlist;


		//$this->common->adddatamodel("Notification", $data["id"], $data);

		// echo "<pre>";
		// print_r($tokenlist);
		// echo "</pre>";
		// echo "-----------------";
		// exit;
		for($j=0;$j<count($tokenlist);$j++){
			 $title =$this->input->post('title');
        $body = $this->input->post('message');;
        $data = ['type' => 'adminnotification','id'=>$id];
		$token=$tokenlist[$j];

       $result = $this->firebase->sendPushNotification($token, $title, $body, $data);

      // echo json_encode($result);
	   //exit;
		}




	//	$this->mytest($data["id"],$data['message'],'promotion',"user");	
		$this->session->set_flashdata('successmessage', 'New Promotion added successfully');
		redirect('Promotion/addNotification');
	}
	function jana(){
		$j1=array(
			"dqXmsQfhfkJHpeU4soSQxS:APA91bEKNTpVLItjJodLjsO_GDiVmbrdOo5jfIdZvu9szVtf0PNBbkvP-9O50wLkQQZPTuyv0-odPFn45FJQK7Di_qu390qK_nvWemqUXUQsl_NR9_GEVOs",
		"eiaxxE7dxU9Cqs4n1wDwPw:APA91bHw9_u0Am6rTyVKmHVGTXRSeb2EdaSC95Fm55EaBml3nfmDampCMCHYoUI-vBOskYZhtMz4L85zjGZF5BJqvCUOchK7oqsPha0GryHYGT7eEr3EkIA",
"ciEIaAgoKkSDlaHICW_Juh:APA91bHUPZp7SSGyJ1QqNDTiECR3_abNnLKLBwsnX9B3MDiTkJGy-98POtnjPPxyrQjFGnXSq_GGGKiS3SYX0KVo0eltnetGvgbz5ofB2UCkGh_12PkLBzs",
"e6_oCXangEmxq-EIvJRqdn:APA91bGaopoOG3lPYmJriGI2iuucimVcwYc6VL-0chZRlAX5zDinlTmxLW_61AiqErrjFYj90KROtnD2W2ZlcegKQuyyxWL58VlJwRSUEpnekXN7fyIf9ac"
		);
		echo count($j1);
	//	exit;
		for($j=0;$j<count($j1);$j++){
			 $title = 'Test Notification';
        $body = 'This is a test push to one device.';
        $data = ['type' => 'alert'];
		$token=$j1[$j];
		echo $j;		
       $result = $this->firebase->sendPushNotification($token, $title, $body, $data);

       echo json_encode($result);
	   
		}
   
	}

	public function addpromodata()   
	{
		$data = $this->input->post();
		$data["id"] = time();
		$data['Percentage']=(float)$data['Percentage'];
		$data["startTime"] = strtotime($data["startTime"]) * 1000;
		$data["endTime"] = strtotime($data["endTime"]) * 1000;
		settype($data["id"], "string");

/*
if ($_FILES['file']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['file']['tmp_name']),
				[
					'name' => "permo" . rand() . time() . $_FILES['file']['name'],
				]
			);

			$data['url'] = $uploadedFile->info()['mediaLink'];
		}

*/
		$this->common->adddatamodel("Promotions", $data["id"], $data);
	//	$this->mytest($data["id"],$data['message'],'promotion',"user");	
		$this->session->set_flashdata('successmessage', 'New Promotion added successfully');
		redirect('promotion');
	}

public function mytest($id="111",$msg="new data",$type="promotion",$ntype="user"){
	$data["promotions"] = $this->common->readdatafromcollectionbetween2where("Users","userRole","=",$ntype,"token","!=","");
		$token=array();
		$userIdArray=array();
	


		foreach($data["promotions"] as $l=>$j){
			 if(!empty($j['token'])  && $j['token'] !=""){
			 	  $userIdArray[$l] = false;
			array_push($token, $j['token'])	; 	
			 }
	
		}
		// echo "<pre>";
		// print_r($token);

		$notification=$this->send_notification($token,"New Promotion",$msg,$id,$type);
// print_r($notification);
// echo "</pre>";
}

function send_notification($token_id,$title,$body,$id,$type){
	 
	$icon=base_url('uploads/logo.png');
	
	$finalPostArray = array('registration_ids' => $token_id,
								'notification' => array('body' => $body,
														'title' => $title,
														"image"=> $icon,
														   "sound"=> "sample4_out.caf"
													),
									'aps'=>array(
										"sound"=> "sample4_out.caf"
									),				
								"data"=> array("click_action"=> "FLUTTER_NOTIFICATION_CLICK",
												"type"=>$type,
												"id"=>$id,
												"sound"=> "sample4_out.caf", 
												"soundios"=> "sample4_out.caf",
												"vibrate"=> 1)); 
		
	
		
		
		$headers = array
				(
					'Authorization: key=' . API_ACCESS_KEY1,
					'Content-Type: application/json'
				);
	#Send Reponse To FireBase Server	
			$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, false );
			curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $finalPostArray ) );
			$result['mystatus'] = curl_exec($ch );
			curl_close( $ch );
	#Echo Result Of FireBase Server
	//$result['firbasestatus']=$fields;
	return $result;
		}
	public function addPromotion()   
	{
		$data = $this->input->post();
		$data["id"] = time();
		$data["startTime"] = strtotime($data["startTime"]) * 1000;
		$data["endTime"] = strtotime($data["endTime"]) * 1000;
		$data["noOfTrips"] = (int)$data["noOfTrips"];
		$data["remainingRides"] = NULL;
		$data["rideModels"] = NULL;
		$data["type"] = "driver";
		settype($data["id"], "string");

	$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();

if ($_FILES['file']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['file']['tmp_name']),
				[
					'name' => "permo" . rand() . time() . $_FILES['file']['name'],
				]
			);

			$data['url'] = $uploadedFile->info()['mediaLink'];
		}


		$this->common->adddatamodel("Promotions", $data["id"], $data);
		$this->mytest($data["id"],$data['message'],'promotion',"driver");		
		
		$this->session->set_flashdata('successmessage', 'New Promotion added successfully');
		redirect('promotion');
	}

	public function deletePromotion($id)   
	{
		$this->common->deletedatamodel("Promotions", $id);
		$this->session->set_flashdata('successmessage', 'Promotion Deleted');
		redirect('promotion');
	}
		public function deleteNotification($id)   
	{
		$this->common->deletedatamodel("Notification", $id);
		$this->session->set_flashdata('successmessage', 'Notification Deleted');
		redirect('promotion/notification');
	}
	
	
}
