<?php
class common_model extends CI_Model {
    
	var $is_login = false;
	var $login_id = '';
	var $login_name = '';
	var $login_type = '';
	var $login_email = '';
	var $lastLogin = '';
	var $loginDashboard = '';
	var $defaultCurrencyCode = '';
	var $defaultCountry = '';
	var $defaultCurrencySymbol = '';
	var $defaultCurrencyCountry = '';
	var $siteCurrency = '';
	var $limit =20;
	
 	function __construct() {
 		parent::__construct();
		$this->setLoginVars();
   	}
   	
	function Highlight_Words($text, $search_word)
	{
        // $text = preg_replace('#'. preg_quote($search_word) .'#i', '<span style="color: lawngreen;">\\0</span>', $text);
        $text = preg_replace('#'. preg_quote($search_word) .'#i', '<b>\\0</b>', $text);
        return $text;
    }
	
 	function setLoginVars() {
 	    
  		if($this->session->userdata('COCUSER')){  
			$userSessData = $this->session->userdata('COCUSER');
			 
 			$this->is_login=true;
			$this->login_id = $userSessData['ID'];
			$this->login_name = $userSessData['USERNAME'];
			$this->login_type = $userSessData['USER_TYPE'];
			$this->login_email = $userSessData['EMAIL'];
 			 
		}
		
		if(isset($_GET['userid']) && !empty($_GET['userid'])){
		//	echo $_GET['userid'];exit;
			 $loginRow = $this->oAuthCheck('GooglePlus',$_GET['userid']); 
			 //print_r($loginRow);exit;
			 if($loginRow){
					 $newdata['COCUSER']['authorized'] = 1;
					 $newdata['COCUSER']['ID'] = $loginRow->accountId;
					 $newdata['COCUSER']['NAME'] = $loginRow->accountFirstname;
					 $newdata['COCUSER']['USERNAME'] = $loginRow->accountUsername;
					 $newdata['COCUSER']['EMAIL'] = $loginRow->accountEmail;
					 $newdata['COCUSER']['USER_TYPE'] = $loginRow->accountType;
  					 $newdata['COCUSER']['LAST_LOGIN'] = $loginRow->accountLastLoginTime;
 					 $userLoginCount = $loginRow->accountLogincount; $userLoginCount++;
					 $updateData = array( );
					 $updateData['accountLastLoginTime'] = 	'UNIX_TIMESTAMP(NOW())'; 
					 $updateData['accountLastLoginIP'] = 	$this->input->ip_address();
					 $updateData['accountLastLoginUA'] = 	$this->input->user_agent(); 
					 $updateData['accountLogincount'] = 	$userLoginCount;    
					 $this->updateAccountData($updateData,$loginRow->accountId);
					 $track_user_details = 'User has been logged in';
					 $arrTracking =array( 'log_type' => 'UserActivity', 'log_status_msg' => 'Login', 'log_msg' => $track_user_details ); 
					 $this->tracking($arrTracking);
					 $this->session->set_userdata($newdata);
					 redirect('/home');
				 }else{
					  redirect('/home');
				 }
		}
		 
	}
	
	function oAuthCheck($oauthPro = false, $oauthId = false){
		$this->db->select('*');
		$this->db->from('accounts');
 		$this->db->where('accountDeleted',0); 
		$this->db->where('account_oauth_provider',$oauthPro); 
		$this->db->where('account_oauth_id',$oauthId); 
 		$query = $this->db->get();
 			if($query->num_rows()){return $query->row();}
			else return false;

	
	}
	
	
  	function checkLoginStatus($accountAuthStatus = false){
		$cookie_email = $_COOKIE['sfacuu__'];$cookie_password = $_COOKIE['sfacup__'];
		if(!empty($cookie_email) && !empty($cookie_password) && $this->isLogin === false){
			$userEmail = base64_decode($_COOKIE['sfacuu__']);
			$userPassword = base64_decode($_COOKIE['sfacup__']);
			$userRow = $this->accounts_model->userLoginRow($userEmail);
			$this->setCookieLogin($userRow,$userPassword);
		}else{
			if($this->is_login === true && $accountAuthStatus === false){  
 					 redirect('home');exit;
 			}else if($this->is_login === false && $accountAuthStatus === true){
 				$this->session->set_flashdata('errMsg','<span aria-hidden="true" class="glyphicon glyphicon-exclamation-sign"></span>  Please log in.');
				 $urlData['redirectUrl'] = str_replace(base_url(),'',current_url());
				 $this->session->set_userdata($urlData);
 				redirect('login');exit;
			}
		}
	}
	 
	 
	function setCookieLogin($userRow,$userPassword){
		//print_r($userRow);exit;
		if($userRow->userPassword != md5($userPassword)){
			$this->loginUnSetCookie();
		}else if($userRow->userDeleted  != 0){
			$this->loginUnSetCookie(); 
		}else if($userRow->userDisabled  != 0){
			$this->loginUnSetCookie();
		}else if($userRow->userActive  == 0){
			$this->loginUnSetCookie(); 
		}else if($userRow->userApproved  == 0){
			$this->loginUnSetCookie();
		}else{
		 if($userRow->userType == 'Buyer' || $userRow->userType == 'BulkBuyer') {
			 $newdata['SFABUYER']['authorized'] = 1;
			 $newdata['SFABUYER']['ID'] = $userRow->userId;
			 $newdata['SFABUYER']['NAME'] = $userRow->userFirstName.' '.$userRow->userLastName;
			 $newdata['SFABUYER']['USERNAME'] = $userRow->userName;
			 $newdata['SFABUYER']['EMAIL'] = $userRow->userEmail;
			 $newdata['SFABUYER']['USER_TYPE'] = $userRow->userType;
			 $newdata['SFABUYER']['LAST_LOGIN'] = $userRow->userLatestLoginTime;
		 }else{
			 $newdata['SFASELLER']['authorized'] = 1;
			 $newdata['SFASELLER']['ID'] = $userRow->userId;
			 $newdata['SFASELLER']['NAME'] = $userRow->userFirstName.' '.$userRow->userLastName;;
			 $newdata['SFASELLER']['USERNAME'] = $userRow->userName;
			 $newdata['SFASELLER']['EMAIL'] = $userRow->userEmail;
			 $newdata['SFASELLER']['USER_TYPE'] = $userRow->userType;
			 $newdata['SFASELLER']['LAST_LOGIN'] = $userRow->userLatestLoginTime;
		 } $this->session->set_userdata($newdata);
		 if($userRow->userType == 'Buyer' || $userRow->userType == 'BulkBuyer') {
			 redirect('dashboard');exit;
		 }else{
			 redirect('seller/dashboard');exit; 
		 }
		}
	}
	 
	  
	function isExistUserEmail($userEmail,$userId=false){
		$this->db->select('*');
		$this->db->from('accounts');
 		$this->db->where('accountDeleted',0); 
		$this->db->where('accountEmail',$userEmail);
		//$this->db->where("(userType != 'Admin'  OR userType != 'SubAdmin' OR userType != 'User'  OR userType != 'System')"); 
		if($userId){
			$this->db->where('accountId !=',$userId); 
		}
  		$query = $this->db->get(); 
		 
 			if($query->num_rows()){return $query->row();}
			else return false;
 	}
	function isExistUsername($username,$userId=false){
		$this->db->select('*');
		$this->db->from('accounts');
 		$this->db->where('accountDeleted',0); 
		$this->db->where('accountUsername',$username);
		//$this->db->where("(userType != 'Admin'  OR userType != 'SubAdmin' OR userType != 'User'  OR userType != 'System')"); 
		if($userId){
			$this->db->where('accountId !=',$userId); 
		}
  		$query = $this->db->get(); 
		 
 			if($query->num_rows()){return $query->row();}
			else return false;
 	}
	function isExistAdminUsername($userName,$userId=false){
		$this->db->select('*');
		$this->db->from('accounts');
 		$this->db->where('accountDeleted',0); 
		$this->db->where('accountUsername',$userName); 
		//$this->db->where("(accountType = 'Admin'  OR accountType = 'SubAdmin' OR accountType = 'Franchise' )"); 
		if($userId){
			$this->db->where('accountId !=',$userId); 
		}
  		$query = $this->db->get();
		 
 			if($query->num_rows()){return $query->row();}
			else return false;
 	}
	function checkCurrentPassword($userPassword  = false){
		$this->db->where('userPassword', do_hash($userPassword, 'md5'))
				->where('userId',$this->login_id);	
		$query = $this->db->get('users');
		 
 			if($query->num_rows()){return $query->row();}
			else return false;
	}
	function getAccountByEmail($userEmail){
		$query = $this->db->where('( accountEmail ="'.$userEmail.'" )')
								  ->where('(accountType ="User")')
								  ->where('accountDeleted',0)  ->where('accountDisabled',0) 
								  ->get('accounts'); 
			 //  echo $this->db->last_query();  
			 //  exit;
			if($query->num_rows()){
 				return $query->row();
			}else {
 				return false;
			}
	}
	function updateAccountData($updateData,$userId){
		$this->db->where('accountId', $userId);
		$this->db->update('accounts', $updateData);
	}   
	 
 	function isLockedLogin($arrData){
		$this->db->select('*');
		$this->db->from('blacklist');
		if(isset($arrData['black_for']) && !empty($arrData['black_for'])){ $this->db->where('black_for', $arrData['black_for']); }
		if(isset($arrData['black_lock_by']) && !empty($arrData['black_lock_by'])){ $this->db->where('black_lock_by', $arrData['black_lock_by']); }
		if(isset($arrData['black_lock_id'])){ $this->db->where('black_lock_id', $arrData['black_lock_id']); }//Should not check empty
		 $this->db->where('(black_unlock_time = 0 OR  black_unlock_time > '.time().')');  
		  $this->db->where('black_deleted',0);  
   		 $query = $this->db->get();	   //echo $this->db->last_query();  
		if($query->num_rows()){
			$row = $query->row();
			// print_r($row);exit;
			if($row->black_unlock_time != 0){
				return  ' Sorry your account blocked!. Please try after some time!';
			}else {
				return  ' Sorry your account blocked!. Please contact admin!';
			} 
 		}else {
			return false;	
		} 
		 
	}
	 
	function addLogMsg($arrData){
		$postData = $this->input->post();
		if(isset($postData['user_password'])){ $postData['user_password'] =  $this->encrypt->encode($postData['user_password'],'sadm');; }
		if(isset($postData['news_description'])){ $postData['news_description'] =  $this->encrypt->encode($postData['news_description'],'sadm');; }
		if(isset($postData['cv_content'])){ $postData['cv_content'] =  $this->encrypt->encode($postData['cv_content'],'sadm');; }

		$arrData['log_time'] =	time();
		$arrData['log_session'] =	$this->session->userdata('session_id');
		$arrData['log_referer_url'] =	$this->agent->referrer();
		$arrData['log_url'] =	current_url();
		$arrData['log_request_data'] =	serialize($postData);
		$arrData['log_request_type'] =	'POST';
		$this->db->insert('logs', $arrData);
		/******** Start Check Lock *******/
		$ip = $this->input->ip_address();
		$ua = $this->input->user_agent();
		$log_account = $arrData['log_account'];
		$user_ip_failed_attempt_count = $user_acc_failed_attempt_count = 5;
		$user_ip_unlock_type =  $user_acc_unlock_type = 'Auto';
		$user_ip_unlock_auto_hr = $user_acc_unlock_auto_hr = 1;
		if($this->config->item('user_ip_failed_attempt_count')) $user_ip_failed_attempt_count = $this->config->item('user_ip_failed_attempt_count');
		if($this->config->item('user_acc_failed_attempt_count')) $user_acc_failed_attempt_count = $this->config->item('user_acc_failed_attempt_count');
		if($this->config->item('user_ip_unlock_type')) $user_ip_unlock_type = $this->config->item('user_ip_unlock_type');
		if($this->config->item('user_acc_unlock_type')) $user_acc_unlock_type = $this->config->item('user_acc_unlock_type');
		if($this->config->item('user_ip_unlock_auto_hr')) $user_ip_unlock_auto_hr = $this->config->item('user_ip_unlock_auto_hr');
		if($this->config->item('user_acc_unlock_auto_hr')) $user_acc_unlock_auto_hr = $this->config->item('user_acc_unlock_auto_hr');
		$returnMsg = '';
		if(!empty($log_account)){
			$arrWhere = array('blacklist_id'=>0,'log_account'=>$log_account,'log_type'=>'UserLogin','log_status_msg'=>'InvalidLogin','log_time'=>'-1 hours');
			$arrLogs = $this->getLogs($arrWhere);
			
			if($arrLogs){
				$attemptsCount = count($arrLogs);$left_attempts = $user_acc_failed_attempt_count - $attemptsCount;
				if($left_attempts == 0){
					$black_unlock_time = 0;
					if($user_acc_unlock_type == 'Auto')$black_unlock_time =  strtotime("+$user_acc_unlock_auto_hr hours");;
						$arrData = array('black_for'=>'UserLogin','black_lock_by'=>'Account','black_unlock_type'=>$user_acc_unlock_type,
										'black_lock_id'=>$log_account,'black_unlock_time'=>$black_unlock_time);
						$black_id= $this->addLogHistory($arrData);
						$this->updateLogHistoryId($black_id,$arrWhere);
						$returnMsg =  ' Account Blocked!. Please contact Admin!';
				} else if($left_attempts == 1){
						$returnMsg =  ' If the next attempt is fail the account will be blocked!';
				}
				else{ $returnMsg =  ' Left attempts '.($left_attempts).'!'; }


			}

		}else{
			$arrWhere = array('blacklist_id'=>0,'log_account'=>0,'log_ip'=>$ip,'log_type'=>'UserLogin','log_status_msg'=>'InvalidLogin','log_time'=>'-1 hours');
			$arrLogs = $this->getLogs($arrWhere);
			if($arrLogs){
				$attemptsCount = count($arrLogs);$left_attempts = $user_ip_failed_attempt_count - $attemptsCount;
				if($left_attempts == 0){
					$black_unlock_time = 0;
					if($user_ip_unlock_type == 'Auto')$black_unlock_time =  strtotime("+$user_ip_unlock_auto_hr hours");;
						$arrData = array('black_for'=>'UserLogin','black_lock_by'=>'IP','black_unlock_type'=>$user_ip_unlock_type,
										'black_lock_id'=>$ip,'black_unlock_time'=>$black_unlock_time);
						$black_id= $this->addLogHistory($arrData);
						$this->updateLogHistoryId($black_id,$arrWhere);
						$returnMsg =  ' IP Blocked!. Please contact Admin!';
				}else if($left_attempts == 1){
						$returnMsg =  ' If the next attempt is fail your IP will be blocked!';
				}
				else{ $returnMsg =  ' Left attempts '.($left_attempts).'!'; }
			}
		}
		/******** End Check Lock *******/
		return $returnMsg;
	}
	function addLogHistory($arrData){
		$arrData['black_lock_time'] =	time();
		$arrData['black_session'] = $this->session->userdata('session_id');
		$this->db->insert('blacklist', $arrData);
		return $this->db->insert_id();
	}
	function updateLogHistoryId($black_id,$arrData){
		$locData = array( 'blacklist_id'=>$black_id );
		if(isset($arrData['log_type']) && !empty($arrData['log_type'])){ $this->db->where('log_type', $arrData['log_type']); }
		if(isset($arrData['log_ip']) && !empty($arrData['log_ip'])){ $this->db->where('log_ip', $arrData['log_ip']); }
		if(isset($arrData['blacklist_id'])){ $this->db->where('blacklist_id', $arrData['blacklist_id']); }//Should not check empty
		if(isset($arrData['log_account'])){ $this->db->where('log_account', $arrData['log_account']); }//Should not check empty
		if(isset($arrData['log_ua']) && !empty($arrData['log_ua'])){ $this->db->where('log_ua', $arrData['log_ua']); }
		if(isset($arrData['log_status_msg']) && !empty($arrData['log_status_msg'])){ $this->db->where('log_status_msg', $arrData['log_status_msg']); }
		if(isset($arrData['log_msg']) && !empty($arrData['log_msg'])){ $this->db->where('log_msg', $arrData['log_msg']); }
		if(isset($arrData['log_time']) && !empty($arrData['log_time'])){ $this->db->where('log_time > ', strtotime($arrData['log_time'])); }
		$qry = $this->db->update('logs', $locData);
	}
	function getLogs($arrData){
 		$this->db->select('*');
		$this->db->from('logs');
		if(isset($arrData['log_type']) && !empty($arrData['log_type'])){ $this->db->where('log_type', $arrData['log_type']); }
		if(isset($arrData['log_ip']) && !empty($arrData['log_ip'])){ $this->db->where('log_ip', $arrData['log_ip']); }
		if(isset($arrData['blacklist_id'])){ $this->db->where('blacklist_id', $arrData['blacklist_id']); }//Should not check empty
		if(isset($arrData['log_account'])){ $this->db->where('log_account', $arrData['log_account']); }//Should not check empty
		if(isset($arrData['log_ua']) && !empty($arrData['log_ua'])){ $this->db->where('log_ua', $arrData['log_ua']); }
		if(isset($arrData['log_status_msg']) && !empty($arrData['log_status_msg'])){ $this->db->where('log_status_msg', $arrData['log_status_msg']); }
		if(isset($arrData['log_msg']) && !empty($arrData['log_msg'])){ $this->db->where('log_msg', $arrData['log_msg']); }
		if(isset($arrData['log_time']) && !empty($arrData['log_time'])){ $this->db->where('log_time > ', strtotime($arrData['log_time'])); }
  		$query = $this->db->get();	 //echo $this->db->last_query(); 
		if($query->num_rows()){return $query->result();}
		else return false;
	}
	 
	function doUploadImage($arrUploadDate){  
		foreach($arrUploadDate as $dataK => $dataV)$$dataK = $dataV;
 		$this->load->library('verot_upload');
		$objUpload = new Verot_upload();
 		$objUpload->upload($_FILES[$fileName]);  
		if ($objUpload->uploaded){   
 			$file_new_name_body = $newName.time(); 
			$objUpload->file_new_name_body = $file_new_name_body;  
			$objUpload->file_safe_name = true;
			$objUpload->Process($dir);   
  			if ($objUpload->processed)  {  
 					$upload_data = array();
					$upload_data['file_ext'] = $objUpload->file_dst_name_ext;
					$upload_data['file_type'] = $objUpload->image_convert;
					$upload_data['image_type'] = $objUpload->image_convert;
					$upload_data['file_path'] = $objUpload->file_dst_path;
					$upload_data['full_path'] = $objUpload->file_dst_pathname ;
					$upload_data['image_width'] = $objUpload->image_dst_x ;
					$upload_data['image_height'] = $objUpload->image_dst_y;
					$upload_data['is_image'] = 1;
					if(is_array($resize) && !empty($resize)) {
						foreach($resize as $sizeDimK => $sizeDimV) {
							$xDim = $sizeDimK.'_x'; $yDim = $sizeDimK.'_y';
							if(isset($xDim) || isset($yDim)) { 
								$dir_pics = $dir.$sizeDimK.'/';
								$objUpload->file_new_name_body = $file_new_name_body;
								$objUpload->file_safe_name = true;
								$objUpload->image_resize            = true;
								$objUpload->image_ratio_fill      = true;
								if(isset($xDim))$objUpload->image_x = $sizeDimV[$xDim];
								if(isset($yDim))$objUpload->image_y = $sizeDimV[$yDim];
								$objUpload->Process($dir_pics); 
							} 
						}
					}
   					$upload_data['file_name'] = $objUpload->file_dst_name;
 					$upload_data['file_size'] = $objUpload->file_src_size;
 					$resArr = array('success'=>true,'fileData' => $upload_data);
				 
			}
			else $resArr = array('success'=>false,'message' => $objUpload->error);
		}else{ 
			$resArr = array('success'=>false,'message' => $objUpload->error);
		} 
 		 
 		return $resArr;
		
	} 
	
	function tracking($arrData) {
		if(!isset($arrData['log_request_data'])){ 
 			$postData = $this->input->post();
			$getData = $this->input->get();
			if(!empty($postData)){ 
 			if(isset($postData['userPassword'])){ $postData['userPassword'] =  $this->encrypt->encode($postData['userPassword'],'sadm');; }
 			$arrData['log_request_data']  = serialize($postData);$arrData['log_request_type'] =	'POST';
			}else if(!empty($getData)){ $arrData['log_request_data']  = serialize($getData);$arrData['log_request_type'] = 'GET'; }
		}
   		$arrData['log_account'] =	$this->login_id; 
  		$arrData['log_time'] =	time(); 
		$arrData['log_ip'] =	$this->input->ip_address();
		$arrData['log_ua'] =	$this->input->user_agent();
		$arrData['log_session'] =	$this->session->userdata('session_id');
		$arrData['log_referer_url'] =	$this->agent->referrer();
		$arrData['log_url'] =	current_url();
   		$this->db->insert('logs', $arrData); 
  	}
	
	
	function loginUnSetCookie() {
		setcookie('sfacuu__', '', time() - 31536000, '/');
		setcookie('sfacup__', '', time() - 31536000, '/');
	}
	function setCookie($name, $value, $path = false) {  
		if ($path === false) {
			$path = dirname($_SERVER['PHP_SELF']);
		}
		setcookie($name, $value, time() + 864000, $path);
	}
	function unsetCookie($name, $value, $path = false) {
		if ($path === false) {
			$path = dirname($_SERVER['PHP_SELF']);
		}//echo $path;exit;
		setcookie($name, $value, time() - 864000, $path);
	}

	 
	function isExistAdminEmail($userEmail,$userId=false){
		$this->db->select('*');
		$this->db->from('accounts');
 		$this->db->where('accountDeleted',0); 
		$this->db->where('accountEmail',$userEmail); 
		//$this->db->where("(accountType = 'Admin'  OR accountType = 'SubAdmin'  OR accountType = 'Franchise' )"); 
		if($userId){
			$this->db->where('accountId !=',$userId); 
		}
  		$query = $this->db->get();
		 
 			if($query->num_rows()){return $query->row();}
			else return false;
 	} 	 
    function getUserRow($accountId){
		$this->db->select('*');
		$this->db->from('accounts');
 		$this->db->where('accountDeleted',0); 
		$this->db->where('(accountType="User" )'); 
		$this->db->where('accountId',$accountId); 
  		$query = $this->db->get();
		if($query->num_rows()){return $query->row();}
		else return false;
 	} 
    function getUserRowByKey($accountToken){
		$this->db->select('*');
		$this->db->from('accounts');
 		$this->db->where('accountDeleted',0); 
		$this->db->where('(accountType="User" )'); 
		$this->db->where('accountToken',$accountToken); 
		
 		$query = $this->db->get();
 			if($query->num_rows()){return $query->row();}
			else return false;
 	} 	
	function activateAccount($userActiveKey){
		$upData['accountActivated'] = time();
		$this->db->where('accountToken',$userActiveKey)->update('accounts',$upData);
	}
	
	
	function updateAccount(){
		$updata = array(
				'accountFirstname' => $this->input->post('accountFirstname',true),
				'accountLastname' => $this->input->post('accountLastname',true),
				'accountUsername' => $this->input->post('accountUsername',true),
 				'accountPhone' => $this->input->post('accountPhone',true),
			 	
 		);
		 if ($_FILES['videoImage']['error'] == 0 ) {
					 
					$arrUploadDate = array( 'fileName'=>'accountImage',
											'dir'=>'./uploads/users/',
											'newName'=>'accountImage_',
											'resize'=>array('thumb_x'=>278,
															'thumb_y'=>139,
															'medium_x'=>409,
															'medium_y'=>200)
											);  
					$fileData 		= $this->doUploadImage($arrUploadDate); 
					$varfilesuccess = 0;
					if($fileData['success']){
						$videoImageName =  $fileData['fileData']['file_name'];
						$varfilesuccess = 1;
						$updata['accountImage'] = $videoImageName;
						$updata['accountUpoladType'] = 'image';
					}
				}
		$this->db->where('accountId',$this->common_model->login_id);
		$this->db->update('accounts',$updata);
		return true;
	}
	

}
