<?php

/*

	Controller For Lwd..

*/

Class Lwd extends CI_Controller
{
	function __construct()
	{
		parent::__construct();
		$this->load->helper('url');
		$this->load->library('session');
		$this->load->model('lwds');
		$this->load->model('cost_center');
		$this->load->model('contractareas');
		$this->load->model('offices');
		$this->load->library('session');
		$this->load->library('pagination');
		if( $this->session->userdata('login_id') != 1 )
		{
			$this->session->set_flashdata('error_msg','Not Login Yet');
			redirect('user/index');
			//echo "no login"; exit;
		}
		
	}

	function index()
	{
		
	   if(isset($_POST['costcenterlwd']) && !empty($_POST['costcenterlwd']) && isset($_POST['contractarealwd']) && !empty($_POST['contractarealwd']) && isset($_POST['officelwd']) && !empty($_POST['officelwd'])){
		   
		    $this->session->set_userdata('costcenterlwd',$_POST['costcenterlwd']);
			$this->session->set_userdata('contractarealwd',$_POST['contractarealwd']);
			$this->session->set_userdata('officelwd',$_POST['officelwd']);
			$data['costcenter'] = $this->cost_center->cc_list();
			$data['contract_areas'] = $this->contractareas->get_all();
			$data['contract_costcenter'] = $this->offices->contract_costcenter();
			$data['office_list'] = $this->offices->get_all_offices();
			$office_list = $this->offices->office_list();
			
			$contractarea_detail = [];

			if( $this->input->post('select_limit') !="" )
			{
				$data['current_limit'] = $this->input->post('select_limit');
			}
			else
			{
				$data['current_limit'] = 25;
			}

			$config = [

				'base_url' 			=> site_url("lwd/index"),
				'total_rows'		=> $this->lwds->get_count_lwd(),
				'per_page'			=> $data['current_limit'],
				'full_tag_open'		=> '<ul class="pagination pull-right">',
				'full_tag_close'	=> '</ul>',
				'first_tag_open'	=> '<li>',
				'first_tag_close'	=> '</li>',
				'last_tag_open'		=> '<li>',
				'last_tag_close'	=> '</li>',
				'cur_tag_open'		=> '<li class="active"><a>',
				'cur_tag_close'		=> '</a></li>',
				'num_tag_open'		=> '<li>',
				'num_tag_close'		=> '</li>',
				'next_tag_open'		=> '<li>',
				'next_tag_close'	=> '</li>',
				'prev_tag_open'		=> '<li>',
				'prev_tag_close'	=> '</li>'
			];

			
			
			if($this->session->userdata('type')=="office") {

				if( $this->input->get('searchbar') )
				{
					$data['detail'] = $this->lwds->office_list_search_lwd($this->session->userdata('office_id'),$this->input->get('searchbar'));
				}
				else
				{
					$data['detail'] = $this->lwds->get_lwd_office_list($this->session->userdata('office_id'),$config['per_page'], $this->uri->segment(3));
				}
				
				
				$contractareaname         = $this->lwds->getcontractareaname($this->session->userdata('contractarea_id'));
				$costcentername           = $this->lwds->getcostcentername($contractareaname[0]->costcenter_id);
				$data['contractareaname'] = $contractareaname[0]->contractarea_name;
				$data['costcentername']   = $costcentername[0]->costcenter_name;
				
					
			}else{
				
				if( $this->input->get('searchbar') )
				{
					$this->lwds->search_term = $this->input->get('searchbar');
					$data['detail'] = $this->lwds->office_list_search();			
				}
				else
				{
					$data['detail'] = $this->lwds->get_lwd_list_filter($_POST['officelwd'], $config['per_page'], $this->uri->segment(3));
				}
				 
				
			}
			
			
			
			$this->pagination->initialize($config);
			
			$this->load->view('lwd/lwd', $data);
				
	   }else{
	      
	      
		    $this->session->set_userdata('costcenterlwd',"");
			$this->session->set_userdata('contractarealwd',"");
			$this->session->set_userdata('officelwd',"");
			$data['costcenter'] = $this->cost_center->cc_list();
			$data['contract_areas'] = $this->contractareas->get_all();
			$data['contract_costcenter'] = $this->offices->contract_costcenter();
			$data['office_list'] = $this->offices->get_all_offices();
			$office_list = $this->offices->office_list();
			
			$contractarea_detail = [];

			if( $this->input->post('select_limit') !="" )
			{
				$data['current_limit'] = $this->input->post('select_limit');
			}
			else
			{
				$data['current_limit'] = 25;
			}

			$config = [

				'base_url' 			=> site_url("lwd/index"),
				'total_rows'		=> $this->lwds->get_count_lwd(),
				'per_page'			=> $data['current_limit'],
				'full_tag_open'		=> '<ul class="pagination pull-right">',
				'full_tag_close'	=> '</ul>',
				'first_tag_open'	=> '<li>',
				'first_tag_close'	=> '</li>',
				'last_tag_open'		=> '<li>',
				'last_tag_close'	=> '</li>',
				'cur_tag_open'		=> '<li class="active"><a>',
				'cur_tag_close'		=> '</a></li>',
				'num_tag_open'		=> '<li>',
				'num_tag_close'		=> '</li>',
				'next_tag_open'		=> '<li>',
				'next_tag_close'	=> '</li>',
				'prev_tag_open'		=> '<li>',
				'prev_tag_close'	=> '</li>'
			];

			//debug($config,1);
			
			if($this->session->userdata('type')=="office") {

				if( $this->input->get('searchbar') )
				{
					$data['detail'] = $this->lwds->office_list_search_lwd($this->session->userdata('office_id'),$this->input->get('searchbar'));
				}
				else
				{
					$data['detail'] = $this->lwds->get_lwd_office_list($this->session->userdata('office_id'),$config['per_page'], $this->uri->segment(3));
				}
				
				
				$contractareaname         = $this->lwds->getcontractareaname($this->session->userdata('contractarea_id'));
				$costcentername           = $this->lwds->getcostcentername($contractareaname[0]->costcenter_id);
				//debug($costcentername,1);
				$data['contractareaname'] = $contractareaname[0]->contractarea_name;
				$data['costcentername']   = $costcentername[0]->costcenter_name;
				
					
			}else{
				
				if( $this->input->get('searchbar') )
				{
					$this->lwds->search_term = $this->input->get('searchbar');
					$data['detail'] = $this->lwds->office_list_search();			
				}
				else
				{
					$data['detail'] = $this->lwds->get_lwd_list($config['per_page'], $this->uri->segment(3));
				}
				 
				
			}
			
			$data["links_up"] = $this->pagination->initialize($config);
			$data["links_footer"] = $this->pagination->initialize($config);
			//debug($data["links"],1);
			$this->load->view('lwd/lwd', $data);
			
			//debug($data);
			/*for( $i=0; $i<count($office_list); $i++ )
			{
				$this->offices->contractarea_id = $office_list[$i]['contractarea_id'];
				$contractarea_detail = $this->offices->get_contract();
				$office_list[$i]['contractarea_detail'] = $contractarea_detail;
				for ($m=0; $m <count($contractarea_detail) ; $m++)
				{ 
					$this->offices->costcenterid = $contractarea_detail[$m]['costcenter_id'];
					$office_list[$i]['costcenter_detail'] = $this->offices->get_costcenter();
				}
				$data['detail'] = $office_list;
			}*/
				
	   }
	}

	function login_name()
	{
		$this->lwds->login_name = $this->input->get('login_name', true);
		$login_name = $this->lwds->login_name();
		if($login_name['ref'] > 0)
		{
			echo "already";
		}
		else
		{
			echo "free";
		}
	}

	function email_address()
	{
		$this->lwds->email_address = $this->input->get('email_address');
		$email_address = $this->lwds->email_address();
		if($email_address['ref'] > 0)
		{
			echo "already";
		}
		else
		{
			echo "free";
		}	
	}

	/* change signal kill status */
	function change_signal_kill()
	{
		$this->lwds->lwd_id = $this->input->post('lwd_id');
		$this->lwds->signal_kill = $this->input->post('signal_kill');
		$signal_status = $this->lwds->signal_status();
		if($signal_status) {
			$device_token = $this->lwds->get_device_token();
			if($device_token[0]->device_token!=""){
			  if($device_token[0]->device_type=="android") {
		  		if( $device_token[0]->app_type=="ORBIS" || $device_token[0]->app_type=="orbis" || $device_token[0]->app_type=="Orbis"){
				  if($this->input->post('signal_kill')=="0") {

				    $api_key='AAAAKZ4uE9A:APA91bEdEwS56C5-SqJZS6Y63twyMI025G-4h6j1btxoMitd026R9SbCVEKRCXJ9JBQAuBbRvaFRdFhl6xUw6r2bwl2F5W3IgEfgUUNpBcYGIoC7B_wRg1EDX2TuGMCoJzdwNmym6ESZ';
					$registrationIds = array($device_token[0]->device_token);
					$msg = array
					(
					 'title'    => 'Notallowed',
					 'message'  => 'Notallowed',
					 'status'   => '0'
					);
					
				  }
				  
				  if($this->input->post('signal_kill')=="1") {
				    $api_key='AAAAKZ4uE9A:APA91bEdEwS56C5-SqJZS6Y63twyMI025G-4h6j1btxoMitd026R9SbCVEKRCXJ9JBQAuBbRvaFRdFhl6xUw6r2bwl2F5W3IgEfgUUNpBcYGIoC7B_wRg1EDX2TuGMCoJzdwNmym6ESZ';
					$registrationIds = array($device_token[0]->device_token);
					$msg = array
					(
					 'title'    => 'Allowed',
					 'message'  => 'Allowed',
					 'status'   => '1'
					);
				  }
				}
				if(  $device_token[0]->app_type=="HS2" || $device_token[0]->app_type=="hs2" )
				{
					if($this->input->post('signal_kill')=="0") {
						

				    $api_key='AAAA8eYTIB8:APA91bGr33l42rCaGecp7s16mpX6VzKnTPUxXGhiy4sI0kuJIny6x4xBsof4DDBh3Q4L8Le63PPbl_KYGM3ZkGPU_J5sNv4ocDqjbDzII1kG2k4nNmSTUKyzQp4kIN_U6MxbfE2IA2rg';
					//$registrationIds = array('edViKtNuRTw:APA91bGRyL82qiEqPXMCmED2jXwE5mHI0YwjdkL8NZg8KSlzznck7X3hrobmZFgU9CeHH8BCx1kf_6HmW_5FQp0nHAF4_14hivqxEVPh7wzJdVkVBNp6MmFOw5CCZKTK8i3KQo0X813t');
					$registrationIds = array($device_token[0]->device_token);
					$msg = array
					(
					 'title'    => 'Notallowed',
					 'message'  => 'Notallowed',
					 'status'   => '0'
					);
					
				  }
				  
				  if($this->input->post('signal_kill')=="1") {
				  	
				    $api_key='AAAA8eYTIB8:APA91bGr33l42rCaGecp7s16mpX6VzKnTPUxXGhiy4sI0kuJIny6x4xBsof4DDBh3Q4L8Le63PPbl_KYGM3ZkGPU_J5sNv4ocDqjbDzII1kG2k4nNmSTUKyzQp4kIN_U6MxbfE2IA2rg';
					//$registrationIds = array('edViKtNuRTw:APA91bGRyL82qiEqPXMCmED2jXwE5mHI0YwjdkL8NZg8KSlzznck7X3hrobmZFgU9CeHH8BCx1kf_6HmW_5FQp0nHAF4_14hivqxEVPh7wzJdVkVBNp6MmFOw5CCZKTK8i3KQo0X813t');
					$registrationIds = array($device_token[0]->device_token);
					$msg = array
					(
					 'title'    => 'Allowed',
					 'message'  => 'Allowed',
					 'status'   => '1'
					);
				  }
				}


				  $fields = array
					(
					 'registration_ids'  => $registrationIds,
					 'data'   => $msg
					);
					
					 
					$headers = array
					(
					 
					 'Authorization: key='.$api_key,
					 '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, false );
					curl_setopt( $ch,CURLOPT_POSTFIELDS,json_encode( $fields ) );
					$result = curl_exec($ch );
					//debug($result,1);
					curl_close( $ch );
					
					echo "done";

				
			  }
			  
			  if($device_token[0]->device_type=="ios") {
			 

					$ch = curl_init();
					curl_setopt( $ch,CURLOPT_URL, 'https://www.redalertws.com/iosconfig/main.php' );
					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 );
			  		debug($result,1);

  			/*$deviceToken = 'DF279E65798F9202273A28793F494FE1CEB713A9B2E507C9C511592CE09A6E80';

			$passphrase = '1234';
			$pempath = base_url()."css/pushcert.pem";
			$message = 'hello world';
			$ctx = stream_context_create();
			stream_context_set_option($ctx, 'ssl', 'local_cert', $pempath); 
			stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

			// Open a connection to the APNS server
			$fp = stream_socket_client(
				'gateway.sandbox.push.apple.com:2195', $err,
				//'ssl://gateway.push.apple.com:2195', $err,
				$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

			if (!$fp)
				exit("Failed to connect: $err $errstr" . PHP_EOL);

				 echo 'Connected to APNS' . PHP_EOL;

				// Create the payload body
				$body['aps'] = array(
		
				'alert' => $message,
				'badge' => '1',
				'sound' => 'default'
			);
			// Encode the payload as JSON
			$payload = json_encode($body);

			// Build the binary notification
			$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

			// Send it to the server
			$result = fwrite($fp, $msg, strlen($msg));
			print_r($result);
	     if (!$result)
				echo 'Message not delivered' . PHP_EOL;
			else
				echo 'Message successfully delivered' . PHP_EOL;



			// Close the connection to the server
			fclose($fp);*/
							  
			  }
			}
		}
		
		//echo ($signal_status)? 'done' : 'fail';
	}

	function change_signal_kill_ios()
	{
		$this->lwds->lwd_id = $this->input->post('lwd_id');
		$this->lwds->signal_kill = $this->input->post('signal_kill');
		$signal_status = $this->lwds->signal_status();
		if($signal_status)
		{
			echo 'done';
		}
		else
		{
			echo "fail";
		}
	}
	
	function add_lwd()
	{
		$this->lwds->fname = trim( $this->input->post( 'fname',true ) ) ;
		$this->lwds->login_name = trim( $this->input->post( 'login_name',true ) ) ;
		$this->lwds->email_address = trim( $this->input->post( 'email',true ) ) ;
		$this->lwds->password = trim( $this->input->post( 'password',true ) ) ;
		$this->lwds->gender = trim( $this->input->post( 'gender',true ) ) ;
		$this->lwds->number = trim( $this->input->post( 'phone',true ) ) ;
		$this->lwds->imei = trim( $this->input->post( 'imei',true ) ) ;
		$this->lwds->address = trim( $this->input->post( 'address',true ) ) ;
		$this->lwds->office = trim( $this->input->post( 'office_id',true ) ) ;
		
		$add_lwd_db = $this->lwds->add_lwd_db(); 
		if($add_lwd_db > 0)
		{
			echo "done";
		}
		else
		{
			echo "fail";
		}

	}

	public function profile_view($id)
	{
		$this->lwds->lwd_id = base64_decode($id);
		$get_lwd_profile['profile'] = $this->lwds->get_lwd_profile();
		$get_lwd_profile['escalation'] = $this->lwds->get_lwds_escalation();
		$this->load->view('lwd/lwd_profile',$get_lwd_profile);
	}
	
	function get_office($contractareaid)
	{
		$office = $this->lwds->office_list($contractareaid);
        echo json_encode($office);
		
	}

	function get_map_location($id)
	{
		$this->lwds->lwd_id = $id;
		$map_location_lwd = $this->lwds->map_location_lwd();
		echo json_encode($map_location_lwd);
	}

	function lwd_add()
	{
		$data['costcenter'] = $this->cost_center->cc_list();
		//debug($data,1);
		$this->load->view('lwd/add_lwd',$data);
	}

	function add_setting()
	{
		if( empty($this->input->post('allow_user'))  )
		{
			$allow_user = '0';
		}
		else
		{
			$allow_user = $this->input->post('allow_user');
		}
		$add_lwd_setting = $this->lwds->add_lwd_setting($this->input->post(), $allow_user);
		echo ($add_lwd_setting)? 'done' : 'fail';
	}
	

	function get_contract_area()
	{
		$get_filter_contractarea = $this->contractareas->get_filter_contractarea($this->input->get('costcenter'));
		echo json_encode($get_filter_contractarea);
	}

	function get_office_list($id)
	{
		//echo '------'.$id; exit;
		$get_office_list = $this->offices->office_filter_lwd_list($id);
		echo json_encode($get_office_list);
	}
	
	function get_lwd($lwdid) {
		
		$lwds = $this->lwds->getlwds($lwdid);
		echo json_encode($lwds);
		
	}
	
	function edit_lwd($lwdid) {
		
		$firstname  = $_POST['fname'];
		$lastname   = $_POST['lname'];
		$emaddress  = $_POST['emaddress'];
		$devicetype = $_POST['dtype'];
		$phnumber   = $_POST['phnumber'];
		$imnumber   = $_POST['imnumber'];
		$addr       = $_POST['addr'];
		$gender		= $_POST['gender'];
		
		$editlwd = $this->lwds->editlwds($lwdid,$firstname,$lastname,$emaddress,$devicetype,$phnumber,$imnumber,$addr, $gender);
		echo json_encode($editlwd);
		
	}
	
	function get_settings($lwdid) {
		
		$settings = $this->lwds->getsettings($lwdid);
		echo json_encode($settings);
		
	}
	
	function edit_setting($lwdid) {
		
		$redalert    =  trim($this->input->post( 'redalert',true)) ;
		$amberalert  =  trim($this->input->post( 'amberalert',true));
		$ipaddress   =  trim($this->input->post( 'ipaddress',true));
		$port        =  trim($this->input->post( 'port',true));
		$redalertsms =  trim($this->input->post( 'redalertsms',true));
		$silentdial  =  trim($this->input->post( 'silentdial',true));
		$positionupdate = trim($this->input->post( 'positionupdate',true));
		$fixedamber = trim($this->input->post( 'fixedamber',true));
		$falldetectenabled = trim($this->input->post( 'falldetectenabled',true));
		$limitamber  = trim($this->input->post( 'limitamber',true));
		$falldetectsensitivity = trim($this->input->post( 'falldetectsensitivity',true));
		$allowuser  = trim($this->input->post( 'allowuser',true));
		$settings = $this->lwds->editsettings($lwdid, $redalert, $amberalert, $ipaddress, $port, $redalertsms, $silentdial, $positionupdate, $fixedamber, $falldetectenabled, $limitamber, $falldetectsensitivity, $allowuser );
		echo json_encode($settings);
		
	}

	function get_escalation_detail($id)
	{
		$detail_escalation = $this->lwds->detail_escalation_lwd($id);
		echo json_encode($detail_escalation);
	}


	// search lwd
	function search_lwd()
	{
		$resultArray = array();
		$this->lwds->search_term = $this->input->get('term');
		$searchReturn = $this->lwds->searchReturn();
		if( count($searchReturn) != 0 )
		{	
			for( $i=0; $i<count($searchReturn); $i++ )
			{
				$resultArray[] = $searchReturn[$i]['number'];
				//$resultArray[] = '<a href="'.base_url().'/lwd/profile_view/'.base64_encode($searchReturn[$i]['ref']).'" >'.$searchReturn[$i]['fullname'].'</a>';
			}
		}
		else
		{
			$resultArray[] = 'No Rows Founds';
		}

		echo json_encode($resultArray);
	}

	function search_lwd_name()
	{
		$resultArray = array();
		$this->lwds->search_term = $this->input->get('term');
		$searchReturn = $this->lwds->searchReturnName();
		if( count($searchReturn) != 0 )
		{	
			for( $i=0; $i<count($searchReturn); $i++ )
			{
				$resultArray[] = $searchReturn[$i]['fullname'];
				//$resultArray[] = '<a href="'.base_url().'/lwd/profile_view/'.base64_encode($searchReturn[$i]['ref']).'" >'.$searchReturn[$i]['fullname'].'</a>';
			}
		}
		else
		{
			$resultArray[] = 'No Rows Founds';
		}

		echo json_encode($resultArray);
	}

	function login()
	{
		$this->load->view('lwd/login');
	}
}