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

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

class Admin_role 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
	 */
	function __construct()
	{
		parent::__construct();
		$this->load->model('admin/admin_model', '', TRUE);
		$this->fungsi->check_login();
		$this->fungsi->sess_search_segment();
	}
	
	//Menu ID utk keperluan otorisasi
	var $menu_list_role  = 12;
	var $menu_add_role = 11;
	
	public function index()
	{	
		$this->admin_add_role();
	}
	
	/* Form add role */
	function admin_add_role()
	{	
		//Otorisasi menu
		$this->fungsi->menu_auth($this->menu_add_role);
		
		$data_menu1 = array();
		//$data_menu2 = array();
		$query_menu = $this->admin_model->get_menu_all()->result();	
		
		foreach($query_menu as $row): 
					$data_menu1[$row->pid][] = $row;
					//$data_menu2[] = $row->murl;
		endforeach; 
				
		$data['menu'] =  '<ul id="tree1">'; 
		$data['menu'] .=   $this->fungsi->menu_widget_role($data_menu1,0); 
		
		$data['menu_path'] = 'ADMIN > ROLE > ADD ROLE';
		$data['form_action']= site_url('admin/admin_role/add_role');
		$data['add_customer_disabled']='disabled="disabled"';
		//$data['table_rolecust']=$this->get_rolecust();
		//$data['link'] = array('link_back' => anchor('admin/admin_role','Back', array('class' => 'back')));
		$this->load->view('admin/admin_role_form', $data);
		
	}
	
	/* Add role */
	function add_role()
	{	
	
		//Check otorisasi
		$this->fungsi->trans_auth($this->session->userdata('add'));
		
		$config = array(
                array(
											 'field'   => 'txt_rname',
											 'label'   => 'Role name',
											 'rules'   => 'required|callback_rolename_check'
										  ),
									   array(
											 'field'   => 'txt_rdesc',
											 'label'   => 'Role description',
											 'rules'   => 'required'
										  ),
										array(
											 'field'   => 'chk_view',
											 'label'   => 'Transaction auth',
											 'rules'   => 'callback_auth_form_check'
										  ),
										 array(
											 'field'   => 'chk_add',
											 'label'   => 'Transaction auth',
											 'rules'   => 'callback_auth_form_check'
										  ),
										   array(
											 'field'   => 'chk_delete',
											 'label'   => 'Transaction auth',
											 'rules'   => 'callback_auth_form_check'
										  ),
										  array(
											 'field'   => 'chk_app',
											 'label'   => 'Transaction auth',
											 'rules'   => 'callback_auth_form_check'
										  ),
										  array(
											 'field'   => 'chk_update',
											 'label'   => 'Transaction auth',
											 'rules'   => 'callback_auth_form_check'
										  ),
										  array(
											 'field'   => 'chk_cancel',
											 'label'   => 'Transaction auth',
											 'rules'   => 'callback_auth_form_check'
										  ),
										   array(
											 'field'   => 'chk_menu[]',
											 'label'   => 'Menu auth',
											 'rules'   => 'required'
										  )
            );
			
			$this->form_validation->set_rules($config); 
			
		if ($this->form_validation->run() == TRUE)
			{
				//print_r($this->input->post('chk_menu'));
				/* Insert data */
			$role = array( 		'rolename'		=>  $this->input->post('txt_rname'),
								'roledesc'		=> $this->input->post('txt_rdesc'),
								'view'			=> $this->input->post('chk_view'),
								'add'			=> $this->input->post('chk_add'),
								'edit'			=> $this->input->post('chk_update'),
								'delete'		=> $this->input->post('chk_delete'),
								'app'			=> $this->input->post('chk_app'),
								'cancel'			=> $this->input->post('chk_cancel'),
								'crby'			=> $this->session->userdata('uid'),
								'crdate' 		=> date( 'Y-m-d'),
								'crtime' 		=> date( 'H:i:s' ),
						);
			 
			
			//Get last roleid
			$query_roleid =  $this->fungsi->get_last_id('master_role')->result();	
			//print_r($query_roleid);
			foreach($query_roleid as $row_roleid);
			$last_roleid = $row_roleid->Auto_increment;
			
			//echo $last_roleid;
			
			$role_menu = array();
			foreach($this->input->post('chk_menu') as $menu)
			{
				$role_menu[] = array( 	'roleid'		=>  $last_roleid,
										'mid'			=> 	$menu,
										'crby'			=> $this->session->userdata('uid'),
										'crdate' 		=> date( 'Y-m-d'),
										'crtime' 		=> date( 'H:i:s' ),
						);
			}
			//print_r($role_menu);
			
			//Utk transaksi multiple gunakan fungsi transaction
			$this->db->trans_begin();
				
				$this->admin_model->add_role($role);
				$this->admin_model->add_rolemenu_batch($role_menu);
				
			$this->db->trans_complete(); 
			
			if ($this->db->trans_status() === FALSE)
				{
					$this->session->set_flashdata('message_err', 'Data input error');	
					$this->db->trans_rollback();
				} 
			else
				{
					$this->session->set_flashdata('message_ok', 'Data input succesfully');
					 $this->db->trans_commit();
				}
			
				redirect('admin/admin_role/admin_add_role');
			}
		else
			{
				$this->admin_add_role();
			}
	}
	
	/* Form auth check */
	public function auth_form_check()
	{
		if ($this->input->post('chk_view')=='' && $this->input->post('chk_add')=='' 
		&& $this->input->post('chk_update')=='' && $this->input->post('chk_delete')=='' && $this->input->post('chk_app')=='' && $this->input->post('chk_cancel')=='') 
		{
			$this->form_validation->set_message('auth_form_check', 'The %s field can not be empty');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
		
	}
	
	/* Display list role */
	function admin_list_role()
	{	
	
		//Otorisasi menu
		$this->fungsi->menu_auth($this->menu_list_role);
		
		//Check otorisasi
		$this->fungsi->trans_auth($this->session->userdata('view'));
		
		 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');
            }
			
		/* Setting Parameter Untuk Paging */
		$uri_segment = 4;
		$offset =    $this->uri->segment($uri_segment);
		$role = $this->admin_model->get_role_paging($this->config->item('paging_limit'), $offset, $data['search'])->result();
		$num_rows = $this->admin_model->count_rows_role($data['search']);
		$data['total'] = $num_rows;
		$config['base_url'] = site_url('admin/admin_role/admin_list_role/');
		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('Role ID', 'Name', 'Description', 'View', 'Add', 'Delete', 'Update', 'Approval', 'Cancel', 'Options');
				
					foreach ($role  as $roles)
					{	
					
		$this->table->add_row($roles->roleid, $roles->rolename, $roles->roledesc, $this->fungsi->convert_status($roles->view),  $this->fungsi->convert_status($roles->add),  $this->fungsi->convert_status($roles->delete),  $this->fungsi->convert_status($roles->edit),  $this->fungsi->convert_status($roles->app), $this->fungsi->convert_status($roles->cancel), anchor('admin/admin_role/edit_role/'.$roles->roleid,'Edit',array('class' => 'update')).'  '.
												anchor('admin/admin_role/del_role/'.$roles->roleid,'Delete',array('class'=> 'delete','onclick'=>"return confirm('Delete role with ID ".$roles->roleid." ?')")).'  '.
												anchor('admin/admin_role/copy_role/'.$roles->roleid,'Copy',array('class'=> 'copy')) );	
							
					}
					$data['table'] = $this->table->generate();
					
				}
			else
				{
					$data['message'] = 'No data to display';
				}		
		$data['menu_path'] = 'ADMIN > ROLE > LIST ROLE';
		//$data['link'] = array('link_back' => anchor('admin/admin_role','Back', array('class' => 'back')));	
		$data['form_action']= site_url('admin/admin_role/admin_list_role/');
		$this->load->view('admin/admin_role_list', $data);
		
	}
		
	/* Delete role */
	function del_role()
	{	
		//Check otorisasi
		$this->fungsi->trans_auth($this->session->userdata('delete'));
		
		$this->admin_model->del_role($this->uri->segment(4));
		$this->session->set_flashdata('message_ok', 'Role succesfully delete');
		redirect('admin/admin_role/admin_list_role');
	}
	/* Edit role */
	function edit_role()
	{
		$data_menu1 = array();
		$query_menu = $this->admin_model->get_menu_all()->result();	
	
		foreach($query_menu as $row): 
					$data_menu1[$row->pid][] = $row;
		endforeach; 
		
		$tmp = array();
		
		$query_rolemenu = $this->admin_model->get_rolemenu_roleid($this->uri->segment(4))->result();
		
		foreach($query_rolemenu as $row_rolemenu)
		{	
			
			$tmp[] = $row_rolemenu->mid;
		}
		
		$data['menu'] =  '<ul id="tree1">'; 	
		$data['menu'] .=   $this->fungsi->menu_widget_role_edit($data_menu1, 0 ,$tmp); 
		
		$query_role = $this->admin_model->get_role_roleid($this->uri->segment(4))->result();
		foreach($query_role as $row_role);
		
		$data['default']['txt_rname']  =  $row_role->rolename;
		$data['default']['txt_rdesc']  =  $row_role->roledesc;
		$data['default']['chk_view']   =  $row_role->view;
		$data['default']['chk_add']	   =  $row_role->add;
		$data['default']['chk_delete'] =  $row_role->delete;
		$data['default']['chk_update'] =  $row_role->edit;
		$data['default']['chk_app']	   =  $row_role->app;
		$data['default']['chk_cancel'] =  $row_role->cancel;
		
		$data['default']['readonly_txt_rname'] =  '';
		
		$data['menu_path'] = 'ADMIN > ROLE > LIST ROLE > EDIT ROLE';
		$data['form_action']= site_url('admin/admin_role/update_role/'.$this->uri->segment(4));
		$data['link'] = array('link_back' => anchor('admin/admin_role/admin_list_role','Back', array('class' => 'back')));
		$data['add_customer_disabled']='';
		//$data['table_rolecust']=$this->get_rolecust();
		$this->load->view('admin/admin_role_form', $data);
	}
	
	/* Update role */
	function update_role()
	{	
	
		//Check otorisasi
		$this->fungsi->trans_auth($this->session->userdata('edit'));
		
		$config = array(			   
										array(
											 'field'   => 'txt_rname',
											 'label'   => 'Role name',
											 'rules'   => 'required'
										  ),
									   array(
											 'field'   => 'txt_rdesc',
											 'label'   => 'Role description',
											 'rules'   => 'required'
										  ),
										array(
											 'field'   => 'chk_view',
											 'label'   => 'Authorization',
											 'rules'   => 'callback_auth_form_check'
										  ),
										 array(
											 'field'   => 'chk_add',
											 'label'   => 'Authorization',
											 'rules'   => 'callback_auth_form_check'
										  ),
										   array(
											 'field'   => 'chk_delete',
											 'label'   => 'Authorization',
											 'rules'   => 'callback_auth_form_check'
										  ),
										  array(
											 'field'   => 'chk_app',
											 'label'   => 'Authorization',
											 'rules'   => 'callback_auth_form_check'
										  ),
										  array(
											 'field'   => 'chk_update',
											 'label'   => 'Authorization',
											 'rules'   => 'callback_auth_form_check'
										  ),
										   array(
											 'field'   => 'chk_cancel',
											 'label'   => 'Authorization',
											 'rules'   => 'callback_auth_form_check'
										  ),
										   array(
											 'field'   => 'chk_menu[]',
											 'label'   => 'Menu',
											 'rules'   => 'required'
										  )
            );
			
			$this->form_validation->set_rules($config); 
			
		if ($this->form_validation->run() == TRUE)
			{
				$role = array( 		
									'rolename'		=> $this->input->post('txt_rname'),	
									'roledesc'		=> $this->input->post('txt_rdesc'),
									'view'			=> $this->input->post('chk_view'),
									'add'			=> $this->input->post('chk_add'),
									'edit'			=> $this->input->post('chk_update'),
									'delete'		=> $this->input->post('chk_delete'),
									'app'			=> $this->input->post('chk_app'),
									'cancel'		=> $this->input->post('chk_cancel'),
									'crby'			=> $this->session->userdata('uid'),
									'crdate' 		=> date( 'Y-m-d'),
									'crtime' 		=> date( 'H:i:s' ),
						);
						
		
		foreach($this->input->post('chk_menu') as $menu)
		{
				$role_menu[] = array( 	'roleid'		=>  $this->uri->segment(4),
										'mid'			=> 	$menu,
										'crby'			=> $this->session->userdata('uid'),
										'crdate' 		=> date( 'Y-m-d'),
										'crtime' 		=> date( 'H:i:s' ),
						);
		}	
			//Utk transaksi multiple gunakan fungsi transaction
			$this->db->trans_begin();
			
				$this->admin_model->del_role_menu($this->uri->segment(4));
				$this->admin_model->update_role($this->uri->segment(4), $role);
				$this->admin_model->add_rolemenu_batch($role_menu);
				
			$this->db->trans_complete(); 
			
			if ($this->db->trans_status() === FALSE)
				{
					$this->session->set_flashdata('message_err', 'Data input error');	
					$this->db->trans_rollback();
				} 
			else
				{
					$this->session->set_flashdata('message_ok', 'Data update succesfully');
					 $this->db->trans_commit();
				}
			
				redirect('admin/admin_role/admin_list_role');
			}
			
		else
			{
				$this->edit_role();
			}
	
	}
	
	/* Check role name exist */
	public function rolename_check($rolename)
	{	
		$query_rolename_check = $this->admin_model->search_rolename($rolename)->result();
		
		if ($this->fungsi->is_array_empty($query_rolename_check)==FALSE) 
		{
			$this->form_validation->set_message('rolename_check', '%s '.$rolename.' already exist, please choose another name');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
		
	}
	
	
	/* Search SAP customer code / name */
	/*function search_sap_cust()
	{	
		
			$sap = new SAPConnection();
			$sap->Connect($this->fungsi->sap_connection_string());
			if ($sap->GetStatus() == SAPRFC_OK ) $sap->Open ();
			if ($sap->GetStatus() != SAPRFC_OK ) {
		   	$sap->PrintStatus();
		   	exit;
			}
			
		 	$fce = &$sap->NewFunction ("YFM_DISPCUST_NCR");
			if ($fce == false ) {
		   $sap->PrintStatus();
		   exit;
		   }
		   
		  		if( $this->uri->segment(4)=='kunnr' )
				{
					$fce->GV_KUNNR = '*'.strtoupper($_GET['term']).'*';
				}
				else
				{
					$fce->GV_NAME1 = '*'.strtoupper($_GET['term']).'*';
					
				}
				$fce->Call();
	
	$return_arr = array();
	
	 if ($fce->GetStatus() == SAPRFC_OK) {
		 
		  $fce->GI_HEADER->Reset();
		  while ($fce->GI_HEADER->Next())
				{
					if( $this->uri->segment(4)=='kunnr' )
						{
							 $row_array['label'] = $this->fungsi->fm_delete_zero_value($fce->GI_HEADER->row["KUNNR"]);
					 		 $row_array['value'] = $this->fungsi->fm_delete_zero_value($fce->GI_HEADER->row["KUNNR"]);
			 				 $row_array['txt_custname']  = $fce->GI_HEADER->row["NAME1"];	
						}
					else
						{
							$row_array['label'] = $fce->GI_HEADER->row["NAME1"];
					 		$row_array['value'] = $fce->GI_HEADER->row["NAME1"];
			 		 		$row_array['txt_custid']  = $this->fungsi->fm_delete_zero_value($fce->GI_HEADER->row["KUNNR"]);
						}
					
					 
					  array_push($return_arr,$row_array);
				}
				
			echo json_encode($return_arr);
		 
	 }
	 else
	 {
		 $fce->PrintStatus();
	 	 $sap->Close();  
	 }
	 
	 
		
	}*/
	
	
	/*function add_cust_auth()
	{
		
		if($this->input->post('txt_custid')== '' || $this->input->post('txt_custname')== '')
		{	
			$message = 'Field cannot be empty';
      		$class = "error";
			//$output = '{ "message": "'.$message.'", "bg_color": "'.$bg_color.'" }';
    		
		}
		else
		{	
			if ($this->rolecust_exist($this->uri->segment(4), $this->input->post('txt_custid'))==TRUE)
			{
				
				$rolecust = array(  'roleid'	=> $this->uri->segment(4),
									'kunnr'		=> $this->input->post('txt_custid'),
									'name1'		=> $this->input->post('txt_custname'),
									'crby'		=> $this->session->userdata('uid'),
									'crdate' 	=> date( 'Y-m-d'),
									'crtime' 	=> date( 'H:i:s' ),
							);
				$this->admin_model->add_rolecust($rolecust);
				
				$message = 'Data successfully input';
				$class = "success";
			//$output = '{ "message": "'.$message.'", "bg_color": "'.$bg_color.'" }';
			}
			else
			{
				$message = 'Role with ID '.$this->uri->segment(4).' already have customer with number '. $this->input->post('txt_custid').' please choose others';
      			$class = "error";
			}
		}
		
		$output = '{ "message": "'.$message.'", "class": "'.$class.'" }';	
		echo $output;
	}*/
	
	
	/* Check role cust exist */
	public function rolecust_exist($roleid, $kunnr)
	{	
		$query_rolecust_check = $this->admin_model->search_rolecust($roleid, $kunnr)->result();
		
		if ($this->fungsi->is_array_empty($query_rolecust_check)==FALSE) 
		{
			return FALSE;
		}
		else
		{
			return TRUE;
		}
		
	}
	
	/* Get role cust */
	/*public function get_rolecust()
	{
		
		$role_cust = $this->admin_model->get_rolecust($this->uri->segment(4))->result();
		$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('Role ID', 'Cust. No', 'Name','Options');
				
					foreach ($role_cust  as $role_custs)
					{	
					
		$this->table->add_row($role_custs->roleid, $role_custs->kunnr, $role_custs->name1,'<a href="#" class="delete" onclick="return del_rolecust('.'\''.$role_custs->roleid.'\','.'\''.$role_custs->kunnr.'\')">Delete</a>');	
							
					}
		//$data['table_rolecust'] = $this->table->generate();
		$table_rolecust =  $this->table->generate();
		
		return $table_rolecust;
	
	}
	
	function del_rolecust()
	{
		$this->admin_model->del_rolecust($this->uri->segment(4),$this->uri->segment(5));
		$message = 'Data already deleted';
      	$class = "success";
		$output = '{ "message": "'.$message.'", "class": "'.$class.'" }';	
		echo $output;
		//$this->session->set_flashdata('message_ok', 'Role succesfully delete');
		//redirect('admin/admin_role/admin_list_role');
		
	}*/
	
	/* Copy role */
	function copy_role()
	{
		//Copy role master
		$query_role = $this->admin_model->get_role_roleid($this->uri->segment(4))->result();
		foreach($query_role as $row_role);
		
		$role_master = array( 	'rolename'	    =>  $row_role->rolename.'-COPY',
									'roledesc'		=> 	$row_role->roledesc,
									'view'			=> 	$row_role->view,
									'add'			=> 	$row_role->add,
									'delete'		=> 	$row_role->delete,
									'app'			=> 	$row_role->app,
									'cancel'		=> 	$row_role->cancel,
							    	'crby'			=>  $this->session->userdata('uid'),
									'crdate' 		=>  date( 'Y-m-d'),
									'crtime' 		=>  date( 'H:i:s' ),
						);
						
		
		$this->admin_model->add_role($role_master);
		
		//Get last role number
		$this->admin_model->get_last_role();
		$query_last_role = $this->admin_model->get_last_role()->result();
		foreach($query_last_role as $row_last_role);
		
		//echo $row_last_role->roleid;
					
	 	//Copy role menu
		$query_rolemenu = $this->admin_model->get_rolemenu_roleid($this->uri->segment(4))->result();
		foreach($query_rolemenu as $row_rolemenu)
		{	
			
			$role_menu[] = array( 	'roleid'	    => 	$row_last_role->roleid,
								    'mid'			=> 	$row_rolemenu->mid,
									'crby'			=>  $this->session->userdata('uid'),
									'crdate' 		=>  date( 'Y-m-d'),
									'crtime' 		=>  date( 'H:i:s' ),
						);
		}
		
		//Copy role customer
		/*$role_cust = $this->admin_model->get_rolecust($this->uri->segment(4))->result();
		foreach ($role_cust  as $role_custs)
				{	
					
					$role_custdata[] = array( 	
										'roleid'	    =>  $row_last_role->roleid,
										'kunnr'			=> 	$role_custs->kunnr,
										'name1'			=> 	$role_custs->name1,
										'crby'			=>  $this->session->userdata('uid'),
										'crdate' 		=>  date( 'Y-m-d'),
										'crtime' 		=>  date( 'H:i:s' ),
									);
					
				}*/
				
			
		//Utk transaksi multiple gunakan fungsi transaction
			$this->db->trans_begin();
			
				$this->admin_model->add_rolemenu_batch($role_menu);
				//$this->admin_model->add_rolecust_batch($role_custdata);
				
			$this->db->trans_complete(); 
			
			if ($this->db->trans_status() === FALSE)
				{
					$this->session->set_flashdata('message_err', 'Copy data error');	
					$this->db->trans_rollback();
				} 
			else
				{
					$this->session->set_flashdata('message_ok', 'Copy data succesfully');
					 $this->db->trans_commit();
				}
			
				redirect('admin/admin_role/edit_role/'.$row_last_role->roleid);
				
				
				
	}
	
}