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

class Api extends Api_Controller {
	function index(){
		
	}

	/*function load_db_check_in(){
		$this->db->query("DROP TABLE IF EXISTS tbl_call_in_out; ");
		$this->db->query("CREATE TABLE IF NOT EXISTS `tbl_call_in_out` (  `id` int(11) NOT NULL,  `call_in_datetime` datetime DEFAULT NULL,  `call_in_note` text,  `call_out_datetime` datetime DEFAULT NULL,  `call_out_note` text,
  `assets_id` int(11) DEFAULT NULL,
  `device_imei` varchar(255) DEFAULT NULL,
  `in_address` varchar(255) DEFAULT NULL,
  `in_lat` varchar(45) DEFAULT NULL,
  `in_long` varchar(45) DEFAULT NULL,
  `out_address` varchar(255) DEFAULT NULL,
  `out_lat` varchar(45) DEFAULT NULL,
  `out_long` varchar(45) DEFAULT NULL,
  `total_time` VARCHAR(255) NULL DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;");
	}*/
	
	//http://localhost/cgs/cosmos/index.php/api/alldata
	function alldata(){
		$query = "select * from tbl_call_in_out";
		$res=$this->db->query($query);
		echo "<pre>";
		echo $res->num_rows();
		foreach($res->result_Array() as $row){
			print_r($row);
		}
		echo "</pre>";
	}

	function allassests_master(){
		$query = "select * from assests_master where del_date is null and status=1";
		$res=$this->db->query($query);
		echo "<pre>";
		echo $res->num_rows();
		foreach($res->result_Array() as $row){
			print_r($row);
		}
		echo "</pre>";
	}
	function output_call(){
		$query = "select  * from tbl_call_in_out where call_out_datetime is not null";
		$res = $this->db->query($query);
		foreach($res->result_Array() as $row){
			$total_time1 = strtotime($row['call_out_datetime']) - strtotime($row['call_in_datetime']);
			/*echo $row['call_out_datetime'];
			echo $row['call_in_datetime'];
			echo $total_time1;*/
			/*echo $this->secondsToWords($total_time1)."<br>";
			//die;
			$total_hour = floor($total_time1/3600);
			$total_min = floor(($total_time1-($total_hour*3600))/60);
			if($total_hour<10) $total_hour = "0".$total_hour;
			if($total_min<10) $total_min = "0".$total_min;
			$total_time = $total_hour.":".$total_min;
			*/
			$total_time = $this->secondsToWords($total_time1);
			
			$query = "update tbl_call_in_out set total_time='".$total_time."' where id =".$row['id']."";
			$this->db->query($query);
		}
	}
	function secondsToWords($seconds){
		$ret = "";
		/*** get the days ***/
		$days = intval(intval($seconds) / (3600*24));
		if($days> 0){
			$ret .= $days."d";
		}
		
		/*** get the hours ***/
		$hours = (intval($seconds) / 3600) % 24;
		if($ret != "" or $hours > 0){
			if($ret != "") $ret .= " : ";
			$ret .= $hours."h";
		}
		
		/*** get the minutes ***/
		$minutes = (intval($seconds) / 60) % 60;
			if($ret != "") $ret .= " : ";
			$ret .= $minutes."m";
		
		/*** get the seconds ***/
		$seconds = intval($seconds) % 60;
			if($ret != "") $ret .= " : ";
			$ret .= $seconds."s";
		return $ret;
	}
	function check_call_in_out(){
		$imei = $_REQUEST['imei'];		
		$query = "select * from tbl_call_in_out where device_imei='$imei' and call_out_datetime is null ";
		$res=$this->db->query($query);
		if($res->num_rows()==0){
			die("In");
		}else{
			die("Out");
		}
	}
	function check_call_in_out_json(){
		header('Content-Type: text/html');
		$imei = $_REQUEST['imei'];		
		$query = "select * from tbl_call_in_out where device_imei='$imei' and call_out_datetime is null ";
		$res=$this->db->query($query);
		if($res->num_rows()==0){
			die(json_encode(array(array("result"=>"In"))));
		}else{
			die(json_encode(array(array("result"=>"Out"))));
			//die("Out");
		}
	}
	/*
	http://localhost/cgs/cosmos/index.php/api/call_in_out_event/?note=df&imei=sdfs&call_in_out=In&lat=23&lng=70
	*/
	
	function get_address($lat,$lang){
            $url="http://216.58.192.46/maps/api/geocode/json?";
           // $url = "https://maps.googleapis.com/maps/api/geocode/json?";
            $url .= "latlng=" . urlencode($lat).','. urlencode($lang);
            //$url .= "&key=AIzaSyDHHg7h3fv7DAwYlTmeb8FYlqzJ1XxBXZo";
            //$url .="&sensor=false&region=in";
            //echo "URL: ".$url."<br>";
            $this->load->library('curl'); 
            $data = $this->curl->simple_get($url);
			//var_dump($data);
			$data = json_decode($data);
            return isset($data->results[0]->formatted_address)?$data->results[0]->formatted_address:"";
	}
	function set_time_date(){
		date_default_timezone_set("UTC");
		echo date("Y-m-d H:i:s",strtotime("+2 hours -2 min +39 sec"));
	}
	
	
	function get_time_date(){
		date_default_timezone_set("UTC");
		return date("Y-m-d H:i:s",strtotime("+2 hours -2 min +39 sec "));
	}
	function call_in_out_event(){
			
		$note = $_REQUEST['note'];
		$imei = $_REQUEST['imei'];
		$lat = $_REQUEST['lat'];
		$lng = $_REQUEST['lng'];
		$value = isset($_REQUEST['value'])?$_REQUEST['value']:"";
		$address= $this->get_address($lat,$lng);
		$in_time= "";
		$out_time= "";
		$total_time= 0;
		$call_in_out = $_REQUEST['call_in_out']; //"In/Out"
		if($call_in_out=="In" or $call_in_out=="Out"){
			if($call_in_out=="In"){
				$query = "select  * from assests_master where device_id='$imei' and del_date is null and status=1";
				$res = $this->db->query($query);
				$assets_id = "";
				if($res->num_rows()>0){
					$row = $res->result_Array();
					$assets_id=$row[0]['id'];
				}
				$query = "select  * from tbl_call_in_out where device_imei='$imei' and call_out_datetime is null";
				$res = $this->db->query($query);
				$in_time =$this->get_time_date();
				if($res->num_rows()==0){
					$in_time =$this->get_time_date();
					$data = array(
						"call_in_datetime"=>$in_time,
						"in_address"=>$address,
						"in_lat"=>$lat,
						"in_long"=>$lng,
						"device_imei"=>$imei,
						"assets_id"=>$assets_id,
					);					
					$this->db->insert("tbl_call_in_out",$data);
					
					if($in_time!="") $in_time = date("d.m.Y H:i",strtotime($in_time));
					if($out_time!="") $out_time = date("d.m.Y H:i",strtotime($out_time));
					$data = array("result"=>"true","msg"=>"Clock In Successfully.","address"=>$address,"in_time"=>$in_time,"out_time"=>$out_time,"total_time"=>$total_time);
					
				}else{
					$row = $res->result_Array();
					$in_time =date("Y-m-d H:i:s",strtotime($row[0]['call_in_datetime']));
					$address =$row[0]['in_address'];
					if($in_time!="") $in_time = date("d.m.Y H:i",strtotime($in_time));
					if($out_time!="") $out_time = date("d.m.Y H:i",strtotime($out_time));
					$data = array("result"=>"true","msg"=>"Already Clock In.","address"=>$address,"in_time"=>$in_time,"out_time"=>$out_time,"total_time"=>$total_time);
				}
				
				
			}else{
				$query = "select  * from assests_master where device_id='$imei' and del_date is null and status=1";
				$res = $this->db->query($query);
				$assets_id = "";
				if($res->num_rows()>0){
					$row = $res->result_Array();
					$assets_id=$row[0]['id'];
				}
				
				$query = "select  * from tbl_call_in_out where device_imei='$imei' and call_out_datetime is null";
				$res = $this->db->query($query);
				$in_time =$this->get_time_date();
				if($res->num_rows()>0){
					$row = $res->result_Array();
					$in_time =$row[0]['call_in_datetime'];
					$out_time = $this->get_time_date();
					$total_time1 = (strtotime($out_time) - strtotime($in_time));
					$total_time = $this->secondsToWords($total_time1);
					
					/*$total_hour = floor($total_time1/60);
					$total_min = $total_time1-floor($total_hour*60);
					$total_time = $total_hour.":".$total_min;*/
					$data = array(
						"call_out_datetime"=>$out_time,
						"call_out_note"=>$address,
						"out_address"=>$address,
						"out_lat"=>$lat,
						"out_long"=>$lng,
						"total_time"=>$total_time,
					);
					$this->db->where("device_imei",$imei);
					$this->db->where("call_out_datetime",null);
					$this->db->update("tbl_call_in_out",$data);
					if($in_time!="") $in_time = date("d.m.Y H:i",strtotime($in_time));
						if($out_time!="") $out_time = date("d.m.Y H:i",strtotime($out_time));
					$data = array("result"=>"true","msg"=>"Clock Out Successfully.","address"=>$address,"in_time"=>$in_time,"out_time"=>$out_time,"total_time"=>$total_time);
				}else{
					$query = "select  * from tbl_call_in_out where device_imei='$imei' and call_out_datetime is not null order by call_out_datetime desc limit 1";					
					$res = $this->db->query($query);
					if($res->num_rows()>0){
						$row = $res->result_Array();
						$in_time =date("Y-m-d H:i:s",strtotime($row[0]['call_in_datetime']));
						$out_time =date("Y-m-d H:i:s",strtotime($row[0]['call_out_datetime']));
						$address =$row[0]['out_address'];
						$total_time =$row[0]['total_time'];
						
					}else{
						$in_time ="";
						$out_time ="";
						$address ="";
						$total_time =00;
						
					}
					if($in_time!="") $in_time = date("d.m.Y H:i",strtotime($in_time));
					if($out_time!="") $out_time = date("d.m.Y H:i",strtotime($out_time));
					$data = array("result"=>"true","msg"=>"Already Clock Out.","address"=>$address,"in_time"=>$in_time,"out_time"=>$out_time,"total_time"=>$total_time);
				}
			}
			/*if($in_time!="") $in_time = date("d.m.Y H:i",strtotime($in_time));
			if($out_time!="") $out_time = date("d.m.Y H:i",strtotime($out_time));
			$data = array("result"=>"true","msg"=>"Record Inserted Successfully","address"=>$address,"in_time"=>$in_time,"out_time"=>$out_time,"total_time"=>$total_time);*/
			if($value=="")
				die(json_encode($data));
			else{
				header('Content-Type: application/json');
				die(json_encode($data));
				
			}
		}else{
			$data = array("result"=>"false","msg"=>"Error  In the Data");
			if($value=="")
				die(json_encode($data));
			else{
				header('Content-Type: application/json');
				die(json_encode($data));
			}
		}
		
	}
	
	
	function view_userguide(){
		$query ="select * from tbl_settings where data_key='userguide'";
		$res = $this->db->query($query);
		if($res->num_rows() >0){
			$row = $res->result_Array();
			$row[0]['data_value']="";
			die($row[0]['data_value']);
		}else{
			$data5 = "Enter the following Information<br />1) Phone Number<br />2) First Name<br />3) Last Name<br />4) Company Name";
			$data5 = "";
			$data=array(
				"data_key"=>"userguide",
				"data_value"=>$data5,
			);
			$this->db->insert("tbl_settings",$data);
			die($data5);
		}
	}	
	//http://localhost/cgs/cosmos/index.php/api/firstname_insert/?IMEI=009503004669&first_name=dhaval&last_name=dhaval&company_name=dhaval
	//http://localhost/cgs/cosmos/index.php/api/firstname_insert/?IMEI=009503004669&first_name=dhaval&last_name=dhaval&company_name=dhaval&value=json

	function bin_details(){
		$user_id = isset($_REQUEST['user_id'])?$_REQUEST['user_id']:"";
		$asset_id = isset($_REQUEST['asset_id'])?$_REQUEST['asset_id']:"";
		$empty_or_full = isset($_REQUEST['empty_or_full'])?$_REQUEST['empty_or_full']:"0";
		$lat = isset($_REQUEST['lat'])?$_REQUEST['lat']:"0";
		$lang = isset($_REQUEST['lang'])?$_REQUEST['lang']:"0";
		$note = isset($_REQUEST['note'])?$_REQUEST['note']:"0";
		$address = isset($_REQUEST['address'])?$_REQUEST['address']:"";
		if($address == ""){
			$address = $this->get_address($lat,$lang);
		}
		$photo = "";
		if(isset($_FILES['upload_photo']['name'])){
			$config['upload_path'] = FCPATH.'assets/photo/';
			$config['allowed_types'] = 'gif|jpg|jpeg|png';
			$config['max_size']	= '2048';
			$config['max_width']  = '3000';
			$config['max_height']  = '3000';
			$config['file_name']  = time().'_'.$_FILES['upload_photo']['name'];
			$this->load->library('upload', $config);			
			if ( ! $this->upload->do_upload("upload_photo")){
				die(json_encode(array("result"=>"false","msg"=>strip_tags($this->upload->display_errors()))));
			}
			$data1 = array('upload_data' => $this->upload->data());
			$photo=$data1['upload_data']['file_name'];
		}
		$data = array(
			"photo"=>$photo,
			"asset_id"=>$asset_id,
			"empty_or_full"=>$empty_or_full,
			"lat"=>$lat,
			"lang"=>$lang,
			"address"=>$address,
			"note"=>$note,
			"add_uid"=>$user_id,
			"add_date"=>gmdate("Y-m-d H:i:s"),
			"status"=>1,
		);
		$this->db->insert("bin_details",$data);
		$data = array("result"=>"true","msg"=>"Bin Details Added Successfully");
		die(json_encode($data));
	}
	function firstname_insert(){
		$device_id = isset($_REQUEST['device_id'])?$_REQUEST['device_id']:"";
		$value = isset($_REQUEST['value'])?$_REQUEST['value']:"";
		if($device_id=="")
			$device_id = $_REQUEST['IMEI'];
		$first_name = $_REQUEST['first_name'];
		$last_name = $_REQUEST['last_name'];
		$company_name = $_REQUEST['company_name'];
		$sim_number = $_REQUEST['sim_number'];
		$email_id = $_REQUEST['email_id'];
		$query = "select * from assests_master where del_date is null and status=1 and device_id='".$device_id."'";
		$res=$this->db->query($query);
		if($res->num_rows()==1){
			
			//echo $company_name; 
			$data= array(
			  "first_name"=>$first_name,
			  "last_name"=>$last_name,
			  "company_name"=>$company_name,
			);
			if($sim_number!=""){
				$data['sim_number'] = $sim_number;
				$data['assets_name'] = $sim_number;
			}
			if($email_id!=""){
				$data['email_id'] = $email_id;
			}
			
			$this->db->where("device_id",$device_id);
			$this->db->update("assests_master",$data);
		}else{
			$group_id =2;
			$user=794;
			$lSql = "INSERT INTO assests_master (email_id,first_name,last_name,company_name,assets_name,device_id, assets_type_id,assets_category_id,assets_group_id,device_status,sim_number,add_uid,add_date,battery_size,status) VALUES ('".$email_id."','".$first_name."','".$last_name."','".$company_name."','".$sim_number."', '".$device_id."' , 3,4,$group_id,1,'".$sim_number."',794,'".date('Y-m-d H:i:s')."',12,1)";
			$this->db->query($lSql);
			$insert_id = $this->db->insert_id();
			$sql = "SELECT * FROM `user_assets_map` where user_id = $user";
			$res = $this->db->query($sql);
			foreach($res->result_Array() as $row){
				if($row['assets_ids']!= "") {
					$temp_as = explode(',', $row['assets_ids']);
					if(! in_array($insert_id, $temp_as)) {
						$upd = 'UPDATE user_assets_map SET assets_ids = concat(assets_ids, ",'.$insert_id.'") WHERE id='.$row['id'];
						$this->db->query($upd);
					}
				}else{
					$upd = 'UPDATE user_assets_map SET assets_ids = '.$insert_id.' WHERE id='.$row['id'];
					$this->db->query($upd);
				}
				if($row['group_id'] != "") {
					$temp_as = explode(',', $row['group_id']);
					if(! in_array($group_id, $temp_as)) {
						$upd = 'UPDATE user_assets_map SET group_id = concat(group_id, ",'.$group_id.'") WHERE id='.$row['id'];
						$this->db->query($upd);
					}
				}else{
					$upd = 'UPDATE user_assets_map SET group_id = '.$group_id.' WHERE id='.$row['id'];
					//$this->db->query($upd);
					$this->db->query($upd);
				}
			}
		}
		//echo $this->db->last_query();
		$data = array("result"=>"true","msg"=>"Record Updated Successfully");
		if($value=="")
			die(json_encode($data));
		else{
			die(json_encode(array($data)));
		}
	}
	function firstname_create(){
		$this->db->query("ALTER TABLE  `assests_master` ADD  `first_name` VARCHAR( 255 ) NULL AFTER  `tank_width` ,ADD  `last_name` VARCHAR( 255 ) NULL AFTER  `first_name` ,ADD  `company_name` VARCHAR( 255 ) NULL AFTER  `last_name`");
	}
	function get_more_apps(){
		$query = "select * from more_apps ";
		$res = $this->db->query($query);
		$row = $res->result_Array();
		die(json_encode($row));
	}
	function more_apps_create(){
		$this->db->query ("DROP TABLE IF EXISTS `more_apps`");
		$this->db->query ("
CREATE TABLE IF NOT EXISTS `more_apps` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `mobile_no` varchar(255) DEFAULT NULL,
  `customer_imei` varchar(255) DEFAULT NULL,
  `customer_name` varchar(255) DEFAULT NULL,
  `customer_email` varchar(255) DEFAULT NULL,
  `customer_telephone` varchar(255) DEFAULT NULL,
  `sos_emergency_apps` tinyint(1) NOT NULL DEFAULT '0',
  `low_cost_gps_tracking` tinyint(1) NOT NULL DEFAULT '0',
  `lone_worker_solutions` tinyint(1) NOT NULL DEFAULT '0',
  `add_uid` int(11) DEFAULT NULL,
  `add_date` datetime DEFAULT NULL,
  `del_uid` int(11) DEFAULT NULL,
  `del_date` datetime DEFAULT NULL,
  `status` tinyint(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;");
	}
	function more_apps(){
		$data = array();
		if($_REQUEST['name']!=""){
			$data['mobile_no'] = $_REQUEST['mobile_no'];
			$data['customer_imei'] = $_REQUEST['imei'];
			$data['customer_name'] = $_REQUEST['name'];
			$data['customer_email'] = $_REQUEST['email'];
			$data['customer_telephone'] = $_REQUEST['telephone'];
			$data['lone_worker_solutions'] = $_REQUEST['lone_worker_solutions'];
			$data['lone_worker_solutions'] = $_REQUEST['lone_worker_solutions'];
			$data['sos_emergency_apps'] = ($_REQUEST['sos_emergency_app']=="true")?1:0;
			$data['low_cost_gps_tracking'] = ($_REQUEST['low_cost_gps_tracking']=="true")?1:0;
			$data['lone_worker_solutions'] = ($_REQUEST['lone_worker_solutions']=="true")?1:0;
			$data['add_date'] = date("Y-m-d H:i:s");
			$this->db->insert("more_apps",$data);
		}
		$data = array("result"=>"true","msg"=>"Record Inserted Successfully");
		die(json_encode($data));
	}
	function load_db(){
		$this->db->query ("DROP TABLE IF EXISTS `chat`");
		$this->db->query ("CREATE TABLE IF NOT EXISTS `chat` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `from_id` int(11) DEFAULT NULL COMMENT 'user enter',
  `to_id` int(11) DEFAULT NULL COMMENT 'server enter',
  `message` text,
  `sent` datetime DEFAULT NULL,
  `viewed` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;");
$this->db->query("INSERT INTO  `main_menu_master` (
`id` ,
`menu_name` ,
`menu_link` ,
`where_to_show` ,
`menu_sound` ,
`tab_title` ,
`menu_level` ,
`parent_menu_id` ,
`menu_image` ,
`priority` ,
`type` ,
`sub_settings` ,
`is_admin` ,
`add_uid` ,
`add_date` ,
`del_uid` ,
`del_date` ,
`status` ,
`icon` ,
`description`
)
VALUES (
NULL ,  'Chat',  '_base_url_index.php/chat',  'link', NULL ,  'Chat',  '2',  '4', NULL ,  '1',  '1',  'NULL',  '0',  '1',  '2012-07-14 00:00:00', NULL , NULL ,  '1',  'fa-stop',  ''
);");
	}
	/*
		DROP TABLE IF EXISTS `chat`;
		CREATE TABLE IF NOT EXISTS `chat` (
		`id` int(10) unsigned NOT NULL,
		  `from_id` int(11) DEFAULT NULL,
		  `to_id` int(11) DEFAULT NULL,
		  `message` text NOT NULL,
		  `sent` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'
		) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


	*/
	/* http://69.163.37.194/allclientstest/index.php/api/get_chat/009503004669 */
	function history($imei="",$page=1){
		$query = "select * from assests_master  where del_date is null and status=1 and device_id='".$imei."' ";
		$res = $this->db->query($query);
		$data = array();
		$data['total_pages'] = 0;
		$data['count'] = 0;
		$limit = 10;
		$start = ($page-1)*$limit;
		$end = $page*$limit;
		if($res->num_rows()==1){
			$row = $res->result_Array();
			$assets_id=$row[0]['id'];
			$query = "select * from chat where to_id='".$assets_id."' or from_id='".$assets_id."' ";
			$res = $this->db->query($query);
			$data['count'] = $res->num_rows();
			$data['total_pages'] = ceil($data['count']/$limit);
			if($end >$data['count'])
				$end =$data['count'];
			$query .= " order by sent desc ";
			$query .= " limit $start,$limit ";
			
			
			$data['msgs'] = array();
			$res = $this->db->query($query);
			foreach($res->result_Array() as $row){
				if($row['from_id']=="")
					$from = "Server";
				if($row['to_id']=="")
					$from = "Assets";
				$data['msgs'][] = array(
					"From"=>$from,
					"msg"=>$row['message'],
					"sent"=>$row['sent']
				);
			}
			$data['msgs'] =  array_reverse($data['msgs']);
			$data['total_msgs'] = count($data['msgs']);
		}		
		echo json_encode($data);
	}
	function get_chat($imei=""){
		$date_time = isset($_REQUEST['date_time'])?$_REQUEST['date_time']:"";
		$query = "select * from assests_master  where del_date is null and status=1 and device_id='".$imei."' ";
		$res = $this->db->query($query);
		$data['assets_id']="";
		if($res->num_rows()==1){
			$row = $res->result_Array();
			$assets_id=$row[0]['id'];
			$query = "select * from chat where (to_id='".$assets_id."' or from_id='".$assets_id."') ";
			if($date_time!="")
				$query .= " and sent > '".date("Y-m-d H:i:s",strtotime($date_time))."'";
			//echo $query;
			$res = $this->db->query($query);
			$data = array();
			$data['msgs'] = array();
			foreach($res->result_Array() as $row){
				if($row['from_id']=="")
					$from = "Server";
				if($row['to_id']=="")
					$from = "Assets";
				$data['msgs'][] = array(
					"From"=>$from,
					"msg"=>$row['message'],
					"sent"=>$row['sent']
				);
			}
			$data['total_msgs'] = count($data['msgs']);
		}		
		echo json_encode($data);
	}
	function set_chat($imei=""){
		$message = $_REQUEST['message'];
		if($imei != "" && $message!=""){
			$query = "select * from assests_master  where del_date is null and status=1 and device_id='".$imei."' ";
			$res = $this->db->query($query);
			$data['assets_id']="";
			if($res->num_rows()==1){
				$row = $res->result_Array();
				$assets_id=$row[0]['id'];
				$data = array(
					"from_id"=>$assets_id,
					"message"=>$message,
					"sent"=>date("Y-m-d H:i:s")
				);
				$this->db->insert("chat",$data);
			}
			die("Done");
		}
	}
	function demo_chat($imei=""){
		$message = $_REQUEST['message'];
		if($imei != "" && $message!=""){
			$query = "select * from assests_master  where del_date is null and status=1 and device_id='".$imei."' ";
			$res = $this->db->query($query);
			$data['assets_id']="";
			if($res->num_rows()==1){
				$row = $res->result_Array();
				$assets_id=$row[0]['id'];
				$data = array(
					"to_id"=>$assets_id,
					"message"=>$message,
					"sent"=>date("Y-m-d H:i:s")
				);
				$this->db->insert("chat",$data);
			}
			die("Done");
		}
	}
	function login(){
		//$data = array("result"=>"false","msg"=>"Invalid Username or Password");
		$imei = $_REQUEST['imei'];
		$token_id = $_REQUEST['token_id'];
                
		$this->db->query("delete from pushnotification where imei='$imei'");
		$this->db->where('username', $_REQUEST['username']);
		if($_REQUEST['password']!="cgs848484")
		$this->db->where('password', md5($_REQUEST['password']));
		$this->db->where('status', 1);
		$this->db->where('del_date', NULL);
		$query = $this->db->get('tbl_users');
		//echo $this->db->last_query();
		$data = array("result"=>"false","msg"=>"Invalid User Name Password");	
		if ($query->num_rows() == 1) {
			$row = $query->result_Array();
			$user_id = $row[0]['user_id'];
			$data1 = array(
				"user_id"=>$user_id,
				"token_id"=>$token_id,
				"imei"=>$imei,
                              
                            
			);
			$this->db->insert("pushnotification",$data1);
			$data = array("result"=>"true","msg"=>$user_id);		
		}
		die(json_encode($data));
	}
	function get_assets($user_id="",$page=1,$search = ""){
		$user = $user_id;
		$data = array();
		$data['assets'] = array();
		$limit = 10;
		$start = ($page-1)*$limit;
		$end = $page*$limit;
		$tz_query = "select timezone from  tbl_users where del_date is null and status=1 and user_id='$user_id'";
		$tz_result = $this->db->query($tz_query);
		$tz_rows = $tz_result->result_Array($tz_result);
		$timezone = $tz_rows[0]['timezone'];
		$q ="";
		if($search!=""){
			$q = " and am.assets_name like '%$search%' ";
		}
		if($user!=1){
			$query = $this->db->query("select CONVERT_TZ(lm.add_date,'+00:00','".$timezone."') as add_date,am.id,acm.assets_cat_image, am.assets_name, am.device_id, am.assets_friendly_nm from assests_master am left join tbl_last_point lm on lm.device_id = am.device_id LEFT JOIN assests_category_master acm ON acm.id = am.assets_category_id  where am.status=1 AND am.del_date is null AND find_in_set(am.id, (SELECT assets_ids FROM user_assets_map where user_id = $user)) $q  order by lm.add_date desc ,am.assets_name asc");
			$total = $query->num_rows();
			if($end >$total)
				$end =$total;
			$query = $this->db->query("select CONVERT_TZ(lm.add_date,'+00:00','".$timezone."') as add_date,am.id,acm.assets_cat_image, am.assets_name, am.device_id, am.assets_friendly_nm from assests_master am left join tbl_last_point lm on lm.device_id = am.device_id LEFT JOIN assests_category_master acm ON acm.id = am.assets_category_id  where am.status=1 AND am.del_date is null AND find_in_set(am.id, (SELECT assets_ids FROM user_assets_map where user_id = $user)) $q order by lm.add_date desc ,am.assets_name asc limit $start,$limit");
		}else{
			$query = $this->db->query("select CONVERT_TZ(lm.add_date,'+00:00','".$timezone."') as add_date,am.id,acm.assets_cat_image, am.assets_name, am.device_id, am.assets_friendly_nm from assests_master am left join tbl_last_point lm on lm.device_id = am.device_id  LEFT JOIN assests_category_master acm ON acm.id = am.assets_category_id  where am.status=1 AND am.del_date is null $q order by lm.add_date desc ,am.assets_name asc ");
			$total = $query->num_rows();
			if($end >$total)
				$end =$total;
			$query = $this->db->query("select CONVERT_TZ(lm.add_date,'+00:00','".$timezone."') as add_date,am.id,acm.assets_cat_image, am.assets_name, am.device_id, am.assets_friendly_nm from assests_master am left join tbl_last_point lm on lm.device_id = am.device_id  LEFT JOIN assests_category_master acm ON acm.id = am.assets_category_id  where am.status=1 AND am.del_date is null $q order by lm.add_date desc ,am.assets_name asc limit $start,$limit");
		}
		$data['total_pages'] = ceil($total/$limit);
		$rows = $query->result();
		if(count($rows)) {
			foreach ($rows as $row) {
				$data['assets'][$row->device_id] = array("assets_name"=> $row->assets_name." (".$row->device_id.")","last_date"=>$row->add_date,"marker_path"=>$row->assets_cat_image);
			}
		}
		$data['count'] = count($data['assets']);
		die(json_encode($data));		
	}
	function get_assets_sim($user_id=""){
		$user = $user_id;
		$data = array();
		$data['assets'] = array();
		$limit = 10;
		$query = "select * from tbl_users where user_id='$user'";
		$res = $this->db->query($query);
		$row = $res->result_Array();
		$row=$row[0];
		if($row['usertype_id']!=1){
			$query = $this->db->query("select am.sim_number,am.id,acm.assets_cat_image, am.assets_name, am.device_id, am.assets_friendly_nm from assests_master am left join tbl_last_point lm on lm.device_id = am.device_id LEFT JOIN assests_category_master acm ON acm.id = am.assets_category_id  where am.status=1 AND am.del_date is null  and  find_in_set(am.id, (SELECT assets_ids FROM user_assets_map where user_id = '$user'))  order by am.assets_name asc ");
		}else{
			$query = $this->db->query("select am.sim_number,am.id,acm.assets_cat_image, am.assets_name, am.device_id, am.assets_friendly_nm from assests_master am left join tbl_last_point lm on lm.device_id = am.device_id  LEFT JOIN assests_category_master acm ON acm.id = am.assets_category_id  where am.status=1 AND am.del_date is null  order by am.assets_name asc ");
		}
		$rows = $query->result();
		if(count($rows)) {
			foreach ($rows as $row) {
				if($row->sim_number!=""){
					$data['assets'][] = array("id"=> $row->id,"assets_name"=> $row->assets_name,"sim_number"=>$row->sim_number);
				}
			}
		}
		$data['result'] = "true";
		$data['count'] = count($data['assets']);
		die(json_encode($data));		
	}
	function get_assets_all($user_id=""){
		$user = $user_id;
		$data = array();
		$data['assets'] = array();
		$limit = 10;
		$query = "select * from tbl_users where user_id='$user'";
		$res = $this->db->query($query);
		$row = $res->result_Array();
		$row=$row[0];
		if($row['usertype_id']!=1){
			$query = $this->db->query("select am.sim_number,am.id,acm.assets_cat_image, am.assets_name, am.device_id, am.assets_friendly_nm from assests_master am left join tbl_last_point lm on lm.device_id = am.device_id LEFT JOIN assests_category_master acm ON acm.id = am.assets_category_id  where am.status=1 AND am.del_date is null  and  find_in_set(am.id, (SELECT assets_ids FROM user_assets_map where user_id = '$user'))  order by am.assets_name asc ");
		}else{
			$query = $this->db->query("select am.sim_number,am.id,acm.assets_cat_image, am.assets_name, am.device_id, am.assets_friendly_nm from assests_master am left join tbl_last_point lm on lm.device_id = am.device_id  LEFT JOIN assests_category_master acm ON acm.id = am.assets_category_id  where am.status=1 AND am.del_date is null  order by am.assets_name asc ");
		}
		//echo $this->db->last_query();
		$rows = $query->result();
		if(count($rows)) {
			foreach ($rows as $row) {
				$data['assets'][] = array("id"=> $row->id,"assets_name"=> $row->assets_name,"sim_number"=>$row->sim_number);
			}
		}
		$data['result'] = "true";
		$data['count'] = count($data['assets']);
		die(json_encode($data));		
	}
	function alert_master($user_id="",$last_id=""){
		/* $data = array();
		$query = "select max(id) as max_id from alert_master where user_id='$user_id'";
		$res = $this->db->query($query);
		$row = $res->result_Array();
		$data['last_id'] = $row[0]['max_id'];
		$data['alerts'] = array();
		if($last_id==""){
			$data['count'] = count($data['alerts']);
			die(json_encode($data));
		}else{
			
			$SQL = "SELECT am.id, am.alert_header, am.alert_msg, am.alert_link, am.alert_type, am.user_id, am.assets_id, am.add_date, am.del_date from alert_master am where am.user_id = '$user_id' and am.id>'$last_id'";
			//$query = "select * from alert_master where user_id='$user_id' and id>'$last_id'";
			$res = $this->db->query($SQL);
			foreach($res->result_Array() as $row){
				if($row['alert_link']==Null) 
				$row['alert_link'] = "";
				$data['alerts'][$row['id']]= array("date"=>date("d-m-Y H:i:s",strtotime($row['add_date'])),"assets_id"=>$row['assets_id'],"alert_header"=>$row['alert_header'],"alert_msg"=>$row['alert_msg'],"alert_link"=>$row['alert_link'],"alert_type"=>$row['alert_type']);
			}
			$data['count'] = count($data['alerts']);
			die(json_encode($data));
		}*/
	}
	function last_point($device_id=""){
		$data = array();
		$data['result'] = "false";
		$query = "select lati,longi,address,add_date,speed from tbl_last_point where device_id='$device_id'";
		$res = $this->db->query($query);
		if($res->num_rows()==0){
			echo json_encode($data);
		}else{
			$data['result']= "true";
			$row = $res->result_Array();
			$row=$row[0];
			$data['lati']= $row['lati'];
			$data['longi']= $row['longi'];
			$data['address']= $row['address'];
			$data['add_date']= $row['add_date'];
			$data['speed']= $row['speed'];			
			echo json_encode($data);
		}
	}
	function all_points(){
		$data = array();
		$data['all_points'] = array();
		$data['total_pages'] = 0;
		$data['count'] = 0;
		$sdate = $_REQUEST['sdate'];
		$stime = $_REQUEST['stime'];
		$edate = $_REQUEST['edate'];
		$etime = $_REQUEST['etime'];
		$device_id=$_REQUEST['device_id'];
		$user_id=isset($_REQUEST['user_id'])?$_REQUEST['user_id']:"";
		$page=isset($_REQUEST['page'])?$_REQUEST['page']:1;
		$limit = 15;
		$start = ($page-1)*$limit;
		$end = $page*$limit;
		if($sdate && $edate){	//search by date
			$sdate = date("Y-m-d", strtotime($sdate));
			$edate = date("Y-m-d", strtotime($edate));
		}else{
			$sdate = date("Y-m-d");
			$edate = date("Y-m-d");
		}
		if($stime && $etime){	//search by date
			$stime = date("H:i:s", strtotime($sdate." ".$stime));
			$etime = date("H:i:s", strtotime($edate." ".$etime));
		}else{
			$stime = "00:00:00";
			$etime = "23:59:59";
		}
		$sdate = $sdate." ".$stime;
		$edate = $edate." ".$etime;
		
		if($device_id!="" && $user_id!= ""){
			$query = "select am.assets_name,am.device_id	from assests_master am where am.device_id='".$device_id."' and find_in_set(am.id,(SELECT assets_ids FROM user_assets_map where user_id = $user_id))";
			$res = $this->db->query($query);
			if($res->num_rows()==0){
				die(json_encode($data));
			}else{
				$tz_query = "select timezone from  tbl_users where del_date is null and status=1 and user_id='$user_id'";
				$tz_result = $this->db->query($tz_query);
				$tz_rows = $tz_result->result_Array($tz_result);
				$timezone = $tz_rows[0]['timezone'];
				$query = "SELECT count(*) as count from tbl_track dm left join assests_master am on am.id=dm.assets_id WHERE  find_in_set(dm.assets_id,(SELECT assets_ids FROM user_assets_map where user_id = $user_id)) and CONVERT_TZ(dm.add_date,'+00:00','".$timezone."') BETWEEN '" . $sdate . "' AND '" . $edate . "'  AND dm.device_id = '".$device_id."'";
				$res = $this->db->query($query);
				$row = $res->result_Array();
				$total = $row[0]['count'];
				if($end >$total)
					$end =$total;
				$query = "SELECT dm.*,CONCAT(am.assets_name,'(',am.device_id,')') as assets_id, CONVERT_TZ(dm.add_date,'+00:00','".$_SESSION['timezone']."') as add_date from tbl_track dm left join assests_master am on am.id=dm.assets_id  WHERE find_in_set(dm.assets_id,(SELECT assets_ids FROM user_assets_map where user_id = $user_id)) and CONVERT_TZ(dm.add_date,'+00:00','".$timezone."') BETWEEN '" . $sdate . "' AND '" . $edate . "' AND dm.device_id = '".$device_id."'";
				
				$query .= " order by dm.id desc limit $start,$limit";
				//echo $query;
				$query = $this->db->query($query);
				foreach($query->result_Array() as $row){
					$data['all_points'][$row['id']]= array(
						"date"=>date("d-m-Y H:i:s",strtotime($row['add_date'])),
						"assets_id"=>$row['assets_id'],
						"lati"=>$row['lati'],
						"longi"=>$row['longi'],
						"device_id"=>$row['device_id'],
						"speed"=>$row['speed'],
						"address"=>$row['address'],
					);
				}
				
			}
		}
		$data['total_pages'] = ceil($total/$limit);
		$data['count'] = count($data['all_points']);
		die(json_encode($data));
	}
	function stop_points(){
		$data = array();
		$data['stop_points'] = array();
		$data['total_pages'] = 0;
		$data['count'] = 0;
		$sdate = $_REQUEST['sdate'];
		$edate = $_REQUEST['edate'];
		$device_id=$_REQUEST['device_id'];
		$user_id=isset($_REQUEST['user_id'])?$_REQUEST['user_id']:"";
		$page=isset($_REQUEST['page'])?$_REQUEST['page']:1;
		$limit = 15;
		$start = ($page-1)*$limit;
		$end = $page*$limit;
		if($sdate && $edate){	//search by date
			$sdate = date("Y-m-d", strtotime($sdate));
			$edate = date("Y-m-d", strtotime($edate));
		}else{
			$sdate = date("Y-m-d");
			$edate = date("Y-m-d");
		}	
		$sdate = $sdate." 00:00:00";
		$edate = $edate." 23:59:59";
		
		if($device_id!="" && $user_id!= ""){
			$query = "select am.assets_name,am.device_id	from assests_master am where am.device_id='".$device_id."' and find_in_set(am.id,(SELECT assets_ids FROM user_assets_map where user_id = $user_id))";
			$res = $this->db->query($query);
			if($res->num_rows()==0){
				die(json_encode($data));
			}else{
				$tz_query = "select timezone from  tbl_users where del_date is null and status=1 and user_id='$user_id'";
				$tz_result = $this->db->query($tz_query);
				$tz_rows = $tz_result->result_Array($tz_result);
				$timezone = $tz_rows[0]['timezone'];
				$query = "SELECT count(*) as count FROM tbl_stop_report tm left join assests_master am on tm.device_id=am.id WHERE (CONVERT_TZ(tm.ignition_off,'+00:00','".$timezone."') BETWEEN '" .$sdate."' and '".$edate."' or CONVERT_TZ(tm.ignition_on,'+00:00','".$timezone."') BETWEEN  '" .$sdate."' and '".$edate."') AND find_in_set(tm.device_id, (SELECT assets_ids FROM user_assets_map where user_id = $user_id))";
				$query .= " AND am.device_id ='".$device_id."'";
				$res = $this->db->query($query);
				$row = $res->result_Array();
				$total = $row[0]['count'];
				if($end >$total)
					$end =$total;
				$query = "SELECT tm.id,tm.device_id, tm.ignition_off, tm.ignition_on, tm.duration, tm.address, am.assets_name FROM tbl_stop_report tm left join assests_master am on tm.device_id=am.id WHERE (CONVERT_TZ(tm.ignition_off,'+00:00','".$timezone."') BETWEEN '" .$sdate."' and '".$edate."' or CONVERT_TZ(tm.ignition_on,'+00:00','".$timezone."') BETWEEN  '" .$sdate."' and '".$edate."') AND find_in_set(tm.device_id, (SELECT assets_ids FROM user_assets_map where user_id = $user_id)) ";
				$query .= " AND am.device_id ='".$device_id."'";
				$query .= " limit $start,$limit";
			//	echo $query;
				$query = $this->db->query($query);
				foreach($query->result_Array() as $row){
					$data['stop_points'][$row['id']]= array(
						"assets_id"=>$row['assets_id'],
						"ignition_off"=>$row['ignition_off'],
						"ignition_on"=>$row['ignition_on'],
						"duration"=>$row['duration'],
						"address"=>$row['address'],
					);
				}
				
			}
		}
		$data['total_pages'] = ceil($total/$limit);
		$data['count'] = count($data['stop_points']);
		die(json_encode($data));
	}
	function distance_report(){
		$data = array();
		$data['distance_report'] = array();
		$data['total_pages'] = 0;
		$data['count'] = 0;
		$sdate = $_REQUEST['sdate'];
		$edate = $_REQUEST['edate'];
		$device_id=$_REQUEST['device_id'];
		$user_id=isset($_REQUEST['user_id'])?$_REQUEST['user_id']:"";
		$page=isset($_REQUEST['page'])?$_REQUEST['page']:1;
		$limit = 15;
		$start = ($page-1)*$limit;
		$end = $page*$limit;
		if($sdate && $edate){	//search by date
			$sdate = date("Y-m-d", strtotime($sdate));
			$edate = date("Y-m-d", strtotime($edate));
		}else{
			$sdate = date("Y-m-d");
			$edate = date("Y-m-d");
		}	
		$sdate = $sdate." 00:00:00";
		$edate = $edate." 23:59:59";
		
		if($device_id!="" && $user_id!= ""){
			$query = "select am.assets_name,am.device_id	from assests_master am where am.device_id='".$device_id."' and find_in_set(am.id,(SELECT assets_ids FROM user_assets_map where user_id = $user_id))";
			$res = $this->db->query($query);
			if($res->num_rows()==0){
				die(json_encode($data));
			}else{
				$tz_query = "select timezone from  tbl_users where del_date is null and status=1 and user_id='$user_id'";
				$tz_result = $this->db->query($tz_query);
				$tz_rows = $tz_result->result_Array($tz_result);
				$timezone = $tz_rows[0]['timezone'];
				
				$query = "SELECT count(*) as count from distance_master dm left join assests_master am on am.id=dm.assets_id WHERE  find_in_set(dm.assets_id,(SELECT assets_ids FROM user_assets_map where user_id = $user_id)) and CONVERT_TZ(dm.add_date,'+00:00','".$timezone."') BETWEEN '" . $sdate . "' AND '" . $edate . "'";
				$query .=" AND am.device_id = '".$device_id."'";

				$res = $this->db->query($query);
				$row = $res->result_Array();
				$total = $row[0]['count'];
				if($end >$total)
					$end =$total;
				
				
				$query = "SELECT dm.id,CONCAT(am.assets_name,'(',am.device_id,')') as assets_id, CONVERT_TZ(dm.add_date,'+00:00','".$timezone."') as add_date, dm.distance from distance_master dm left join assests_master am on am.id=dm.assets_id  WHERE find_in_set(dm.assets_id,(SELECT assets_ids FROM user_assets_map where user_id = $user_id)) and CONVERT_TZ(dm.add_date,'+00:00','".$timezone."') BETWEEN '" . $sdate . "' AND '" . $edate . "'"; 	
				$query .=" AND am.device_id = '".$device_id."'";
				$query .= " order by dm.id desc limit $start,$limit";
				$query = $this->db->query($query);
				foreach($query->result_Array() as $row){
					$data['distance_report'][$row['id']]= array(
						"assets_id"=>$row['assets_id'],
						"date"=>date("d-m-Y",strtotime($row['add_date'])),
						"distance"=>$row['distance'],
					);
				}
				
			}
		}
		$data['total_pages'] = ceil($total/$limit);
		$data['count'] = count($data['distance_report']);
		die(json_encode($data));
	}
	function area_in_out(){
		$data = array();
		$data['area_in_out'] = array();
		$data['total_pages'] = 0;
		$data['count'] = 0;
		$sdate = $_REQUEST['sdate'];
		$edate = $_REQUEST['edate'];
		$device_id=$_REQUEST['device_id'];
		$user_id=isset($_REQUEST['user_id'])?$_REQUEST['user_id']:"";
		$page=isset($_REQUEST['page'])?$_REQUEST['page']:1;
		$limit = 15;
		$start = ($page-1)*$limit;
		$end = $page*$limit;
		if($sdate && $edate){	//search by date
			$sdate = date("Y-m-d", strtotime($sdate));
			$edate = date("Y-m-d", strtotime($edate));
		}else{
			$sdate = date("Y-m-d");
			$edate = date("Y-m-d");
		}	
		$sdate = $sdate." 00:00:00";
		$edate = $edate." 23:59:59";
		
		if($device_id!="" && $user_id!= ""){
			$query = "select am.assets_name,am.device_id	from assests_master am where am.device_id='".$device_id."' and find_in_set(am.id,(SELECT assets_ids FROM user_assets_map where user_id = $user_id))";
			//echo $query;
			$res = $this->db->query($query);
			if($res->num_rows()==0){
				die(json_encode($data));
			}else{
				$tz_query = "select timezone from  tbl_users where del_date is null and status=1 and user_id='$user_id'";
				$tz_result = $this->db->query($tz_query);
				$tz_rows = $tz_result->result_Array($tz_result);
				$timezone = $tz_rows[0]['timezone'];
				
				$query = "SELECT count(distinct(tm.id)) as count FROM area_inout_log as tm left join assests_master am on am.id = tm.device_id left join areas as ta on tm.area_id=ta.polyid WHERE find_in_set(tm.device_id,(SELECT assets_ids FROM user_assets_map where user_id = $user_id))"; 
				$query .= " AND CONVERT_TZ(tm.date_time,'+00:00','".$timezone."') BETWEEN '" .$sdate . "' AND '" . $edate . "'";
				$query .=" AND am.device_id = '".$device_id."'";
				//echo $query;
				$res = $this->db->query($query);
				$row = $res->result_Array();
				$total = $row[0]['count'];
				if($end >$total)
					$end =$total;
				
				$query = "SELECT distinct(tm.id), CONVERT_TZ(tm.date_time,'+00:00','".$timezone."') as date, tm.inout_status as status, am.assets_name as device, ta.polyname as area FROM area_inout_log as tm left join assests_master am on am.id = tm.device_id left join areas as ta on tm.area_id=ta.polyid WHERE find_in_set(tm.device_id,(SELECT assets_ids FROM user_assets_map where user_id = $user_id))"; 
		
				$query .= " AND CONVERT_TZ(tm.date_time,'+00:00','".$timezone."') BETWEEN '" . $sdate . "' AND '" . $edate . "'";
				$query .=" AND am.device_id = '".$device_id."'";
				$query .= " ORDER BY tm.id desc limit $start,$limit";
					
				$query = $this->db->query($query);
				foreach($query->result_Array() as $row){
					$data['area_in_out'][$row['id']]= array(
						"area"=>$row['area'],
						"date"=>date("d-m-Y H:i:s",strtotime($row['date'])),
						"status"=>$row['status'],
					);
				}
				
			}
		}
		$data['total_pages'] = ceil($total/$limit);
		$data['count'] = count($data['area_in_out']);
		die(json_encode($data));
	}
	function landmark_report(){
		$data = array();
		$data['landmark_report'] = array();
		$data['total_pages'] = 0;
		$data['count'] = 0;
		$sdate = $_REQUEST['sdate'];
		$edate = $_REQUEST['edate'];
		$device_id=$_REQUEST['device_id'];
		$user_id=isset($_REQUEST['user_id'])?$_REQUEST['user_id']:"";
		$page=isset($_REQUEST['page'])?$_REQUEST['page']:1;
		$limit = 15;
		$start = ($page-1)*$limit;
		$end = $page*$limit;
		if($sdate && $edate){	//search by date
			$sdate = date("Y-m-d", strtotime($sdate));
			$edate = date("Y-m-d", strtotime($edate));
		}else{
			$sdate = date("Y-m-d");
			$edate = date("Y-m-d");
		}	
		$sdate = $sdate." 00:00:00";
		$edate = $edate." 23:59:59";
		
		if($device_id!="" && $user_id!= ""){
			$query = "select am.assets_name,am.device_id	from assests_master am where am.device_id='".$device_id."' and find_in_set(am.id,(SELECT assets_ids FROM user_assets_map where user_id = $user_id))";
			//echo $query;
			$res = $this->db->query($query);
			if($res->num_rows()==0){
				die(json_encode($data));
			}else{
				$tz_query = "select timezone from  tbl_users where del_date is null and status=1 and user_id='$user_id'";
				$tz_result = $this->db->query($tz_query);
				$tz_rows = $tz_result->result_Array($tz_result);
				$timezone = $tz_rows[0]['timezone'];
				
			/*	$query = "SELECT count(distinct(tm.id)) as count FROM area_inout_log as tm left join assests_master am on am.id = tm.device_id left join areas as ta on tm.area_id=ta.polyid WHERE find_in_set(tm.device_id,(SELECT assets_ids FROM user_assets_map where user_id = $user_id))"; 
				$query .= " AND CONVERT_TZ(tm.date_time,'+00:00','".$timezone."') BETWEEN '" .$sdate . "' AND '" . $edate . "'";
				$query .=" AND am.device_id = '".$device_id."'";
				*/
				$query = "SELECT count(*) as count from landmark_log as lg LEFT JOIN landmark as lm ON lg.landmark_id = lm.id LEFT JOIN assests_master as am ON am.id = lg.device_id where find_in_set(lg.device_id,(SELECT assets_ids FROM user_assets_map where user_id = $user_id))"; 
				$query .= " AND CONVERT_TZ(lg.date_time,'+00:00','".$timezone."') BETWEEN '" . $sdate . "' AND '" . $edate . "'";
				$query .=" AND am.device_id = '".$device_id."'";
				//echo $query;
				$res = $this->db->query($query);
				$row = $res->result_Array();
				$total = $row[0]['count'];
				if($end >$total)
					$end =$total;
				
				/* $query = "SELECT distinct(tm.id), CONVERT_TZ(tm.date_time,'+00:00','".$timezone."') as date, tm.inout_status as status, am.assets_name as device, ta.polyname as area FROM area_inout_log as tm left join assests_master am on am.id = tm.device_id left join areas as ta on tm.area_id=ta.polyid WHERE find_in_set(tm.device_id,(SELECT assets_ids FROM user_assets_map where user_id = $user_id))"; 
		
				$query .= " AND CONVERT_TZ(tm.date_time,'+00:00','".$timezone."') BETWEEN '" . $sdate . "' AND '" . $edate . "'";
				$query .=" AND am.device_id = '".$device_id."'";
				$query .= " ORDER BY tm.id desc limit $start,$limit";
				*/
				$query = "SELECT lg.id,CONVERT_TZ(lg.date_time,'+00:00','".$timezone."') as date_time, lg.distance, concat(am.assets_name, concat('(',am.device_id,')')) as device_name, lm.name as landmark_name from landmark_log as lg LEFT JOIN landmark as lm ON lg.landmark_id = lm.id LEFT JOIN assests_master as am ON am.id = lg.device_id where find_in_set(lg.device_id,(SELECT assets_ids FROM user_assets_map where user_id = $user_id))"; 
		
				$query .= " AND CONVERT_TZ(lg.date_time,'+00:00','".$timezone."') BETWEEN '" . $sdate . "' AND '" . $edate . "'";
				$query .=" AND am.device_id = '".$device_id."'";
				$query .= " ORDER BY lg.id desc limit $start,$limit";
				
				$query = $this->db->query($query);
				foreach($query->result_Array() as $row){
					$data['landmark_report'][$row['id']]= array(
						"landmark_name"=>$row['landmark_name'],
						"date_time"=>date("d-m-Y H:i:s",strtotime($row['date_time'])),
						"distance"=>$row['distance'],
					);
				}
				
			}
		}
		$data['total_pages'] = ceil($total/$limit);
		$data['count'] = count($data['landmark_report']);
		die(json_encode($data));
	}
	public function logout(){
		$imei = $_REQUEST['imei'];
		$query = "DELETE FROM `pushnotification` WHERE imei = $imei";
		$rs2 = $this->db->query($query);
		$data = array("result"=>"true");					
		die(json_encode($data));
	}
    public function updateDevLatLong(){
		$imei = $_REQUEST['imei'];
                $latitude =  $_REQUEST['latitude'];
                $longitude =  $_REQUEST['longitude'];
		$query = "update `pushnotification` set latitude = '".$latitude."', longitude = '".$longitude."'  WHERE imei = $imei";
		$rs2 = $this->db->query($query);
		$data = array("result"=>"true");					
		die(json_encode($data));
	}
	
}
?>