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

class User extends CI_Controller {
	function __Construct(){
		parent::__Construct();
		if(!isset($_SESSION['USERS_DATA'])){
			redirect(base_url("login"));
		}
		$this->load->library('ts_functions');
		$this->load->library('parser');
	}
	
	public function index(){
	    $data['title'] ="customers";
	    $data['active'] ="customers";
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$data['customer'] = $this->my_model->select_data('*' , 'users',array('userType' => 2,'status'=>1),'',array('userName','ASC'));
		$data['active'] =1;
		
		$this->load->view('users/customer',$data);
		$this->load->view('footer');
	}
	
	public function incustomers(){
	    $data['title'] ="customer-inactive";
	    $data['active'] ="customer";
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$data['customer'] = $this->my_model->select_data('*' , 'users',array('userType' => 2, 'status'=>0),'',array('userName','ASC'));
		$data['active'] =0;
		
		$this->load->view('users/customer',$data);
		$this->load->view('footer');
	} 
	
	function upload_image($upPath , $name , $postFix = NULL){
		$this->CI = get_instance();
		$basePath = explode('application',dirname(__FILE__))[0];
		$uploadPath = $basePath.$upPath; 
		$config['upload_path'] = $uploadPath;
		$config['allowed_types'] = '*';
		$this->CI->load->library('upload', $config);
		if ($this->CI->upload->do_upload($name)){
			$uploaddata = $this->CI->upload->data();
			$imgName = $uploaddata['raw_name'];
			$imgExt = $uploaddata['file_ext'];
			$randomstr = substr(md5(microtime()), 0, 10);
			$uploadedImage = $randomstr.$postFix.$imgExt;
			rename($uploadPath.$imgName.$imgExt, $uploadPath.$uploadedImage);
			return $uploadedImage;
		}else{ 
			return '';
		}
	}
	public function create_user(){
		  if(isset($_POST['UserName']) && !empty($_POST['UserName'])){
		      $update_Arr =  array();
		      if(!empty($_POST['UserName'])){
		          
		          $update_Arr['userName'] = $_POST['UserName'];
		      }
		      
		      if(!empty($_POST['UserRole'])){
		          
		          $update_Arr['userType'] = $_POST['UserRole'];
		      } 
		      
		      if(!empty($_POST['UserEmail'])){
		          
		          $update_Arr['userEmail'] = $_POST['UserEmail'];
		      } 
		      
		      if(!empty($_POST['UserMobile'])){
		          
		          $update_Arr['userMobile'] = $_POST['UserMobile'];
		      }
		      
		      if(!empty($_POST['District'])){
		         
		          $District = $_POST['District'];
		          if(!empty($_POST['WordNumber'])){
		              $WordNumber = $_POST['WordNumber'];
		          }else{
		              $WordNumber =0;
		          }
		          
		          if(!empty($_POST['HouseNumber'])){
		              $HouseNumber = $_POST['HouseNumber'];
		          }else{
		              $HouseNumber =0;
		          }
		          
		          if(!empty($_POST['Town'])){
		              $Town = $_POST['Town'];
		          }else{
		              $Town =0;
		          }
		          $update_Arr['address'] = $District."|".$WordNumber."|".$Town."|".$HouseNumber;
		      } 
		      
		      if(!empty($_POST['UserPassword'])){
		          
		          $update_Arr['userPassword'] = md5($_POST['UserPassword']);
		      }
		    
	        if(isset($_FILES['ItemImage']['name']) && !empty($_FILES['ItemImage']['name'])){
				$ItemImage = $this->upload_image('/assets/uploads/' , 'ItemImage' );	
				$update_Arr['userImage'] = $ItemImage; 
			}
			if(isset($_POST['UserId']) && !empty($_POST['UserId'])){
			    
			    $where = array(
    			               'userId !='    => $_POST['UserId'],
    			               'userMobile'    => $_POST['UserMobile']
    						   );
    		    $userData = $this->my_model->select_data('*','users', $where);
			    if($userData){
			        $resp = array('status' => 0 , 'error' => 'Mobile number already exists.');
			    }else{   
    				$this->my_model->update_data_limit('users' ,$update_Arr,array('userId' => $_POST['UserId']), 1); 
    				$resp = array('status' => 1 ,'redirect' => 'user','msg'=>'Successfully updated');
			    }	
			}else{ 
			    $where = array(
    			               'userMobile'    => $_POST['UserMobile']
    						   );
    		    $userData = $this->my_model->select_data('*','users', $where);
			    if($userData){
			        $resp = array('status' => 0 , 'error' => 'Mobile number already exists.');
			    }else{
    			    $update_Arr['status'] = 1;
    				$this->my_model->insert_data('users' ,$update_Arr); 
    				$resp = array('status' => 1 ,'redirect' => 'user','msg'=>'Successfully created');
			    }
			}  
		}else{ 
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	public function edit_user(){ 
		if(isset($_POST['UsrerEditId']) && !empty($_POST['UsrerEditId'])){
			$UsrerEditId = $_POST['UsrerEditId'];
			$userData = $this->my_model->select_data('*' , 'users' , array('userId' => $UsrerEditId,'userType'=>2),'1');
			if(!empty($userData)){
				$resp = array('status' => 1 , 'userData' => $userData[0]);
			}else{
				$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
			} 
		}else{
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	public function wholesaler (){
	    $data['title'] ="Wholesalers";
	    $data['active'] ="Wholesaler";
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$data['customer'] = $this->my_model->select_data('*' , 'users',array('userType' => 3,'status'=>1),'',array('userName','ASC'));

		$data['active'] = 1;
		$this->load->view('users/wholesaler',$data);
		$this->load->view('footer');
	} 
	
	
	public function inwholesaler (){
	    $data['title'] ="Wholesalers-inactive";
	    $data['active'] ="Wholesaler";
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$data['customer'] = $this->my_model->select_data('*' , 'users',array('userType' => 3,'status'=>0),'',array('userName','ASC'));
		$data['active'] =0;
		
		$this->load->view('users/wholesaler',$data);
		$this->load->view('footer');
	}

    public function create_wholesaler(){
		  if(isset($_POST['UserName']) && !empty($_POST['UserName'])){
		      $update_Arr =  array();
		      if(!empty($_POST['UserName'])){
		          
		          $update_Arr['userName'] = $_POST['UserName'];
		      }
		      
		      if(!empty($_POST['UserEmail'])){
		          
		          $update_Arr['userEmail'] = $_POST['UserEmail'];
		      } 
		      
		      if(!empty($_POST['UserMobile'])){
		          
		          $update_Arr['userMobile'] = $_POST['UserMobile'];
		      }
		      
		      if(!empty($_POST['District'])){
		         
		          $District = $_POST['District'];
		          if(!empty($_POST['WordNumber'])){
		              $WordNumber = $_POST['WordNumber'];
		          }else{
		              $WordNumber =0;
		          }
		          
		          if(!empty($_POST['HouseNumber'])){
		              $HouseNumber = $_POST['HouseNumber'];
		          }else{
		              $HouseNumber =0;
		          }
		          
		          if(!empty($_POST['Town'])){
		              $Town = $_POST['Town'];
		          }else{
		              $Town =0;
		          }
		          $update_Arr['address'] = $District."|".$WordNumber."|".$Town."|".$HouseNumber;
		      } 
		      
		      
		      if(!empty($_POST['UserPassword'])){
		          
		          $update_Arr['userPassword'] = md5($_POST['UserPassword']);
		      }
		      
		      if(!empty($_POST['AadharNumber'])){
		          
		          $update_Arr['aadharNumber'] = $_POST['AadharNumber'];
		      }
		      
		      if(!empty($_POST['PanNumber'])){
		          
		          $update_Arr['panNumber'] = $_POST['PanNumber'];
		      }
		      
		      if(!empty($_POST['GSTNumber'])){
		          
		          $update_Arr['GSTNumber'] = $_POST['GSTNumber'];
		      }
		      
		    
	          if(isset($_FILES['WholesalerImage']['name']) && !empty($_FILES['WholesalerImage']['name'])){
				$usersImage = $this->upload_image('/assets/uploads/users/' , 'WholesalerImage' );	
				$update_Arr['userImage'] = $usersImage; 
		    	}
		    	
		      if(isset($_FILES['ShopImage']['name']) && !empty($_FILES['ShopImage']['name'])){
				$usersImage = $this->upload_image('/assets/uploads/users/' , 'ShopImage' );	
				$update_Arr['shopImage'] = $usersImage; 
		    	}
		    	
	    	  if(isset($_FILES['AadharImage']['name']) && !empty($_FILES['AadharImage']['name'])){
				$usersImage = $this->upload_image('/assets/uploads/users/' , 'AadharImage' );	
				$update_Arr['aadharImage'] = $usersImage; 
		    	}
		    	
		      if(isset($_FILES['PanImage']['name']) && !empty($_FILES['PanImage']['name'])){
				$usersImage = $this->upload_image('/assets/uploads/users/' , 'PanImage' );	
				$update_Arr['panImage'] = $usersImage; 
		    	}
		    	
			if(isset($_POST['UserId']) && !empty($_POST['UserId'])){
				
				$where = array(
				                'userId !='    => $_POST['UserId'],
    			               'userMobile'    => $_POST['UserMobile']
    						   );
    		    $usermb = $this->my_model->select_data('*','users', $where);
				
				$where = array(
				               'userId !='    => $_POST['UserId'],
    			               'userEmail'    => $_POST['UserEmail']
    						   );
    		    $userem = $this->my_model->select_data('*','users', $where);
				
				if(!empty($usermb)){
					$msg = "Mobile number already exists.";
				}
				
				if(!empty($userem)){
					$msg = "Email address already exists.";
				}
			    
			    if(!empty($msg)){
			        $resp = array('status' => 0 , 'error' => $msg);
			    }else{   
    			$this->my_model->update_data_limit('users' ,$update_Arr,array('userId' => $_POST['UserId']), 1); 
				$resp = array('status' => 1 ,'redirect' => 'user/wholesaler','msg'=>'Successfully updated.');
			    }
			}else{ 
			    
				$where = array(
    			               'userMobile'    => $_POST['UserMobile']
    						   );
    		    $usermb = $this->my_model->select_data('*','users', $where);
				
				$where = array(
    			               'userEmail'    => $_POST['UserEmail']
    						   );
    		    $userem = $this->my_model->select_data('*','users', $where);
				
				if(!empty($usermb)){
					$msg = "Mobile number already exists.";
				}
				
				if(!empty($userem)){
					$msg = "Email address already exists.";
				}
			    if(!empty($msg)){
			        $resp = array('status' => 0 , 'error' => $msg);
			    }else{
    			    $update_Arr['status'] = 1;
    			    $update_Arr['userType'] = 3;
				    $this->my_model->insert_data('users' ,$update_Arr); 
				    $resp = array('status' => 1 ,'redirect' => 'user/wholesaler','msg'=>'Successfully created.');
				    
				    //send email user details your email account
				    $user_email = $_POST['UserEmail'];
				    $user_name = $_POST['UserName'];
				    $user_pass = $_POST['UserPassword'];
				    $user_login = base_url('login');
				    $loginword="Please use this link to login";
				    
				    $this->ts_functions->sendnotificationemails('addnewuseremail', $user_email, 'New Account Created' , $user_name ,base_url(),$user_pass,$user_login,$loginword);
				    // mobile send notice 
				    $mobile_no = $_POST['UserMobile'];
				    $message = "Hi $user_name,%0aCongratulations. We have your account.%0aHere are your login details%0aUseremail : $user_email%0aPassword : $user_pass%0a$loginword%0a$user_login%0a%0a%0aThanks,%0a%0aHome Delivery.";

				    $this->ts_functions->send_msg($mobile_no,$message);
			    }
			}  
		}else{ 
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try12.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	public function edit_wholesaler(){ 
		if(isset($_POST['UsrerEditId']) && !empty($_POST['UsrerEditId'])){
			$UsrerEditId = $_POST['UsrerEditId'];
			$userData = $this->my_model->select_data('*' , 'users' , array('userId' => $UsrerEditId,'userType'=>3),'1');
			if(!empty($userData)){
				$resp = array('status' => 1 , 'userData' => $userData[0]);
			}else{
				$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
			} 
		}else{
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	
	public function userStatus(){
		
		if(isset($_POST['UserId']) && !empty($_POST['UserId']))
		{  
	        $user_id = $_POST['UserId'];
	        $status = $_POST['status'];
			
    		    $where = array(
    			               'userId'    => $user_id,
    			               'userType !='    =>1
    						   );
    		$userData = $this->my_model->select_data('*','users', $where);
    		    
			if(!empty($userData))
			{   
			   
			    $data = array(
			              'status'=>$status
			            );
			    $this->my_model->update_data('users' ,$data, array('userId'=>$user_id));	
			    $resp = array('status' => 1 , 'msg' => 'Successfully updated.');
			}else{
				$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
			}
		}else{
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}

	
}