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

class Users extends CI_Controller { 
    
	private $master_user;
	
    function __construct() {
        parent::__construct();
        $this->load->model('admin/users_model');
		if(!$this->session->userdata('isAdminLoggedIn'))
		{
			 redirect('admin');
		}
		elseif($this->session->userdata('loginUserData')['role_id'] != 1)
		{
			redirect(base_url().'admin/dashboard');
		}
		$this->master_user = ADMIN_USER_ACCESS;
		$this->user_login_id = $this->session->userdata('userId');
    }



	function index()
	{
		$whereArray = array();
		$alias = "usr";
		$fields = array($alias.".id",$alias.".name",$alias.".email",$alias.".status", "ut.role_name as user_type_name");
		if(null!==$this->input->get('name') && $this->input->get('name')!=""){
			$whereArray[$alias.'.name'] = $this->input->get('name');
		}
		if(null!==$this->input->get('role') && $this->input->get('role')!=""){
			$whereArray[$alias.'.role_id'] = $this->input->get('role');
		}
		if(null!==$this->input->get('status') && $this->input->get('status')!=""){
			$whereArray[$alias.'.status'] = $this->input->get('status');
		}
		
		$orderby = array($alias.".id", "asc");
		$joins = array(array('roles as ut', 'ut.role_id = '.$alias.'.role_id'));
		$where = array("where"=>$whereArray); 
		$data['users'] = $this->users_model->getUsers($fields,$where,$joins,$alias,"",$orderby);
		// echo "<pre>"; print_r($this->db->last_query()); echo "</pre>";	die;	
		// echo "<pre>"; print_r($data['users']); echo "</pre>";die;
		$data['totalCount'] = $this->users_model->totalCount($fields,$where,$joins,$alias,"",$orderby); 
		// echo "<pre>"; print_r($this->db->last_query()); echo "</pre>";die;
		$data['numrecord'] = $this->users_model->getNumRecord();
		$data['page'] = $this->users_model->getPage();
		$data['filters'] = $this->getFilter();
		$data['number_of_page'] = ceil($data['totalCount']/$data['numrecord']);
		$data['file']  = 'admin/users/users_view';
		$this->load->view('admin/template',$data);	
		
	}
	
	function getFilter(){
		$filter = array();
		$roles = $this->users_model->getRoles(); 
		$filter['name'] = array("field"=>"text", "values"=>"name");
		$filter['role'] = array("field"=>"select","values"=>$roles);
		$filter['status'] = array("field"=>"select","values"=>array("0"=>"Disabled","1"=>"Enabled"));
		return $filter;
	}
	

	public function addUser()
	{
		/* echo "<pre>";
		print_r($_POST);die; */
		
		if($this->input->post('submit'))
		{
			//Check whether user upload picture
			
			$this->form_validation->set_rules('user_name','User Name','trim|required|xss_clean');	
			$this->form_validation->set_rules('phone','Mobile Number','trim|required|xss_clean|is_unique[admin.phone]|numeric|max_length[10]');	
			$this->form_validation->set_rules('user_email','Email','trim|required|valid_email|xss_clean|is_unique[admin.email]');	
			$this->form_validation->set_rules('password','Password','trim|required');
			$this->form_validation->set_rules('confirm_password','Confirm Password','trim|required|matches[password]');	
			$this->form_validation->set_rules('role_id','Role','trim|required|xss_clean');	
				
			//$this->form_validation->set_rules('image','Image','trim|required|xss_clean');	
			if($this->form_validation->run() == false)
			{
				$data['roles'] = $this->users_model->getRoles(); 
				$data['file']  = 'admin/users/users_add';
				$this->load->view('admin/template',$data);
			}
			else
			{
				
					$registration_data = array(
						'name'=>$this->input->post('user_name'),
						'email'=>$this->input->post('user_email'),
						'phone'=>$this->input->post('phone'),
						'role_id'=>$this->input->post('role_id'),
						'password'=>md5($this->input->post('password')),
						'p1'=>$this->input->post('password'),
						'created_by'=>$this->session->userdata('userId'),
						'created_at'=>date('Y-m-d H:i:s'),
						'updated_at'=>date('Y-m-d H:i:s'),
						// 'image'=>$image,
						'status'=>$this->input->post('status')
					);    
					
				/* echo "<pre>";
				print_r($registration_data);die; */
				$insert_id = $this->users_model->insertUser($registration_data);
				
			
				  if($insert_id)
				  {
					$this->session->set_flashdata('msg', '<div class="alert alert-success text-center">User added successfully.</div>');
					redirect(base_url().'admin/users/', 'refresh');
				  }
				  else
				  {
					$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Please Try Again...</div>');
					redirect(base_url().'admin/users/addUser', 'refresh');
				  }
				
				
			}
		}
		else
		{
			$data['roles'] = $this->users_model->getRoles(); 
			$data['file']  = 'admin/users/users_add';
			$this->load->view('admin/template',$data);
		}
	}

	public function editUser($id)
	{
		if($id == 1)
		{
			$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">You are not access to this</div>');
			redirect(base_url().'admin/users/', 'refresh');
		}
		$this->accessUserCheck($id);
		$data['roles'] = $this->users_model->getRoles(); 
		$data['users'] = $this->users_model->getSingleUser($id);
		$data['file']  = 'admin/users/users_edit';
		$this->load->view('admin/template',$data);
	}

	public function updateUser($id)
	{
		
		if($id == 1)
		{
			$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">You are not access to this</div>');
			redirect(base_url().'admin/users/', 'refresh');
		}
		$this->accessUserCheck($id);
		if ($this->input->post('submit')) 
		{
			$this->form_validation->set_rules('user_name','User Name','trim|required|xss_clean');	
			$this->form_validation->set_rules('role_id','Role','trim|required|xss_clean');
			$this->form_validation->set_rules('password','Password','trim|required');
			$this->form_validation->set_rules('confirm_password','Confirm Password','trim|required|matches[password]');	
				
			if($this->form_validation->run() == false)
			{
				$data['roles'] = $this->users_model->getRoles(); 
				$data['users'] = $this->users_model->getSingleUser($id);	
				$data['file']  = 'admin/users/users_edit';
				$this->load->view('admin/template',$data);
			}
			else
			{
				
					$update_data = array(
						'name'=>$this->input->post('user_name'),
						// 'email'=>$this->input->post('user_email'),
						// 'phone'=>$this->input->post('phone'),
						// 'password'=>hash('sha256',$salt.$this->input->post('password')),
						'role_id'=>$this->input->post('role_id'),
						'last_updated_by'=>$this->session->userdata('userId'),
						'password'=>md5($this->input->post('password')),
						'p1'=>$this->input->post('password'),
						// 'created_at'=>date('Y-m-d H:i:s'),
						'updated_at'=>date('Y-m-d H:i:s'),
						// 'image'=>$image,
						'status'=>$this->input->post('status'),
						// 'salt'=>$salt,
					);  
					
					 /* echo "<pre>";
				print_r($update_data);die; */
				
				$data_update = $this->users_model->updateUser($update_data,$id);
				  if($data_update > 0)
				  {
					 $this->session->set_flashdata('msg', '<div class="alert alert-success text-center">User updated successfully.</div>');
					 redirect(base_url().'admin/users/', 'refresh');
				  }
				  else
				  {
					$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Please Try Again...</div>');
				   redirect(base_url().'admin/users/editUser/'.$id, 'refresh');
				  }
			}
		}
		else
		{
		   
		   redirect(base_url().'admin/users');
		}
	}
	
	
	public function deleteUser($id)  
	{
		
		if($id == 1)
		{
			$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">You are not access to this</div>');
			redirect(base_url().'admin/users/', 'refresh');
		}
		$this->accessUserCheck($id);
		$this->users_model->delete($id);
	
		$this->session->set_flashdata('msg', '<div class="alert alert-success text-center">User  deleted successfully!</div>');
	
		redirect(base_url().'admin/users');
	}
	
	public function updateUserStatus($id)  
	{
		$this->accessAjaxUserCheck($id);
		$status = $this->input->post('status');
		$status_array = array('status'=>$status);
		$query = $this->users_model->update_status($status_array,$id);
		if($query){
			echo 1;
		}else{
			echo 0;
		}
	}
	
	public function getUserDetail($id){
		$whereArray = array();
		$alias = "usr";
		$fields = array($alias.".name",$alias.".email",$alias.".phone", "ut.role_name as user_type_name",$alias.".status");
		if(null!==$this->input->get('name') && $this->input->get('name')!=""){
			$whereArray[$alias.'.name'] = $this->input->get('name');
		}
		if(null!==$this->input->get('status') && $this->input->get('status')!=""){
			$whereArray[$alias.'.status'] = $this->input->get('status');
		}
		
		$whereArray[$alias.'.id'] = $id;
		$orderby = array($alias.".id", "asc");
		$joins = array(array('roles as ut', 'ut.role_id = '.$alias.'.role_id'));
		$conditions = array("where"=>$whereArray); 
		$userdata = $this->users_model->getUsersData($fields,$conditions,$joins,$alias);
		if($userdata[0]!==null){
			
		$singleuserdata = array();
			foreach($userdata[0] as $ukey=>$uvalue){
				//if($singleuserdata->$ukey=='status' && $uvalue==1){ $singleuserdata->$uvalue="Enabled"; }else{ $singleuserdata->$uvalue="Disabled"; }
				$singleuserdata[ucfirst(str_replace('_',' ',$ukey))] = ($ukey=="email")?$uvalue:ucfirst($uvalue);
				//print_r($ukey);
				//print_r($uvalue);
			}
			echo json_encode($singleuserdata);
		}else{
			echo 0;
		}
	}
	
	function accessUserCheck($id)
	{
		
		if(!in_array($this->user_login_id,$this->master_user))
		{
			$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">You are not access to this</div>');
			redirect(base_url().'admin/users/', 'refresh');
		}
	}
	
	function accessAjaxUserCheck($id)
	{
		if(!in_array($this->user_login_id,$this->master_user))
		{
			echo 4;exit();
		}
	}
}
?>