<?php
class Adm_track_model extends CI_Model {
	var $limit = 10;
	var $page = 0;
	var $pageConfig = array();
	var $errors = array();
	
	function Adm_track_model() {
		parent::__construct();
  		 $this->page = (int)$this->input->get('per_page') ;
		if($this->input->get('page_limit')){$this->limit = (int)$this->input->get('page_limit') ;}
 		if(empty($this->page))$this->page=1;				 
   		$this->pageConfig['start_num'] = (($this->page-1) * $this->limit)+1;
		$this->pageConfig['use_page_numbers'] = TRUE;
		$this->pageConfig['page_query_string'] = TRUE;
		$this->pageConfig['enable_query_strings'] = TRUE; 
  		$this->pageConfig['per_page'] = $this->limit;	
		$this->pageConfig['full_tag_open'] = '<div class="bs-example"> <ul class="pagination">';
		$this->pageConfig['full_tag_close'] = ' </ul> </div>';
		$this->pageConfig['cur_tag_open'] = '<li class="active"><a href="#">';
		$this->pageConfig['cur_tag_close'] = '</a></li>';
		$this->pageConfig['disabled_link_open'] = '<li class="disabled">';
 		$this->pageConfig['num_tag_open'] = $this->pageConfig['next_tag_open'] = $this->pageConfig['prev_tag_open'] = '<li >';
 		$this->pageConfig['disabled_link_close'] = $this->pageConfig['num_tag_close'] = $this->pageConfig['next_tag_close'] =$this->pageConfig['prev_tag_close'] = '</li>';
			$this->pageConfig['first_link'] = 'First'; 
			$this->pageConfig['first_tag_open'] = '<li class="previous ">'; 
			$this->pageConfig['first_tag_close'] = '</li>';
		 	$this->pageConfig['last_link'] = 'Last'; 
			$this->pageConfig['last_tag_open'] = '<li class="next ">'; 
			$this->pageConfig['last_tag_close'] = '</li>';
		 
 		$this->pageConfig['next_link'] = '>>';
		$this->pageConfig['prev_link'] = '<<';
  	}
	 
	function getUserRow($user_id){
		$this->db->where('accountId', $user_id)
 					->order_by('accountDeleted','asc');
 		$query = $this->db->get('accounts'); 
		if($query->num_rows()){ 
			return  $query->row();
		}else {
			return false;	
		}
	}
	function getAdminRow($userId){
		$this->db->where('userId', $userId)->where('userType','Admin')
 					->order_by('userDeleted','asc');
 		$query = $this->db->get('users'); 
		if($query->num_rows()){ 
			return  $query->row();
		}else {
			return false;	
		}
	} 
	function getUsertrackList(){
		$this->db->select('*')
				 ->from('tracking')
 		 		 ->where('track_deleted','0')
				 ->where('(track_user_type != "admin" OR "SubAdmin")');
 		if($this->input->get('searchBy', TRUE) && $this->input->get('searchKey', TRUE) && $this->input->get('searchBy', TRUE) == 'T.track_time' ){ 
			$this->db->where('FROM_UNIXTIME( T.track_time, "%m/%d/%Y" ) = ',$this->input->get('searchKey', TRUE)); 
		}else if($this->input->get('searchBy', TRUE) && $this->input->get('searchKey', TRUE) ){ 
			$this->db->like($this->input->get('searchBy', TRUE),trim($this->input->get('searchKey', TRUE))); 
		} 
		if($this->input->get('userTypeBy', TRUE) ) {
			 $this->db->where('U.user_type =', $this->input->get('userTypeBy', TRUE)); 
		}
		if($this->input->get('sortBy', TRUE) ){ 
			$this->db->order_by($this->input->get('sortBy', TRUE), $this->input->get('orderBy', TRUE)); 
		} else{
			$this->db->order_by("track_added", "desc"); 
		}	
 		$this->db->order_by("track_added", "desc"); 
		if($this->page)$this->page = ($this->page-1);
		$this->db-> limit($this->limit, ($this->page * $this->limit) ); 
		$jobQuery = $this->db->get(); //echo $this->db->last_query();
		if($jobQuery->num_rows()){
			$jobAppRow = $jobQuery->result_array();
			return $jobAppRow;
		}return false;
	}
	function getUsertrackCount(){
 	$this->db->select('*')
				 ->from('tracking')
 		 		 ->where('track_deleted','0');
 		if($this->input->get('searchBy', TRUE) && $this->input->get('searchKey', TRUE) && $this->input->get('searchBy', TRUE) == 'T.track_time' ){ 
			$this->db->where('FROM_UNIXTIME( T.track_time, "%m/%d/%Y" ) = ',$this->input->get('searchKey', TRUE)); 
		}else if($this->input->get('searchBy', TRUE) && $this->input->get('searchKey', TRUE) ){ 
			$this->db->like($this->input->get('searchBy', TRUE),trim($this->input->get('searchKey', TRUE))); 
		} 
		if($this->input->get('userTypeBy', TRUE) ) {
			 $this->db->where('U.user_type =', $this->input->get('userTypeBy', TRUE)); 
		}
		if($this->input->get('sortBy', TRUE) ){ 
			$this->db->order_by($this->input->get('sortBy', TRUE), $this->input->get('orderBy', TRUE)); 
		} else{
			$this->db->order_by("track_added", "desc"); 
		}	
 		$this->db->order_by("track_added", "desc"); 
  		$query = $this->db->get(); 
 		return $query->num_rows();
 	} 
	function getUsertrackRow($track_id){
 		$this->db->select('*')
				 ->from('tracking')
 		 		 ->where('track_deleted','0')
				 ->where('track_id',$track_id);
 		$userQry = $this->db->get(); 
		if($userQry->num_rows()){
			return $userQry->row();
		}else{
			return false;
		}
	}
	function getIPFormat($arrVal,$replaceVal,$chkCond) {
		if($arrVal) {
			foreach($arrVal as $key => $row) {
				if($chkCond == 'empty') {
					if(empty($row)) $return[$key] = $replaceVal;
					else $return[$key] = $row;
				} elseif($chkCond == 'star') {
					if($row === '*') $return[$key] = '';
					else $return[$key] = $row;
				} 
			}
			return $return;
		}
	}
 
	function addEditIPTrack($black_id){ 
		//var_dump($black_id);
		$postData = $this->input->post();
		foreach($postData as $postK => $postV)$$postK = $postV;
		//echo '<pre>'; print_r($specificIp);print_r($subnetIp);print_r($minRangIp);print_r($maxRangIp); 
		$specificIp = $this->getIPFormat($specificIp,0,'empty');
		$subnetIp = $this->getIPFormat($subnetIp,'*','empty');
		$minRangIp = $this->getIPFormat($minRangIp,0,'empty');
		$maxRangIp = $this->getIPFormat($maxRangIp,'255','empty');
		/*$specificIp = array_map(function($value) {return $value === "" ? '0' : $value;}, $specificIp);
		$subnetIp = array_map(function($value) {return $value === "" ? '*' : $value;}, $subnetIp);
		$minRangIp = array_map(function($value) {return $value === "" ? '0' : $value;}, $minRangIp);
		$maxRangIp = array_map(function($value) {return $value === "" ? '255' : $value;}, $maxRangIp);
		 print_r($specificIp);print_r($subnetIp);print_r($minRangIp);print_r($maxRangIp); 
		var_dump($specificIp);exit;*/
		$black_lock_id = '';
		if($blacklist_type == 'Specific'){
			$black_lock_id = implode('.',$specificIp);	
		}else if($blacklist_type == 'Subnet'){
			$black_lock_id = implode('.',$subnetIp);	
		}else if($blacklist_type == 'IPRange'){
			$black_lock_id = implode('.',$minRangIp).'-'.implode('.',$maxRangIp);	
		}	 
			 
   		$arrData = array('black_lock_id' => $black_lock_id,'blacklist_type'=>$blacklist_type,'black_for'=>'blacklist','black_lock_by'=>'IP');
		$arrData['black_lock_time'] =	time(); 
		$arrData['black_unlock_type'] =	'Manual'; 
		$arrData['black_session'] = $this->session->userdata('session_id');
 		if($black_id !== false) {
			$this->db->where('black_id', $black_id); 
			$qry = $this->db->update('blacklist', $arrData); 
			if($qry){ return true;} else return false;
		} else {
 			$this->db->insert('blacklist', $arrData); 		
			$iptrack_id =  $this->db->insert_id();
			if($iptrack_id){ return true;} else return false;
		}
    	} 
	 
	
	  
	 
	function getAdmintrackList(){
		$this->db->select('T.*, U.`account_type`,U.`account_email`')
				 ->from('user_track AS T')
				 ->join('accounts AS `U`','U.account_id = T.track_user_id','left')
		 		 ->where('track_deleted','0') 
				 ->where('track_by','Admin');
		if($this->input->get('searchBy', TRUE) && $this->input->get('searchKey', TRUE) && $this->input->get('searchBy', TRUE) == 'T.track_time' ){ 
			$this->db->where('FROM_UNIXTIME( T.track_time, "%m/%d/%Y" ) = ',$this->input->get('searchKey', TRUE)); 
		}else if($this->input->get('searchBy', TRUE) && $this->input->get('searchKey', TRUE) ){ 
			$this->db->like($this->input->get('searchBy', TRUE),trim($this->input->get('searchKey', TRUE))); 
		} 
		if($this->input->get('accountTypeBy', TRUE) ) {
			 $this->db->where('U.account_type =', $this->input->get('accountTypeBy', TRUE)); 
		}
 		$this->db->order_by("track_time", "desc"); 
		if($this->page)$this->page = ($this->page-1);
		$this->db-> limit($this->limit, ($this->page * $this->limit) ); 
		$jobQuery = $this->db->get(); //echo $this->db->last_query();
		if($jobQuery->num_rows()){
			$jobAppRow = $jobQuery->result_array();
			return $jobAppRow;
		}return false;
	}
	function getAdmintrackCount(){
 		$this->db->select('T.*, U.`account_type`,U.`account_email`')
				 ->from('user_track AS T')
				 ->join('accounts AS `U`','U.account_id = T.track_user_id','left')
		 		 ->where('track_deleted','0') 
				 ->where('track_by','Admin');
 		if($this->input->get('searchBy', TRUE) && $this->input->get('searchKey', TRUE) && $this->input->get('searchBy', TRUE) == 'T.track_time' ){ 
			$this->db->where('FROM_UNIXTIME( T.track_time, "%m/%d/%Y" ) = ',$this->input->get('searchKey', TRUE)); 
		}else if($this->input->get('searchBy', TRUE) && $this->input->get('searchKey', TRUE) ){ 
			$this->db->like($this->input->get('searchBy', TRUE),trim($this->input->get('searchKey', TRUE))); 
		}
		if($this->input->get('accountTypeBy', TRUE) ) {
			 $this->db->where('U.account_type =', $this->input->get('accountTypeBy', TRUE)); 
		}
 		 
  		$query = $this->db->get(); 
 		return $query->num_rows();
 	} 
	function getAdmintrackRow($track_id){
 		$this->db->select('T.*, U.`account_type`,U.`account_email`')
				 ->from('user_track AS T')
				 ->join('accounts AS `U`','U.account_id = T.track_user_id','left')
		 		 ->where('track_deleted','0') 
				 ->where('track_by','Admin');
		$accountQry = $this->db->get(); 
		if($accountQry->num_rows()){
			return $accountQry->row();
		}else{
			return false;
		}
	}
	function updateAdmintrackAction($action,$track_id){ 
 		$successMsg = false;
		if($action == 'delete'){
			$data = array( 'track_deleted' => time() );$successMsg= 'Admin track deleted successfully';
			$this->db->where('track_id', $track_id); $this->db->update('user_track', $data);
 		}else if($action == 'deleteAll'){
			$data = array( 'track_deleted' => time() );$successMsg= 'Admin tracks are deleted successfully';
			 $this->db->where_in('track_id', $track_id); $this->db->update('user_track', $data);
 		}
 		return $successMsg;
  	}
	function getPageHitCount($searchBy,$searchKey){
 		$this->db->select('*') ->from('logs') ->where('log_deleted',0) ;  
		if(!empty($searchBy) && !empty($searchKey)){ $this->db->where($searchBy, $searchKey);	 } 
  		$query = $this->db->get(); 
		return $query->num_rows();
	}
	function getLogHistory($arrData){
		if(is_array($arrData) && !empty($arrData)){
			foreach($arrData as $key=>$val)$$key=$val;	
		}
		 $arrGet = $this->input->get();
 		  if(!empty($arrGet)){  foreach($arrGet as $key=>$val)$$key=$val;	  }
		  
		 
		$this->db->select('*') ->from('logs AS L');
 		if($searchBy == 'log_user_account' && !empty($searchKey)){
			$this->db->join('accounts AS A',' A.accountId = L.log_account AND A.accountDeleted = 0 ','left');
 			 $this->db->where('(L.log_type = "UserActivity" OR  L.log_type = "UserHits" OR  L.log_type = "UserLogin")');   
			$this->db->like('A.email',$searchKey); 	
 		}else if($searchBy == 'log_admin_account' && !empty($searchKey)){
			$this->db->join('accounts AS A',' A.accountId = L.log_account AND A.accountDeleted = 0 ','left');
			 $this->db->where('( L.log_type = "AdminActivity" OR   L.log_type = "AdminLogin")');   
			$this->db->like('A.accountEmail',$searchKey); 	
 		}
		$this->db->where('L.log_deleted',0);
		if(isset($searchBy) && !empty($searchBy) && isset($searchKey) && !empty($searchKey)){
			if($searchBy != 'log_user_account' && $searchBy != 'log_admin_account'){
				$this->db->where($searchBy,$searchKey);
			}
		}
		if(isset($activityType) && $activityType == 'UserLogin'){
				$this->db->where('L.log_type','UserLogin');
		}else if(isset($activityType) && $activityType == 'AdminLogin'){
				$this->db->where('L.log_type','AdminLogin');
		}else if(isset($activityType) && $activityType == 'PageHit'){
				$this->db->where('L.log_type','UserHits');
		}else if(isset($activityType) && $activityType == 'UserActivity'){
				$this->db->where('L.log_type','UserActivity');
		}else if(isset($activityType) && $activityType == 'AdminActivity'){
				$this->db->where('L.log_type','AdminActivity');
		} 
		if(isset($blacklist_id) && !empty($blacklist_id) ){ $this->db->where('L.blacklist_id ',$blacklist_id); }
		if(isset($blacklist_ip) && !empty($blacklist_ip) ){ $this->db->where('L.log_ip ',$blacklist_ip); }
		
		if(isset($logFrom) && !empty($logFrom) ){ $this->db->where('L.log_time >='.strtotime($logFrom)); }
		if(isset($logTo) && !empty($logTo) ){ $this->db->where('L.log_time <='.strtotime($logTo)); }
			
		if(isset($groubBy) && !empty($groubBy)){
				$this->db->group_by($groubBy); 
		}
		$this->db->order_by("L.log_time", "desc"); 
		 
		if(!isset($getCount)){
			if($this->page)$this->page = ($this->page-1);
			$this->db-> limit($this->limit, ($this->page * $this->limit) ); 
		}
		$query = $this->db->get();  //echo $this->db->last_query();
		if(!isset($getCount)){
			if($query->num_rows()){
				return $query->result();
			}return false;
		}else{
			return $query->num_rows();
		}
	}
	function getBlockHistory($arrData){
			if(is_array($arrData) && !empty($arrData)){ foreach($arrData as $key=>$val)$$key=$val;	 }
			//if(!isset($black_for))$black_for = 'AdminLogin';
			$arrGet = $this->input->get();
			if(!empty($arrGet)){  foreach($arrGet as $key=>$val)$$key=$val;	 }
		
		
		$this->db->select('*') ->from('blacklist AS L');
		if($black_for == 'AdminLogin'){
		 	$this->db->join('accounts AS A',' A.accountId = L.black_lock_id AND L.black_lock_by = "Account" ','left');
			if(isset($searchKey) && !empty($searchKey)){ 
				$this->db->where('(A.email LIKE "%'.$searchKey.'%" OR L.black_lock_id LIKE "%'.$searchKey.'%")');
				 
			 }	
 		}else if($black_for == 'UserLogin'){
			$this->db->join('accounts AS A',' A.accountId = L.black_lock_id AND L.black_lock_by = "Account" ','left');
			if(isset($searchKey) && !empty($searchKey)){ 
				$this->db->where('(A.email LIKE "%'.$searchKey.'%" OR L.black_lock_id LIKE "%'.$searchKey.'%")');
				 
			 }
			  
		}else if($searchBy == 'AdminLogin'){
		 	$this->db->join('accounts AS A',' A.accountId = L.black_lock_id AND L.black_lock_by = "Account" ','left');
			if(isset($searchKey) && !empty($searchKey)){ 
				$this->db->where('(A.email LIKE "%'.$searchKey.'%" OR L.black_lock_id LIKE "%'.$searchKey.'%")');
				 
			 }	
 		}else if($searchBy == 'UserLogin'){
			$this->db->join('accounts AS A',' A.accountId = L.black_lock_id AND L.black_lock_by = "Account" ','left');
			if(isset($searchKey) && !empty($searchKey)){ 
				$this->db->where('(A.email LIKE "%'.$searchKey.'%" OR L.black_lock_id LIKE "%'.$searchKey.'%")');
				 
			 }
 		}else {
 			if(isset($searchKey) && !empty($searchKey)){  $this->db->or_like('L.black_lock_id',$searchKey); 	  }	
		}
		
		
 		if(isset($black_for) && !empty($black_for)){ $this->db->where('L.black_for',$black_for); 	 }	
 		if(isset($black_lock_by) && !empty($black_lock_by)){ $this->db->where('L.black_lock_by',$black_lock_by); 	 }	
		if(isset($black_status) &&  $black_status == 'Blocked'){ 
			 $this->db->where('(L.black_unlock_time = 0 OR  L.black_unlock_time > '.time().')');   
		}else if(isset($black_status) &&  $black_status == 'Unblocked'){ 
			 $this->db->where('(L.black_unlock_time != 0 AND  L.black_unlock_time < '.time().')');   
		} else if(isset($black_status) &&  $black_status == 'blacklist'){ 
			 $this->db->where('L.black_for','blacklist');   
		}
		 $this->db->where('L.black_deleted',0);
		if($this->input->get('sortBy', TRUE) ){ 
			$this->db->order_by($this->input->get('sortBy', TRUE), $this->input->get('orderBy', TRUE)); 
		} else{
			$this->db->order_by("L.black_lock_time", "desc"); 
		}	 
 		if(!isset($getCount)){
			if($this->page)$this->page = ($this->page-1);
			$this->db-> limit($this->limit, ($this->page * $this->limit) ); 
		}
		$query = $this->db->get(); //echo $this->db->last_query();
		if(!isset($getCount)){
			if($query->num_rows()){
				return $query->result();
			}return false;
		}else{
			return $query->num_rows();
		}
		
	}
	function updateBlacklist($action,$black_id,$log_note=''){ 
 		$successMsg = false;
		$bhRow = $this->getBlockRow($black_id);
		 if($action == 'unblock'){
				$data = array( 'black_unlock_time' => time(),'log_note'=>$log_note );
				$this->db->where('black_id', $black_id)->update('blacklist', $data);
				if($bhRow->black_lock_by == 'Account')$successMsg= 'Account Unblocked successfully!';
				else $successMsg= 'IP Unblocked successfully!';
 		}else if($action == 'delete'){
			$data = array( 'black_deleted' => time() );$successMsg= 'Blacklist deleted successfully';
			$this->db->where('black_id', $black_id); $this->db->update('blacklist', $data);
 		}else if($action == 'deleteAll'){
			$data = array( 'black_deleted' => time() );$successMsg= 'Blacklist deleted successfully';
			 $this->db->where_in('black_id', $black_id); $this->db->update('blacklist', $data);
 		}	
  		return $successMsg;
  	}
	function getBlockRow($black_id){
			$query = $this->db->where('black_id',$black_id) ->get('blacklist'); //echo $this->db->last_query();
		if($query->num_rows()){
			$jobAppRow = $query->row();
			return $jobAppRow;
		}return false;
	}
	function getBlockAccountRow($black_id,$black_for){
			
			$this->db->select('*') ->from('log_history AS L');
		if($black_for == 'AdminLogin'){
		 	$this->db->join('accounts AS A',' A.account_id = L.black_lock_id AND L.black_lock_by = "Account" ','left');
 		}else if($black_for == 'UserLogin'){
			$this->db->join('members AS A',' A.user_id = L.black_lock_id AND L.black_lock_by = "Account" ','left');
		}
		$this->db->where('black_id',$black_id);  
		$query = $this->db->get(); //echo $this->db->last_query();
		if($query->num_rows()){
			$jobAppRow = $query->row();
			return $jobAppRow;
		}return false;
	}
	function unblockIp($key){
 		$blockedIps = read_file('../BlockAdminLoginIPs.txt');
		if($blockedIps){ 
			$arrIps = explode('|',$blockedIps);
			$arrImp = array();
			foreach($arrIps as $ipStr){
				$rsAr = unserialize($ipStr);
 				if($rsAr['key'] == $key)continue;	
				$arrImp[] = $ipStr;
			}
			$impStr = implode('|',$arrImp);
			write_file('../BlockAdminLoginIPs.txt',$impStr);
 		}
	}
	function getLoginLogs($log_history,$log_type= 'AdminLogin',$log_status_msg='InvalidLogin'){
		$this->db ->where('log_history',$log_history) ->where('log_type',$log_type) ->where('log_status_msg',$log_status_msg);
  		$this->db->order_by("log_time", "desc"); 
 		$jobQuery = $this->db->get('logs'); //echo $this->db->last_query();
		if($jobQuery->num_rows()){
			$jobAppRow = $jobQuery->result();
			return $jobAppRow;
		}return false;
	} 
}
?>