<?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()   
	{

		$data["promotions"] = $this->common->readdatafromcollectionwhereclause("Promotions");
		$this->template->template_render('promotion', $data); 
	}


public function updatepermotiondata($id){
		$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();
$data=$this->input->post();
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'];
		}
		$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('editpromotion', $data); 
	



	}
	public function addPromotionforuser()   
	{
		$data = $this->input->post();
		$data["id"] = time();
		$data["startTime"] = strtotime($data["startTime"]) * 1000;
		$data["endTime"] = strtotime($data["endTime"]) * 1000;
		$data["type"] = "user";
		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',"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');
	}
	
	
}
