<?php
// use Aws\S3\S3Client;
//         use Aws\Credentials\CredentialProvider;
//         use Aws\Exception\AwsException;
        
class Admin_model extends CI_Model {
	
	//var $cookie_path = '/'; 	
 	var $limit = 10;
	var $page = 0;
	var $pageConfig = array();
	var $errors = array();
	var $is_login = false;
	var $login_id = '';
	var $login_name = '';
	var $login_type = '';
	var $login_email = '';
	var $login_access = '';
	var $login_privileges = '';
	function __construct() {
		parent::__construct();
		$this->setLoginVars();
		 if($this->input->get('per_page',true))$this->page = (int)$this->input->get('per_page') ; 
   	}
	 
	function setLoginVars() {
  		if($this->session->userdata('BIBLEALL_RP_ADMIN')){  
			$admSessData = $this->session->userdata('BIBLEALL_RP_ADMIN');
 			$this->is_login=true;
			$this->login_id = $admSessData['ID'];
			$this->login_name = $admSessData['USERNAME'];
			$this->login_type = $admSessData['USER_TYPE'];
			$this->login_email = $admSessData['EMAIL'];
			$this->login_access = $admSessData['ACCESS'];
			$this->login_privileges = $admSessData['PRIVILEGE'];
 			 
		}
		 
	}
	
	
 	
	function getSiteConfigs() {
 		$configModule = 'GeneralSitewide';
		$this->db->select('*')
				 ->from('site_configs')
				 ->where('configModule',$configModule);
		$qry = $this->db->get();
		if($qry->num_rows())  return $qry->result_array(); 
		else return false;
 	}
 	
	function setSiteConfigs() {
	//	print_r($_POST);exit;
		$configModule = 'GeneralSitewide';
		$arrConfigs = array(
 			'site_name' => $this->input->post('site_name',TRUE),
			'site_email' => $this->input->post('site_email',TRUE),
			'site_from_email' => $this->input->post('site_from_email',TRUE),
			'site_contact_email' => $this->input->post('site_contact_email',TRUE),
			'site_career_email' => $this->input->post('site_career_email',TRUE),
			'site_support_email' => $this->input->post('site_support_email',TRUE),
			'site_facebook_link' => $this->input->post('site_facebook_link',TRUE),
			'site_twitter_link' => $this->input->post('site_twitter_link',TRUE),
			'site_google_link' => $this->input->post('site_google_link',TRUE),
			'site_pinterest_link' => $this->input->post('site_pinterest_link',TRUE), 
			'site_linkedin_link' => $this->input->post('site_linkedin_link',TRUE), 
			'ip_failed_attempt_count' => $this->input->post('ip_failed_attempt_count',TRUE), 
			'acc_failed_attempt_count' => $this->input->post('acc_failed_attempt_count',TRUE),
			'ip_unlock_type' => $this->input->post('ip_unlock_type',TRUE), 
			'ip_unlock_auto_hr' => $this->input->post('ip_unlock_auto_hr',TRUE), 
			'multiple_login_request' => $this->input->post('multiple_login_request',TRUE), 
			'user_ip_failed_attempt_count' => $this->input->post('user_ip_failed_attempt_count',TRUE), 
			'user_acc_failed_attempt_count' => $this->input->post('user_acc_failed_attempt_count',TRUE), 
			'user_ip_unlock_type' => $this->input->post('user_ip_unlock_type',TRUE), 
			'user_ip_unlock_auto_hr' => $this->input->post('user_ip_unlock_auto_hr',TRUE), 
			'user_acc_unlock_type' => $this->input->post('user_acc_unlock_type',TRUE), 
			'user_acc_unlock_auto_hr' => $this->input->post('user_acc_unlock_auto_hr',TRUE), 
 			'terms_id' => $this->input->post('terms_id',TRUE),
			'adwords_id' => $this->input->post('adwords_id',TRUE),
			'site_support_email' => $this->input->post('site_support_email',TRUE),
			'site_phone' => $this->input->post('site_phone',TRUE),
			'site_fax' => $this->input->post('site_fax',TRUE),
			'site_address' => $this->input->post('site_address',TRUE),
			'facebook_url' => $this->input->post('facebook_url',TRUE), 
			'twitter_url' => $this->input->post('twitter_url',TRUE), 
 			'google_url' => $this->input->post('google_url',TRUE),
			'site_map' => $_POST['site_map'],
			'instagram_url' => $this->input->post('instagram_url',TRUE),
			'pinterest_url' => $this->input->post('pinterest_url',TRUE),
			'adwords_status' => $this->input->post('adwords_status',TRUE)  
			
			/*'siteHomeDir' => $this->input->post('siteHomeDir',TRUE),*/
		);
		$configCount = count($arrConfigs); $i = 1;
		$selQry = ' REPLACE INTO `site_configs` 	( configModule, configName, configValue,configTime) 
					VALUES';
		foreach($arrConfigs as $name => $val) {
			$selQry.='	(	"' . $configModule . '", 
							"' . $this->db->escape_str($name) . '",
							"' . $this->db->escape_str($val) . '",
							UNIX_TIMESTAMP()
						)';	
			if ($i != $configCount) {
				$selQry .= ', ';
			}
			$i++;		
		}				
		$res = $this->db->query($selQry);
 		$arrTracking =array( 'log_type' => 'AdminActivity', 'log_status_msg'=> 'UpdateSiteSettings', 'log_msg' => 'Site Settings Updated' );
 		$this->admin_model->tracking($arrTracking);		
		if($res) return $this->db->insert_id();	
		else return false;
 	} 
	function authenticateAdmin($module){
		if ($this->is_login === false) {	
			$this->logAdminActivity('Authentication failed');
  			$this->session->set_flashdata('infoMsg', 'You are not authorized to access! Please login.');     
			redirect('/admin');exit;
		} else if ($this->login_type != 'System') { 
			$arrMyAccessModules = explode('|', $this->login_access);
			if (!in_array($module, $arrMyAccessModules)) {
				$this->logAdminActivity('Forbidden access');
				$this->session->set_flashdata('errMsg', "You don't have enough privilege to process the request");  
				redirect('/admin/dashboard');exit;
			}
		}
	}
	function checkAdminPrivilage($privilage,$goToUrl){
	
		if ($this->login_type != 'System') { 
		
			if (!preg_match("/$privilage\b/i", $this->login_privileges)) {
				 $this->session->set_flashdata('errMsg',"You don't have enough privilege to process the request!");	
					redirect($goToUrl);exit;
			} 
		}
	}
	function updateMaintenanceStatus($maintainName,$maintainStatus) {
		$updArr = array('maintainStatus' => $maintainStatus,'maintainUpdatedTime' => time());
		$this->db->where('maintainName',$maintainName)->update('maintenance',$updArr);
   	}
	
	function adminForgotPass($accountUsername){
	    
		$query = $this->db->where('(accountUsername = "'.$accountUsername.'")')
								  ->where('(accountType="System" OR accountType="Administrator" OR accountType = "SubAdmin")')
								  ->where('accountDeleted',0) 
								  ->get('accounts');
								  
			 // echo $this->db->last_query();
			 // exit;
			if($query->num_rows()){
				$row =  $query->row();
  				$this->admin_mail_model->adminForgotMail($row->accountUsername,$row->accountEmail,$row->accountToken,$row->accountType);
				return true;
			}
			else {
				$this->errors[] = 'Account not found';
				return false;
			}
	}
	
 	 function adminLoginRow($accountUsername){
 	     
 			// $query = $this->db->where('(accountUsername = "'.$accountUsername.'")')
				// 			  ->where('(accountType="System" OR accountType="Administrator" OR accountType = "SubAdmin")')
				// 			   ->order_by('accountDeleted','asc')
 			// 				  ->get('accounts');
 							  
 			  	$query = $this->db->where('(accountUsername = "'.$accountUsername.'")')
			  ->where('(accountType="System" OR accountType="Administrator" OR accountType = "SubAdmin" )')
			   ->order_by('accountDeleted','asc')
 			  ->get('accounts');
 							  
 							  
 							  
 							  // print_r($query->row()); exit();
			if($query->num_rows()){return $query->row();}
			else return false;	
 			
			
 	}
	 function getAdminRow($userId){
		$this->db->select('*');
		$this->db->from('accounts');
 		$this->db->where('accountDeleted',0); 
		$this->db->where('accountId',$userId); 
		
 		$query = $this->db->get();
 			if($query->num_rows()){return $query->row();}
			else return false;
 	} 
	function getDeletedAccountRow($userId){
		$this->db->select('*');
		$this->db->from(' jos_users');
 		$this->db->where('userDeleted != 0'); 
		$this->db->where_in('userId',$userId); 
		
 		$query = $this->db->get();
 			if($query->num_rows()){return $query->row();}
			else return false;
 	} 
	 function checkAdminEmail($userId){
		$deletedAdminRow =  $this->getDeletedAccountRow($userId);
		if($deletedAdminRow){
		//print_r($deletedAdminRow);exit;
		$this->db->select('*');
		$this->db->from(' jos_users');
 		$this->db->where('userDeleted',0)->where('(accountType="System" OR accountType="Admin" OR accountType = "SubAdmin" OR accountType = "User")'); 
		$this->db->where('userEmail',$deletedAdminRow->userEmail); 
		
 		$query = $this->db->get();//echo $this->db->last_query();
 			if($query->num_rows()){return $query->row();}
			else return false;
		}else{
			return false;
		}
 	} 
	 function checkUserEmail($userId){
		$deletedAdminRow =  $this->getDeletedAccountRow($userId);
		if($deletedAdminRow){
		//print_r($deletedAdminRow);exit;
		$this->db->select('*');
		$this->db->from(' jos_users');
 		$this->db->where('userDeleted',0); 
		$this->db->where('userEmail',$deletedAdminRow->userEmail); 
		
 		$query = $this->db->get();//echo $this->db->last_query();
 			if($query->num_rows()){return $query->row();}
			else return false;
		}else{
			return false;
		}
 	} 
	 function getAdminRowByKey($accountToken){
		$this->db->select('*');
		$this->db->from('accounts');
 		$this->db->where('accountDeleted',0); 
		$this->db->where('(accountType="System" OR accountType="Administrator" OR accountType = "SubAdmin" )'); 
		$this->db->where('accountToken',$accountToken); 
		
 		$query = $this->db->get();
 			if($query->num_rows()){return $query->row();}
			else return false;
 	} 	
	function activateAdminAccount($userActiveKey){
		$upData['accountActivated'] = time();
		$this->db->where('accountToken',$userActiveKey)->update('accounts',$upData);
	}
	function updatePassword($userActiveKey){
// 		$upData['accountPassword'] = password_decrypt($this->input->post('adminLoginPass'));
		
// 		$upData['accountPassword'] = do_hash($this->input->post('adminLoginPass'),'password_hash');
		$upData['accountPassword'] = password_hash($this->input->post('adminLoginPass'), PASSWORD_DEFAULT);
		
		//md5($this->input->post('adminLoginPass'));
		//print_r($upData);exit;
		$this->db->where('accountToken',$userActiveKey)->update('accounts',$upData);
		return true;
	}
	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 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 changeAccountDetails($userId){
		
 			
 		$accData = array(
			   'accountFirstname' => $this->input->post('name', TRUE) ,
 			   'accountUsername' => $this->input->post('username', TRUE) ,
 			   'accountEmail' => $this->input->post('email', TRUE) ,
  			);
		
		if($this->input->post('password', TRUE) && $this->input->post('password2', TRUE) &&
			$this->input->post('password', TRUE) == $this->input->post('password2', TRUE) )	
// 			$accData[ 'accountPassword'] = password_decrypt($this->input->post('password', TRUE));
// 			$accData[ 'accountPassword'] = do_hash($this->input->post('password', TRUE),'password_hash');
			$accData['accountPassword'] = password_hash($this->input->post('password',TRUE), PASSWORD_DEFAULT);

			
			$accData['accountUpdated'] = date('Y-m-d H:i:s');
			
		$this->db->where('accountId',$userId);
		$this->db->update('accounts',$accData);
// 		echo $this->db->last_query();exit;
		$arrTracking =array( 'log_type' => 'AdminActivity', 'log_status_msg'=> 'UpdateMyAccount', 'log_msg' => 'My Account Details Updated');
 		$this->tracking($arrTracking);	
		return true;	
 		 
	}
	function updateAccountData($updateData,$userId){
		$this->db->where('accountId', $userId);
		$this->db->update('accounts', $updateData);
	}     
	function addEditAdminAccount($userId){
		// print_r($_POST);exit; 
		$accessPrivilege = '';
		$accessPrivilege = $this->input->post('accessPrivilege', TRUE);
		if(count($accessPrivilege) > 1 ) $accessPrivilege = implode('|',$accessPrivilege);
		else $accessPrivilege = $accessPrivilege[0];
		
		$accessModule = $this->input->post('accessModule', TRUE);
		if(count($accessModule) > 1 ) $accessModule = implode('|',$accessModule);
		else $accessModule = $accessModule[0];
		
		$activateKey = do_hash($this->input->post('email', TRUE).time());
 		$accData = array(
			   'accountFirstname' => $this->input->post('name', TRUE) ,
 			   'accountUsername' => $this->input->post('username', TRUE) ,
 			   'accountEmail' => $this->input->post('email', TRUE) ,
			   'accountType' => $this->input->post('usertype', TRUE),
			   'accountActivated' => time(),
			   'accountToken' => $activateKey,
    		   'accountAccessPrivilege' => $accessPrivilege,
			   'accountAccessModule' => $accessModule
			);
			
		$accData['accountImage'] = base_url().'uploads/default_profile.jpg';
			
		if($this->input->post('password', TRUE) && $this->input->post('password2', TRUE) &&
			$this->input->post('password', TRUE) == $this->input->post('password2', TRUE) )	
// 			$accData[ 'accountPassword'] = password_decrypt($this->input->post('password', TRUE));;
// 			$accData[ 'accountPassword'] = do_hash($this->input->post('password', TRUE),'password_hash');
			$accData['accountPassword'] = password_hash($this->input->post('password',TRUE), PASSWORD_DEFAULT);
        
		if($userId){
		    $accData['accountUpdated'] = date('Y-m-d H:i:s');
			$this->db->where('accountId',$userId);
			$this->db->update('accounts', $accData); 
			$arrTracking =array( 'log_type' => 'AdminActivity', 'log_status_msg'=> 'UpdateSubAdmin', 'log_msg' => 'Sub Admin updated'); 
			$this->admin_model->tracking($arrTracking);	
			if($this->input->post('sendPassEmail', TRUE) == 1 && $this->input->post('changeUserPassword', TRUE) == 1 ){	
				// $this->admin_mail_model->sendPasswordEmailFromAdmin($this->input->post('usertype', TRUE),$this->input->post('username', TRUE), $this->input->post('email', TRUE),$this->input->post('password', TRUE));
			}	
		}else{
			$accData['accountCreated'] = date('Y-m-d H:i:s');
			$this->db->insert('accounts', $accData); 		
			$userId =  $this->db->insert_id();
			if($userId){
				$arrTracking =array( 'log_type' => 'AdminActivity', 'log_status_msg'=> 'CreateSubAdmin', 'log_msg' => 'Sub admin created with '.$this->input->post('email', TRUE));
			$this->admin_model->tracking($arrTracking);	
			if($this->input->post('sendEmail', TRUE) == 1){	
				// $this->admin_mail_model->sendNewAdminEmail($this->input->post('usertype', TRUE),$this->input->post('username', TRUE), $this->input->post('email', TRUE),$this->input->post('password', TRUE));
			}
 			} 	
		}		
 			return true;
		 
		
		
	}
	 function getMailTempl($template_id=false) {
		$this->db->select('*')
				 ->from('email_templates');
 		if($template_id !== false) $this->db->where('template_id',$template_id);
		$this->db->order_by("template_name", "asc"); 
 		$qry = $this->db->get(); 
		if($qry->num_rows()){  
			if($template_id !== false)return $qry->row(); 
			else return $qry->result(); 
 		}
		else return false;
	}
	function updateMailTempl() { 
	//print_r($_POST);exit;
		$template_id = $this->input->post('template_id',TRUE);
		$template_subject = $this->input->post('template_subject',TRUE);
		$template_name = $this->input->post('template_name',TRUE);
 		$template_content = $this->input->post('template_content');
   		$selQry = ' REPLACE INTO `email_templates` ( 
								template_id,
								template_name,
								template_subject,
								template_content ) 
					VALUES';
		$selQry.=' (	'.(int)$template_id.',
						"'.mysql_real_escape_string($template_name).'",
						"'.mysql_real_escape_string($template_subject).'",
						"'.mysql_real_escape_string($template_content).'" )';
		$res = $this->db->query($selQry);  
		$arrTracking =array( 'log_type' => 'AdminActivity', 'log_status_msg'=> 'UpdateMailTemplate', 'log_msg' => 'Mail Template Updated' ); 
 		$this->tracking($arrTracking);
		if($res) return true;
		else return false;
	}
		 
	 	function getPage($pageId=false) {
		$this->db->select('*')
				 ->from('pages');
 		if($pageId !== false) $this->db->where('pageId',$pageId);
		
 		$qry = $this->db->get(); 
		if($qry->num_rows()){  
			if($pageId !== false)return $qry->row(); 
			else return $qry->result(); 
 		}
		else return false;
	}
	function updatePage() { 
	//print_r($_POST);exit;
		$pageId = $this->input->post('pageId',TRUE);
		$pageTitle = $this->input->post('pageTitle',TRUE);
		$template_name = $this->input->post('template_name',TRUE);
 		$pageContent = $this->input->post('pageContent');
   		$selQry = ' REPLACE INTO `pages` ( 
								pageId,
								
								pageTitle,
								pageContent ) 
					VALUES';
		$selQry.=' (	'.(int)$pageId.',

						"'.mysql_real_escape_string($pageTitle).'",
						"'.mysql_real_escape_string($pageContent).'" )';
		$res = $this->db->query($selQry);  
		if($res) return true;
		else return false;
	}

	function getDeliveryLocations($sellerId){
		$this->db->select('*');
		$this->db->from('delivery_locations');
 		$this->db->where('sellerId',$sellerId); 
 		$query = $this->db->get();
 			if($query->num_rows()){
				$resRow =  $query->row();
				return $resRow->locations;	
			}
			else {
 				return false;	
			}
	}
	function getUserList($accountType=false){
		$this->db->select('*')->from('accounts')->where('userDeleted',0)->where('userDisabled',0); 
		//if($accountType) $this->db->where('accountType',$accountType);
 		if($accountType && $accountType == 'Buyer' ){
				$this->db->where('(accountType = "Buyer" OR  accountType = "BulkBuyer")');
			}else{
				$this->db->where('(accountType = "Seller" OR  accountType = "BulkSeller")');
			}
 		$this->db->order_by('userEmail','asc'); 
  		$query = $this->db->get();
 			if($query->num_rows()){return $query->result();}
			else return false;
 	} 
	 
	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 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 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 addLogMsg($arrData){
		$postData = $this->input->post();
		if(isset($postData['adminLoginPass'])){
			$postData['adminLoginPass'] =  $this->encryption->encrypt($postData['adminLoginPass'],array('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'];
		$ip_failed_attempt_count = $acc_failed_attempt_count = 5;
		$ip_unlock_type =  $acc_unlock_type = 'Auto';
		$ip_unlock_auto_hr = $acc_unlock_auto_hr = 1;$multiple_login_request = 'Block';
		 if($this->config->item('ip_failed_attempt_count')) $ip_failed_attempt_count = $this->config->item('ip_failed_attempt_count'); 
		 if($this->config->item('acc_failed_attempt_count')) $acc_failed_attempt_count = $this->config->item('acc_failed_attempt_count'); 
		 if($this->config->item('ip_unlock_type')) $ip_unlock_type = $this->config->item('ip_unlock_type'); 
		 if($this->config->item('acc_unlock_type')) $acc_unlock_type = $this->config->item('acc_unlock_type'); 
		 if($this->config->item('ip_unlock_auto_hr')) $ip_unlock_auto_hr = $this->config->item('ip_unlock_auto_hr'); 
		 if($this->config->item('acc_unlock_auto_hr')) $acc_unlock_auto_hr = $this->config->item('acc_unlock_auto_hr'); 
		 if($this->config->item('multiple_login_request')) $multiple_login_request = $this->config->item('multiple_login_request'); 
 		$returnMsg = '';
		if(!empty($log_account)){
			//var_dump($log_account);
			$arrWhere = array('blacklist_id'=>0,'log_account'=>$log_account,'log_type'=>'AdminLogin','log_status_msg'=>'InvalidLogin','log_time'=>'-1 hours');
			$arrLogs = $this->getLogs($arrWhere); 
			//var_dump($arrLogs);
			if($arrLogs){
				$attemptsCount = count($arrLogs);$left_attempts = $acc_failed_attempt_count - $attemptsCount;
				//var_dump($attemptsCount);var_dump($acc_failed_attempt_count);
				//var_dump($left_attempts);
				if($left_attempts == 0){
					$black_unlock_time = 0;
					if($acc_unlock_type == 'Auto')$black_unlock_time =  strtotime("+$acc_unlock_auto_hr hours");;
						$arrData = array('black_for'=>'AdminLogin','black_lock_by'=>'Account','black_unlock_type'=>$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'=>'AdminLogin','log_status_msg'=>'InvalidLogin','log_time'=>'-1 hours');
			$arrLogs = $this->getLogs($arrWhere); 	
			if($arrLogs){
				$attemptsCount = count($arrLogs);$left_attempts = $ip_failed_attempt_count - $attemptsCount;
				if($left_attempts == 0){
					$black_unlock_time = 0;
					if($ip_unlock_type == 'Auto')$black_unlock_time =  strtotime("+$ip_unlock_auto_hr hours");;
						$arrData = array('black_for'=>'AdminLogin','black_lock_by'=>'IP','black_unlock_type'=>$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).'!'; }	
			}else if($multiple_login_request == 'Block'){
					$arrSesLogs = $this->getLogs(array('blacklist_id'=>0,'log_session'=>$this->session->userdata('session_id'),'log_type'=>'AdminLogin' ,
													'log_status_msg'=>'InvalidLogin','log_time'=>'-2 min')); 
					if($arrSesLogs !== false && count($arrSesLogs) >=10){ 
						$blockSys = true;
					}else{
						$arrAllLogs = $this->getLogs(array('blacklist_id'=>0,'log_type'=>'AdminLogin' ,'log_status_msg'=>'InvalidLogin','log_time'=>'-2 min')); 
						if($arrAllLogs !== false && count($arrAllLogs) >= 20){ 
							$blockSys = true;
						}
					}
					if($blockSys){
							$account_unlock_key = do_hash($this->config->item('site_email'));
							$locData = array( 'account_unlock_key'=>$account_unlock_key  );
							$this->db->where('accountType', 'admin'); 
							$qry = $this->db->update('accounts', $locData); 	
							
						$this->adm_mail_model->loginSysBlockedEmail($account_unlock_key);
						write_file('../BlockAdminLoginSys.txt',':System Blocked:');
						$returnMsg =  ' System Blocked!. Please contact Admin!';
					}
			}
 		}
		
 		/******** End Check Lock *******/
 		return $returnMsg;		
 	}
	function updateLoginAttempts($userId,$userLoginAttempts,$userLocked,$userUnlocks){
 				$locData = array( 'userLoginAttempts'=>$userLoginAttempts,
								  'userLocked'=>$userLocked,
								  'userUnlocks'=>$userUnlocks,
								  'userLoginLastAttempt' => time() );
				$this->db->where('userId', $userId); 
				$qry = $this->db->update(' jos_users', $locData); 		
				 
	}
	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 uploadFile($fileName,$dir = './uploads/files/'){
			$arrRes = array('result'=>'Failed' , 'error'=>'ERROR!');
			$config['upload_path'] = $dir;
			$config['allowed_types'] = 'jpg|jpeg|png|gif|doc|docx|zip|rar';
			 $config['max_size']	= (1024 * 2); // in KB 
			$config['file_name'] = 'file_'.time();
			$this->load->library('upload', $config);
 			if ( ! $this->upload->do_upload($fileName)) {
 				$arrRes = array('result'=>'Failed' , 'error'=>$this->upload->display_errors());
 			} else {
				$fileData = $this->upload->data();
				 $arrRes = array('result'=>'Success' , 'fileData'=>$fileData);
 			}
			return $arrRes;
	}
	function uploadVideoFile($fileName,$dir = './uploads/codes/video/'){
			$arrRes = array('result'=>'Failed' , 'error'=>'ERROR!');
			$config['upload_path'] = $dir;
			$config['allowed_types'] = 'mp4|webm|ogg';
			 $config['max_size']	= (1024 * 20); // in KB 
			$config['file_name'] = 'file_'.time();
			$this->load->library('upload', $config);
 			if ( ! $this->upload->do_upload($fileName)) {
 				$arrRes = array('result'=>'Failed' , 'error'=>$this->upload->display_errors());
 			} else {
				$fileData = $this->upload->data();
				 $arrRes = array('result'=>'Success' , 'fileData'=>$fileData);
 			}
			return $arrRes;
	}
	function videoUplode($ImageFile){
		$uploadFileName = false;
 		$this->load->library('verot_upload');
		$objUpload = new Verot_upload();
 		$objUpload->upload($ImageFile);  
		if ($objUpload->uploaded) {
 					$file_new_name_body = 'video_'.time();
 					$dir_pics = './uploads/codes/video/';
					$objUpload->file_new_name_body = $file_new_name_body;
					$objUpload->file_safe_name = true;
					$objUpload->Process($dir_pics);
 					if ($objUpload->processed) {
 						$uploadFileName = $objUpload->file_dst_name;
					} else {
						$uploadFileName = false;
 					}
 					 
				}
		if ( ! $uploadFileName) {
 				$arrRes = array('result'=>'Failed' );
		} else {
			$fileData = '<input type="hidden" name="videfileNames[]" value="'.$uploadFileName.'">
			<input type="hidden" name="videfileTypes[]" value="'.$ImageFile['type'].'">';
			 $arrRes = array('success'=>'true' , 'fileData'=>$fileData);
		}
			return $arrRes;
	}
	function tracking($arrData) {
		 
		if(!isset($arrData['log_request_data'])){ 
 			$postData = $this->input->post();
			$getData = $this->input->get();
			if(!empty($postData)){ 
 			if(isset($postData['adminLoginPass']))
 			{ $postData['adminLoginPass'] =  $this->encryption->encrypt($postData['adminLoginPass'],array('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  logAdminActivity($activity = '')
		{
			if (!empty($activity) && ADMIN_LOG == 1) { 
 				$timestamp = time();
				$logTime = date('H:i:s', $timestamp);
				$ipAddress = $this->input->ip_address();
				$userAgent = $this->input->user_agent();
				$reqProtocol = $this->input->server('SERVER_PROTOCOL');
				$reqMethod =  $this->input->server('REQUEST_METHOD');
				$logUrl = $this->uri->uri_string();
				
				$logContent = "$timestamp\t$activity\t$reqProtocol\t$reqMethod\t$logUrl\t$ipAddress\t$userAgent\r\n";
				    $logDir = '../logs/' . $this->login_email. '/';
				 
				if (!is_dir('../logs')) {
					mkdir('../logs');
				}
				if (!is_dir($logDir)) {
					mkdir($logDir);
				}
				$logFileName = $logDir . date('Y-m-d', $timestamp) . '.log';
				
				$logFileHandler = @fopen($logFileName, 'a+');
				fwrite($logFileHandler, $logContent);
				@fclose($logFileHandler);
			}
		} 
	// Country module
	function getCountries($arrdata=array()){
		if(isset($arrdata)){
			$countryid = (isset($arrdata['countryId'])) ? $arrdata['countryId']:0;
		}
		$this->db->select('countryId, countryName, countryCode, countryFlag, countryAdded');
	  	//$this->db->from('countries');
		if($countryid){
			$this->db->where('countryId',$countryid); 
		}
		if($arrdata['countryCode']!=''){
			$this->db->where('countryCode != ',$arrdata['countryCode']); 
		}
		if($this->input->get('searchKey',true) && $this->input->get('searchBy',true)){
			$this->db->like($this->input->get('searchBy',true),$this->input->get('searchKey',true)); 
		}
	 
		if($this->input->get('sortBy',true) && $this->input->get('sortOrder',true)){
 			$this->db->order_by($this->input->get('sortBy',true),$this->input->get('sortOrder',true)); 
		}else{
 			$this->db->order_by('countryAdded','asc'); 
		}
		
		$varpage  	= ($this->input->get('per_page',true)) ? ($this->input->get('per_page',true)-1):0;
		$varoffset	= $varpage * $this->admin_model->limit;
		//echo '<pre>';print_r($arrdata);echo'</pre>';  		echo $this->db->last_query();exit;
		if(isset($arrdata['type']) && $arrdata['type'] == 'cnt') {$query = $this->db->get('countries');return $query->num_rows();}
		if(isset($arrdata['type']) && $arrdata['type'] == 'all') {
			$query = $this->db->get('countries');	
		}else{
			$query = $this->db->get('countries',$this->admin_model->limit,$varoffset);
		}
		if($query->num_rows()){ if(!$countryid){return $query->result();}else{return $query->row();}}
		else return false;
	}
	function addeditcountry($countryid=0){
		 
		$accData = array(
			   'countryName' => $this->input->post('countryName', TRUE) ,
			   'countryCode' => $this->input->post('countryCode', TRUE) 
			);
		if ($_FILES['countryFlag']['error'] == 0 ) {
			$arrUploadDate = array( 'fileName'=>'countryFlag',
									'dir'=>'./uploads/country/',
									'newName'=>'country_',
									'resize'=>array('thumb_x'=>22,
													'thumb_y'=>14,
													 )
									);  
			$fileData 		= $this->doUploadImage($arrUploadDate); 
			$varfilesuccess = 0;
			if($fileData['success']){
				$imageFileName =  $fileData['fileData']['file_name'];
				$varfilesuccess = 1;
				$accData['countryFlag'] = $imageFileName;
			} else {	}
			
		}
	
		if($countryid){
			$this->db->where('countryId',$countryid);
			$this->db->update('countries', $accData);//echo $this->db->last_query();exit; 
		}else{
			$accData['countryAdded'] = time();
			$this->db->insert('countries', $accData); //echo $this->db->last_query();exit; 		
			$countryid =  $this->db->insert_id();
		}
		if($countryid)return true; else return false;
	}
	function doCountryAction($specType,$action,$ids){
		if($action == 'delete'){
 			$status = 'deleted';$logMsg = 'Delete'.$specType;
			$successMsg= $specType.' deleted successfully';
			$data = array( 'countryDeleted' => time() );
			$this->db->where_in('countryId', $ids); 
   		}else if($action == 'disable'){
 			$status = 'disabled';$logMsg = 'Disable'.$specType;
			$data = array( 'countryDisabled' =>1 );$successMsg= $specType.' disabled successfully';
			$this->db->where_in('countryId', $ids);
   		}else if($action == 'enable'){
 			$status = 'enabled';$logMsg = 'Enable'.$specType;
			$data = array( 'countryDisabled' => 0 );$successMsg= $specType.' enabled successfully';
			$this->db->where_in('countryId', $ids);
   		}	
		$this->db->update('countries', $data);//echo $this->db->last_query();exit; 
		$arrPostData = array('action'=>$action,'countryId'=>$ids,);
		$arrTracking =array( 'log_type' => 'AdminActivity', 'log_status_msg'=> $logMsg, 'log_msg' => $successMsg,'log_request_data' =>  serialize($arrPostData), 'log_request_type' =>  'POST' );
 		//$this->admin_model->tracking($arrTracking);	
 		return $successMsg;
		
	}
	// Currency Module 
	function getCurrencies($arrdata=array()){
		if(isset($arrdata)){
			$currencyid = (isset($arrdata['currencyId'])) ? $arrdata['currencyId']:0;
		}
		$this->db->select('currencyId, currencyCode, currencyName, currencySymbol, currencyCountry, currencyAdded, currencyDisabled, currencyDeleted');
	  	//$this->db->from('countries');
		if($currencyid){
			$this->db->where('currencyId',$currencyid); 
		}
		if($this->input->get('searchKey',true) && $this->input->get('searchBy',true)){
			$this->db->like($this->input->get('searchBy',true),$this->input->get('searchKey',true)); 
		}
		if($this->input->get('searchStatus',true) && $this->input->get('searchStatus',true) == 'Enabled'){
 			$this->db->where('currencyDisabled',0); 
		}else if($this->input->get('searchStatus',true) && $this->input->get('searchStatus',true) == 'Disabled'){
 			$this->db->where('currencyDisabled',1); 
		}
		$this->db->where('currencyDeleted',0);

		if($this->input->get('sortBy',true) && $this->input->get('sortOrder',true)){
 			$this->db->order_by($this->input->get('sortBy',true),$this->input->get('sortOrder',true)); 
		}else{
 			$this->db->order_by('currencyAdded','asc'); 
		}
		$varpage  	= ($this->input->get('per_page',true)) ? ($this->input->get('per_page',true)-1):0;
		$varoffset	= $varpage * $this->admin_model->limit;
		
  		
		if(isset($arrdata['type']) && $arrdata['type'] == 'cnt') {$query = $this->db->get('currencies');return $query->num_rows();}
		$query = $this->db->get('currencies',$this->admin_model->limit,$varoffset);//echo $this->db->last_query();exit;
		if($query->num_rows()){ if(!$currencyid){return $query->result();}else{return $query->row();}}
		else return false;
	}
	function isExistCountry($arrdata){
		if(count($arrdata)>0){
			$countryname = (isset($arrdata['countryName'])) ? $arrdata['countryName']:'';
			$countryid = (isset($arrdata['countryId'])) ? $arrdata['countryId']:'';
			$this->db->select('countryId');
			if($countryname){
				$this->db->where('countryName',$countryname); 
			}
			if($countryid){
				$this->db->where('countryId !=',$countryid); 
			}
			 
			$query = $this->db->get('countries');//echo $this->db->last_query();exit;
			if($query->num_rows()){
				return true;
			}else{
				return false;	
				
			}
		}
	}
	function addeditState($stateId=0){
 		$accData = array(
			   'stateName' => $this->input->post('stateName', TRUE) ,
			   'countryCode' => $this->input->post('countryCode', TRUE) 
			);
  		if($stateId){
			$this->db->where('stateId',$stateId);
			$this->db->update('states', $accData); 
		}else{
			$accData['stateAdded'] = time();
 			$this->db->insert('states', $accData); 		
			$stateId =  $this->db->insert_id();
		}
		if($stateId)return true; else return false;
	}
	function doStateAction($specType,$action,$ids){
		if($action == 'delete'){
 			$status = 'deleted';$logMsg = 'Delete'.$specType;
			$successMsg= $specType.' are deleted successfully';
			$data = array( 'stateDeleted' => time() );
			$this->db->where_in('stateId', $ids); 
   		}else if($action == 'disable'){
 			$status = 'disabled';$logMsg = 'Disable'.$specType;
			$data = array( 'countryDisabled' =>1 );$successMsg= $specType.' are disabled successfully';
			$this->db->where_in('stateId', $ids);
   		}else if($action == 'enable'){
 			$status = 'enabled';$logMsg = 'Enable'.$specType;
			$data = array( 'countryDisabled' => 0 );$successMsg= $specType.' are enabled successfully';
			$this->db->where_in('stateId', $ids);
   		}	
		$this->db->update('states', $data);//echo $this->db->last_query();exit; 
		$arrPostData = array('action'=>$action,'stateId'=>$ids,);
		$arrTracking =array( 'log_type' => 'AdminActivity', 'log_status_msg'=> $logMsg, 'log_msg' => $successMsg,'log_request_data' =>  serialize($arrPostData), 'log_request_type' =>  'POST' );
 		//$this->admin_model->tracking($arrTracking);	
 		return $successMsg;
		
	}
	

	function imageUplode_new($ImageFile, $item_id){ //var_dump($ImageFile); exit;
		$uploadFileName = false;
 		$this->load->library('Verot_upload');
		$objUpload = new CI_Verot_upload();
		$galleryVideoThumbType = $galleryVideoThumbUrl ='';
 		$objUpload->upload($ImageFile);  
 		$file_ext = pathinfo($ImageFile['name'], PATHINFO_EXTENSION);  //var_dump($file_ext); exit;
		if ($objUpload->uploaded) {
		    $mti = str_replace(".","",microtime());
		    $mti = str_replace(" ","", $mti);
 					$file_new_name_body = 'img_'.$mti;
 				//	echo $file_new_name_body;exit;
 					$dir_pics = './uploads/gallery_img';
					$objUpload->file_new_name_body = $file_new_name_body;
					$objUpload->file_safe_name = true;
					$objUpload->Process($dir_pics);
 					if ($objUpload->processed) {
 						$uploadFileName = $objUpload->file_dst_name;
 						if( $file_ext == 'jpg'){
 						$galType = $this->input->post('galleryType', TRUE);
 						}
 						else if($file_ext == 'png'){
 						  $galType = $this->input->post('galleryType', TRUE);  
 						}
 						else if($file_ext == 'gif'){
 						  $galType = $this->input->post('galleryType', TRUE);  
 						}
 						else if($file_ext == 'jpeg'){
 						  $galType = $this->input->post('galleryType', TRUE);  
 						}
 						else if($file_ext == 'webp'){
 						   $galType = $this->input->post('galleryType', TRUE); 
 						}
 						else if($file_ext == 'mp4'){
 						   $galType = "videos"; 
 						}
 						else if($file_ext == 'avi'){
 						   $galType = "videos"; 
 						}
 						else if($file_ext == 'flv'){
 						   $galType = "videos";  
 						}
 						else if($file_ext == 'mov'){
 						   $galType = "videos"; 
 						}
 						else if($file_ext == 'wmv'){
 						   $galType = "videos";  
 						}
 			// 			var_dump($galType); 
 						//for vidoe 1 ake thumimg
 						if($galType == 'videos') { //var_dump("1");
 						    $filname = $uploadFileName ;
                        	$filname = str_replace(".mp4","", $filname);
                        	$filname = str_replace(".wmv","", $filname);
                        	$filname = str_replace(".flv","", $filname);
                        	$filname = str_replace(".mov","", $filname);
                        	$filname = str_replace(".avi","", $filname);
                        	$filname = $filname.".jpg";
                        	$videoUrl = mail_url().'uploads/gallery_video/'.$uploadFileName; //var_dump($videoUrl); exit;
                        	$thumbnail = mail_url().'uploads/gallery_video/'.$filname;
                        	$thumbnailU = mail_url().'uploads/gallery_video/thumb_'.$filname;  
                        	// shell command [highly simplified, please don't run it plain on your script!]
                        	shell_exec("ffmpeg -i $videoUrl -deinterlace -an -ss 1 -t 00:00:01 -r 1 -y -vcodec mjpeg -f mjpeg  -s 240x180 $thumbnail 2>&1");
                        // 	echo "ffmpeg -i $videoUrl -deinterlace -an -ss 1 -t 00:00:01 -r 1 -y -vcodec mjpeg -f mjpeg  -s 240x180 $thumbnail 2>&1";
                        	$galleryVideoThumbUrl = $thumbnailU;
                  			$galleryVideoThumbType = 2;
                   			
 						}
					} else {
						$uploadFileName = false;
 					}
 					 
				}
		if ( ! $uploadFileName) {
 				$arrRes = array('result'=>'Failed' );
		} else {
			
   			$accData = array(
				'galleryType' => $galType,
				'item_id' => $item_id,
				// 'galleryTitle' => $this->input->post('galleryTitle', TRUE),
  		// 		'gallerySearchkey' => $this->input->post('gallerySearchkey', TRUE),
 			// 	'galleryUploadType' => 1,
				'galleryVideoThumbType' => $galleryVideoThumbType,
				'galleryVideoThumbUrl' => $galleryVideoThumbUrl,
			    'gallery_url' => mail_url().'uploads/gallery_img/'.$uploadFileName ,
    			);
    		
		     	$accData['created_at'] = date('Y-m-d H:i:s');
		     	
		     	//echo "<pre>";print_r($accData);
 			$this->db->insert('gallery', $accData); 		
			$galleryId =  $this->db->insert_id();
			
			$fileData = '<input type="hidden" name="videfileNames[]" value="'.$uploadFileName.'">
			<input type="hidden" name="videfileTypes[]" value="'.$ImageFile['type'].'">';
			 $arrRes = array('success'=>'true' , 'fileData'=>$fileData);
			 //$galType = $this->input->post('galleryType', TRUE);
			 if($galType == 'Images')
			    $this->session->set_flashdata('successMsg',"Images Uploaded Successfully");
			 else $this->session->set_flashdata('successMsg',"Videos Uploaded Successfully");
		}
			return $arrRes;
	}
	
	function itembulkimageUplode($ImageFile, $item_id){ //var_dump($ImageFile); exit;
		$uploadFileName = false;
 		$this->load->library('Verot_upload');
		$objUpload = new CI_Verot_upload();
		$galleryVideoThumbType = $galleryVideoThumbUrl ='';
 		$objUpload->upload($ImageFile);  
 		$file_ext = pathinfo($ImageFile['name'], PATHINFO_EXTENSION);  //var_dump($file_ext); exit;
		if ($objUpload->uploaded) {
		    $mti = str_replace(".","",microtime());
		    $mti = str_replace(" ","", $mti);
 					$file_new_name_body = 'img_'.$mti;
 				//	echo $file_new_name_body;exit;
 					$dir_pics = './uploads/gallery_img';
					$objUpload->file_new_name_body = $file_new_name_body;
					$objUpload->file_safe_name = true;
					$objUpload->Process($dir_pics);
 					if ($objUpload->processed) {
 						$uploadFileName = $objUpload->file_dst_name;
 						if( $file_ext == 'jpg'){
 						$galType = "Images";
 						}
 						else if($file_ext == 'png'){
 						  $galType = "Images";
 						}
 						else if($file_ext == 'gif'){
 						  $galType = "Images";  
 						}
 						else if($file_ext == 'jpeg'){
 						  $galType = "Images";  
 						}
 						else if($file_ext == 'webp'){
 						   $galType = "Images"; 
 						}
 						else if($file_ext == 'mp4'){
 						   $galType = "videos"; 
 						}
 						else if($file_ext == 'avi'){
 						   $galType = "videos"; 
 						}
 						else if($file_ext == 'flv'){
 						   $galType = "videos";  
 						}
 						else if($file_ext == 'mov'){
 						   $galType = "videos"; 
 						}
 						else if($file_ext == 'wmv'){
 						   $galType = "videos";  
 						}
 			// 			var_dump($galType); 
 						//for vidoe 1 ake thumimg
 						if($galType == 'videos') { //var_dump("1");
 						    $filname = $uploadFileName ;
                        	$filname = str_replace(".mp4","", $filname);
                        	$filname = str_replace(".wmv","", $filname);
                        	$filname = str_replace(".flv","", $filname);
                        	$filname = str_replace(".mov","", $filname);
                        	$filname = str_replace(".avi","", $filname);
                        	$filname = $filname.".jpg";
                        	$videoUrl = 'uploads/gallery_img/'.$uploadFileName; //var_dump($videoUrl); exit;
                        	$thumbnail = 'uploads/gallery_video_thumb/'.$filname;
                        	$thumbnailU = mail_url().'uploads/gallery_video/thumb_'.$filname;  
                        	// shell command [highly simplified, please don't run it plain on your script!]
                        	shell_exec("ffmpeg -i $videoUrl -deinterlace -an -ss 1 -t 00:00:01 -r 1 -y -vcodec mjpeg -f mjpeg  -s 240x180 $thumbnail 2>&1");
                        	
                        // 	$file_Upload_res 		= $this->file_Upload_2('name', $filname,'item_bulk'); var_dump($file_Upload_res); exit;
                        //	echo "ffmpeg -i $videoUrl -deinterlace -an -ss 1 -t 00:00:01 -r 1 -y -vcodec mjpeg -f mjpeg  -s 240x180 $thumbnail 2>&1";
                        	$galleryVideoThumbUrl = mail_url().$thumbnail;
                  			$galleryVideoThumbType = 2;
                   			
 						}
					} else {
						$uploadFileName = false;
 					}
 					 
				}
		if ( ! $uploadFileName) {
 				$arrRes = array('result'=>'Failed' );
		} else {
		    
		    
            $gallery_name = pathinfo($this->input->post('qqfilename', TRUE), PATHINFO_FILENAME);

   			$accData = array(
				'galleryType' => $galType,
				'item_id' => $item_id,
			    'gallery_url' => mail_url().'uploads/gallery_img/'.$uploadFileName ,
			    'gallery_name' =>  $gallery_name,
			    'galleryVideoThumbUrl' => $galleryVideoThumbUrl,
			    
    			);
    		
		     	$accData['created_at'] = date('Y-m-d H:i:s');
		     	
		     	//echo "<pre>";print_r($accData);
 			$this->db->insert('gallery', $accData); 		
			$galleryId =  $this->db->insert_id();
			
			$fileData = '<input type="hidden" name="videfileNames[]" value="'.$uploadFileName.'">
			<input type="hidden" name="videfileTypes[]" value="'.$ImageFile['type'].'">';
			
			
			
			 $arrRes = array('success'=>'true' , 'fileData'=>$fileData);
			 //$galType = $this->input->post('galleryType', TRUE);
			 if($galType == 'Images')
			    $this->session->set_flashdata('successMsg',"Images Uploaded Successfully");
			 else $this->session->set_flashdata('successMsg',"Videos Uploaded Successfully");
		}
			return $arrRes;
	}
	
	
	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(isset($resize) && (isset($resize['thumb_x']) || isset($resize['thumb_y']))){
						$dir_pics = $dir.'thumbs/';
						$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($resize['thumb_x']))$objUpload->image_x = $resize['thumb_x'];
						if(isset($resize['thumb_y']))$objUpload->image_y = $resize['thumb_y'];
  						$objUpload->Process($dir_pics);
					}
					if(isset($resize) && (isset($resize['large_x']) || isset($resize['large_y']))){
						$dir_pics = $dir.'large/';
						$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($resize['large_x']))$objUpload->image_x = $resize['large_x'];
						if(isset($resize['large_y']))$objUpload->image_y = $resize['large_y'];
						$objUpload->Process($dir_pics);
					}
					if(isset($resize) && (isset($resize['medium_x']) || isset($resize['medium_y']))){
						$dir_pics = $dir.'medium/';
						$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($resize['medium_x']))$objUpload->image_x = $resize['medium_x'];
						if(isset($resize['medium_y']))$objUpload->image_y = $resize['medium_y'];
						$objUpload->Process($dir_pics);
					}
					if(isset($resize) && (isset($resize['710x416_x']) || isset($resize['710x416_y']))){
						$dir_pics = $dir.'710x416/';
						$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($resize['710x416_x']))$objUpload->image_x = $resize['710x416_x'];
						if(isset($resize['710x416_y']))$objUpload->image_y = $resize['710x416_y'];
						$objUpload->Process($dir_pics);
					}if(isset($resize) && (isset($resize['415x200_x']) || isset($resize['415x200_y']))){
						$dir_pics = $dir.'415x200/';
						$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($resize['415x200_x']))$objUpload->image_x = $resize['415x200_x'];
						if(isset($resize['415x200_y']))$objUpload->image_y = $resize['415x200_y'];
						$objUpload->Process($dir_pics);
					}
					if(isset($resize) && (isset($resize['274x200_x']) || isset($resize['274x200_y']))){
						$dir_pics = $dir.'274x200/';
						$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($resize['274x200_x']))$objUpload->image_x = $resize['274x200_x'];
						if(isset($resize['274x200_y']))$objUpload->image_y = $resize['274x200_y'];
						$objUpload->Process($dir_pics);
					}
					if(isset($resize) && (isset($resize['559x416_x']) || isset($resize['274x200_y']))){
						$dir_pics = $dir.'559x416/';
						$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($resize['559x416_x']))$objUpload->image_x = $resize['559x416_x'];
						if(isset($resize['559x416_y']))$objUpload->image_y = $resize['559x416_y'];
						$objUpload->Process($dir_pics);
					}
					if(isset($resize) && (isset($resize['543x486_x']) || isset($resize['543x486_y']))){
						$dir_pics = $dir.'543x486/';
						$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($resize['543x486_x']))$objUpload->image_x = $resize['543x486_x'];
						if(isset($resize['543x486_y']))$objUpload->image_y = $resize['543x486_y'];
						$objUpload->Process($dir_pics);
					}if(isset($resize) && (isset($resize['783x284_x']) || isset($resize['543x486_y']))){
						$dir_pics = $dir.'783x284/';
						$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($resize['783x284_x']))$objUpload->image_x = $resize['783x284_x'];
						if(isset($resize['783x284_y']))$objUpload->image_y = $resize['783x284_y'];
						$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 getAllUsers(){
		$this->db->select('*');
		$this->db->from('accounts')->where('accountType','User');
 		$this->db->where('accountDeleted',0); 
		 
		
 		$query = $this->db->get();
 			if($query->num_rows()){return $query->result();}
			else return false;
 	} 

	function uploadUrl($title,$id){
		$accData['roomUrl'] = url_title(strtolower($title.'_'.$id));
		$this->db->where('roomId',$id);
		$this->db->update('chat_rooms', $accData); 
 	}

	
	function imageUplodeBulk($ImageFile){  //var_dump($ImageFile); exit;
		$uploadFileName = false;
 		$this->load->library('verot_upload');
		$objUpload = new CI_Verot_upload();
 		$objUpload->upload($ImageFile);  
		if ($objUpload->uploaded) {
 					$file_new_name_body = 'img_'.time();
 					$dir_pics = './uploads/codes/stdb/';
					$objUpload->file_new_name_body = $file_new_name_body;
					$objUpload->file_safe_name = true;
					$objUpload->Process($dir_pics);
 					if ($objUpload->processed) {
 						$uploadFileName = $objUpload->file_dst_name;
					} else {
						$uploadFileName = false;
 					}
 					 
				}
		if ( ! $uploadFileName) {
 				$arrRes = array('result'=>'Failed' );
		} else {
			$accData = array(
				'statusType' => 2,
				'categoryId' => $catId,
				'imageURL' => $GLOBALS['ARR_CONFIG']['site_url']."uploads/codes/stdb/".$uploadFileName,
				'uploadType' => 1
				
  			);
		     $accData['statusdbCreated'] = time();
 			$this->db->insert('statusdb', $accData); 		
			$statusdbId =  $this->db->insert_id();
			
			$fileData = '<input type="hidden" name="videfileNames[]" value="'.$uploadFileName.'">
			<input type="hidden" name="videfileTypes[]" value="'.$ImageFile['type'].'">';
			 $arrRes = array('success'=>'true' , 'fileData'=>$fileData);
			 $this->session->set_flashdata('successMsg',"Images Uploaded Successfully");
		}

           


			return $arrRes;
	} 


}



