<?php 
/*
Fungsi : Controller untuk admin user
*/

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

class Admin_user extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	 
	 //Menu ID utk keperluan otorisasi
	var $menu_list_user  = 22;
	var $menu_add_user = 19;

	
	function __construct()
	{
		parent::__construct();
		
		$this->load->model('admin/admin_model', '', TRUE);
		$this->fungsi->check_login();
		$this->fungsi->sess_search_segment();
	}
	
	
	public function index()
	{	
		$this->admin_add_user();
		//Hapus data session pencarian
		
	}
	
	/* Admin add user */
	function admin_add_user()
	{	
		//Otorisasi menu
		$this->fungsi->menu_auth($this->menu_add_user);
		
		//Kirim value form yang tidak termasuk dalam validasi
		$data['default']['cb_role'] = $this->input->post('cb_role');
		$data['default']['cb_idcab'] = $this->input->post('cb_idcab');
		
		//Jika data rg_lock kosong maka set 1 sebagai nilai default
		if($this->input->post('rg_lock')=='')
		{
				$data['default']['rg_lock'] = 0;
		}
		/* Generate combo box */
			$query_role = $this->admin_model->get_role_list();
			$data_role = $query_role->result();
			$data['role']='';
			foreach($data_role as $row)
			{
			$data['role'] .= $row->roleid==$data['default']['cb_role'] ? '<option value="'.$row->roleid.'" selected="selected">': '<option value="'.$row->roleid.'">';
			$data['role'] .= $row->rolename.' - '.$row->roledesc.'</option>';
			}	
			
			/*Generate combo box cabang*/
			$query_cab = $this->admin_model->get_cabang_list();
			$data_cab = $query_cab->result();
			$data['cab']='';
			foreach($data_cab as $row_cab)
			{
			$data['cab'] .= $row_cab->idcab==$data['default']['cb_idcab'] ? '<option value="'.$row_cab->idcab.'" selected="selected">': '<option value="'.$row_cab->idcab.'">';
			$data['cab'] .= $row_cab->idcab.' - '.$row_cab->cabname.'</option>';
			}	
			
		$data['menu_path'] = 'ADMIN > USER > ADD USER';
		$data['form_action']= site_url('admin/admin_user/add_user');
		//$data['link'] = array('link_back' => anchor('admin/admin_user','Back', array('class' => 'back')));
		$this->load->view('admin/admin_user_form', $data);
		
	}
	
	/* Add user */
	function add_user()
	{	
		//Check otorisasi
		$this->fungsi->trans_auth($this->session->userdata('add'));
		
		/* Set validasi */
		$config = array(
               array(
                     'field'   => 'txt_uid',
                     'label'   => 'User ID',
                     'rules'   => 'required|callback_username_check'
                  ),
               array(
                     'field'   => 'txt_dispname',
                     'label'   => 'Display name',
                     'rules'   => 'required'
                  ),
				array(
                     'field'   => 'txt_pass',
                     'label'   => 'Password',
                     'rules'   => 'required|min_length[6]'
                  ),
				  array(
                     'field'   => 'txt_pass2',
                     'label'   => 'Re-type password',
                     'rules'   => 'required|min_length[6]|matches[txt_pass]'
                  ),
				  array(
                     'field'   => 'txt_email',
                     'label'   => 'Email',
                     'rules'   => 'required|valid_email'
                  ),
				   array(
                     'field'   => 'rg_lock',
                     'label'   => 'Lock',
                     'rules'   => 'required'
                  )
            );
		$this->form_validation->set_rules($config); 
		
		if ($this->form_validation->run() == TRUE)
			{
				/* Insert data */
			$user = array( 		'uid'		=>  $this->input->post('txt_uid'),
								'roleid'	=> $this->input->post('cb_role'),
								'idcab'		=> $this->input->post('cb_idcab'),
								'pass'		=> $this->fungsi->encrypt1($this->input->post('txt_pass')),
								'dispname'	=> $this->input->post('txt_dispname'),
								'email'		=> $this->input->post('txt_email'),
								'lock'		=> $this->input->post('rg_lock'),
								'crby'		=> $this->session->userdata('uid'),
								'crdate' 	=> date( 'Y-m-d'),
								'crtime' 	=> date( 'H:i:s' ),
						);
			$this->admin_model->add_user($user);
			
			// Set pesan
			$this->session->set_flashdata('message_ok', 'Data input succesfully');
			redirect('admin/admin_user');
			}
		else
			{
				$this->admin_add_user();
			}
		
	}
	
	
	/* Check user name exist */
	public function username_check($username)
	{	
		$query_username_check = $this->admin_model->search_username($username)->result();
		
		if ($this->fungsi->is_array_empty($query_username_check)==FALSE) 
		{
			$this->form_validation->set_message('username_check', '%s '.$username.' already exist, please choose another name');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
		
	}
	
	/* Display list user */
	function admin_list_user()
	{	
		//Check otorisasi
		$this->fungsi->trans_auth($this->session->userdata('view'));
		
		//Otorisasi menu
		$this->fungsi->menu_auth($this->menu_list_user);
		
		/* Setting Parameter Untuk Paging */
		$uri_segment = 4;
		$offset =    $this->uri->segment($uri_segment);
		
		 if(isset($_POST['submit']))
            {
                $data['search'] = $this->input->post('txt_search');
	                //set session user data untuk pencarian, untuk paging pencarian
	                $this->session->set_userdata('sess_search', $data['search']);
            } else {
                $data['search']  =  $this->session->userdata('sess_search');
            }
			
		$user = $this->admin_model->get_user_paging($this->config->item('paging_limit'), $offset,$data['search'])->result();
		$num_rows = $this->admin_model->count_rows_user($data['search']);
		$data['total'] = $num_rows;
		$config['base_url'] = site_url('admin/admin_user/admin_list_user/');
		if ($num_rows > 0) // Jika query menghasilkan data
				{
					// Membuat pagination			
					$config['total_rows'] = $num_rows;
					$config['per_page'] = $this->config->item('paging_limit');
					$config['uri_segment'] = $uri_segment;
					$this->pagination->initialize($config);
					$data['pagination'] = $this->pagination->create_links();
					$i = 0 + $offset;
					
					$tmpl = array( 'table_open'    => '<table border="0" cellpadding="1" cellspacing="1" id="list">',
								  'row_alt_start'  => '<tr class="zebra">',
								  'row_alt_end'    => '</tr>'
								  );
					$this->table->set_template($tmpl);
		
					// Set heading untuk tabel
					$this->table->set_empty("&nbsp;");
					$this->table->set_heading('User ID', 'Name', 'Role', 'Email', 'Lock', 'Options');
				
					foreach ($user  as $users)
					{	
			
		$this->table->add_row($users->uid, $users->dispname, $users->rolename, $users->email, $this->fungsi->convert_status($users->lock),  anchor('admin/admin_user/edit_user/'.$users->uid,'Edit',array('class' => 'update')).'  '.anchor('admin/admin_user/del_user/'.$users->uid,'Delete',array('class'=> 'delete','onclick'=>"return confirm('Delete user with ID ".$users->uid." ?')")));	
							
					}
					$data['table'] = $this->table->generate();
					
				}
			else
				{
					$data['message'] = 'No data to display';
				}		
		$data['menu_path'] = 'ADMIN > USER > LIST USER';
		//$data['link'] = array('link_back' => anchor('admin/admin_user','Back', array('class' => 'back')));	
		$data['form_action']= site_url('admin/admin_user/admin_list_user/');
		$this->load->view('admin/admin_user_list', $data);
		
	}
	
	/* Delete user */
	function del_user()
	{	
		//Check otorisasi
		$this->fungsi->trans_auth($this->session->userdata('delete'));
	
		$this->admin_model->del_user($this->uri->segment(4));
		$this->session->set_flashdata('message_ok', 'User succesfully delete');
		redirect('admin/admin_user/admin_list_user');
	}
	
	/* Edit user */
	function edit_user()
	{
		
		
		//Get data user by user id
		$query_user_edit = $this->admin_model->get_user_uid($this->uri->segment(4));
		foreach ($query_user_edit->result() as $row_user)
		{	
		$data['default']['txt_uid'] = $row_user->uid;
		$data['default']['txt_dispname'] = $row_user->dispname;
		$data['default']['cb_idcab'] = $row_user->idcab;
		$data['default']['txt_email'] = $row_user->email;
		$data['default']['txt_pass'] = $this->fungsi->decrypt1($row_user->pass);
		$data['default']['txt_pass2'] = $this->fungsi->decrypt1($row_user->pass);
		$data['default']['cb_role'] = $row_user->roleid;
		$data['default']['rg_lock'] = $row_user->lock;
		}
		$data['default']['readonly_txt_uid'] =  'readonly="readonly"';
		/* Generate combo box */
			$query_role = $this->admin_model->get_role_list();
			$data_role = $query_role->result();
			$data['role']='';
			foreach($data_role as $row)
			{
			$data['role'] .= $row->roleid == $data['default']['cb_role'] ? '<option value="'.$row->roleid.'" selected="selected">': '<option value="'.$row->roleid.'">';
			$data['role'] .= $row->rolename.' - '.$row->roledesc.'</option>';
			}	
			
			$query_cab = $this->admin_model->get_cabang_list();
			$data_cab = $query_cab->result();
			$data['cab']='';
			foreach($data_cab as $row_cab)
			{
			$data['cab'] .= $row_cab->idcab==$data['default']['cb_idcab'] ? '<option value="'.$row_cab->idcab.'" selected="selected">': '<option value="'.$row_cab->idcab.'">';
			$data['cab'] .= $row_cab->idcab.' - '.$row_cab->cabname.'</option>';
			}	
		
		$data['menu_path'] = 'ADMIN > USER > LIST USER > EDIT USER';
		$data['form_action']= site_url('admin/admin_user/update_user/'.$this->uri->segment(4));
		$data['link'] = array('link_back' => anchor('admin/admin_user/admin_list_user','Back', array('class' => 'back')));
		$this->load->view('admin/admin_user_form', $data);
		
	}
	
	/* Update user */
	function update_user()
	{	
		//Check otorisasi
		$this->fungsi->trans_auth($this->session->userdata('edit'));
		
		/* Set validasi */
		$config = array(
               array(
                     'field'   => 'txt_dispname',
                     'label'   => 'Display name',
                     'rules'   => 'required'
                  ),
				array(
                     'field'   => 'txt_pass',
                     'label'   => 'Password',
                     'rules'   => 'required|min_length[6]'
                  ),
				  array(
                     'field'   => 'txt_pass2',
                     'label'   => 'Re-type password',
                     'rules'   => 'required|min_length[6]|matches[txt_pass]'
                  ),
				  array(
                     'field'   => 'txt_email',
                     'label'   => 'Email',
                     'rules'   => 'required|valid_email'
                  ),
				   array(
                     'field'   => 'rg_lock',
                     'label'   => 'Lock',
                     'rules'   => 'required'
                  )
            );
		$this->form_validation->set_rules($config); 
		
		if ($this->form_validation->run() == TRUE)
			{
				/* Insert data */
			$user = array(      'roleid'	=> $this->input->post('cb_role'),
								'pass'		=> $this->fungsi->encrypt1($this->input->post('txt_pass')),
								'dispname'	=> $this->input->post('txt_dispname'),
								'idcab'		=> $this->input->post('cb_idcab'),
								'email'		=> $this->input->post('txt_email'),
								'lock'		=> $this->input->post('rg_lock'),
								'chby'		=> $this->session->userdata('uid'),
								'chdate' 	=> date( 'Y-m-d'),
								'chtime' 	=> date( 'H:i:s' ),
						);
			$this->admin_model->update_user($this->uri->segment(4), $user);
			
			// Set pesan
			$this->session->set_flashdata('message_ok', 'Data update succesfully');
			redirect('admin/admin_user/admin_list_user');
			}
		else
			{
				$this->edit_user();
			}
	}
}