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

class User extends MY_Controller {

	function __construct()
	{
		parent::__construct();
		date_default_timezone_set('Asia/Jakarta');
		$this->load->model('master/operator_model');
		$this->load->model('master/operator_access_model');
		$this->load->model('master/operator_type_model');
		$this->bc->set_title('User Privileges');
		$this->bc->add('Settings',base_url().'settings');
		$this->bc->add('User Privileges',base_url().'settings/user');
	}
	
	public function index()
	{
		 $default_menu_url	= 'user/main';
		 $data = array(
		 	'content' => $default_menu_url
		 );
		 $this->bc->set_title('List User');
		 $this->load->view('tpl',$data);
	}

	public function listPage()
	{
		$draw = $this->input->post('draw')?:0;
		$start = $this->input->post('start');
		$rowperpage  = $this->input->post('length')?:0;
		$columnIndex   = $_POST['order'][0]['column'];
		$columnName    = $_POST['columns'][$columnIndex]['data'];
		$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
		$searchValue = $_POST['search']['value']; // Search value
		$isActive = $this->input->post('is_active');
		
		$where = array();
		
		$where["(
			tbl.userName LIKE '%$searchValue%' 
			OR tbl.email LIKE '%$searchValue%'
			OR tbl.phone LIKE '%$searchValue%'
			OR tbl.name LIKE '%$searchValue%'
		)"] = NULL;
		
		$this->operator_model->set_where($where);
		
		$list_count = $this->operator_model->count();
		$this->operator_model->set_limit($rowperpage);
		$this->operator_model->set_offset($start);
		$this->operator_model->set_order(array($columnName=>$columnSortOrder));
		$list_data  = $this->operator_model->get_list();
		
		$response = array(
		  "post" => $this->input->post(),
		  "draw" => intval($draw),
		  "iTotalRecords" => $list_count,
		  "iTotalDisplayRecords" => $list_count,
		  "aaData" => $list_data->result_array()
		);

		header('Content-type: application/json');
		echo json_encode($response);
	}

	public function input($id=0)
	{
		$images_list = array();
		$head = $this->operator_model->get($id);
		$operator_type = $this->operator_type_model->get_list()->result_array();
		if($id)
		$images_list = getImageList($id,1);
		$sub_title = 'New Data';
		if($head['idOperator'])
		{
			$sub_title = 'Modify Data';
		}
		$data = array(
			'content' => 'user/input'
			,'head' => $head
			,'images_list' => $images_list
			,'operator_type' => $operator_type
		);
		$this->bc->add($head['userName'],base_url().'settings/user/'.$id);
		$this->load->view('tpl',$data);
	}

	public function save()
	{
		$request = getInputs();
		
		$this->db->trans_start();
		$data['idOperator'] 	= $request['t_id_operator']?:0;
		$data['email'] 			= validate_input(
			isset($request['t_email'])?$request['t_email']:''
			,array(
				'name'=>'email',
				'required'=>true,
				'type'=>'varchar',
				'maxlength'=>32
			)
		);
		$data['phone'] 			= validate_input(
			isset($request['t_phone'])?$request['t_phone']:''
			,array(
				'name'=>'phone',
				'required'=>true,
				'type'=>'varchar',
				'maxlength'=>32
			)
		);
		$pass1				 	= $request['t_password_1'];
		$pass2				 	= $request['t_password_2'];
		$oprType				= $request['t_opr_type'];
		$data['name']			= $request['name'];
		$data['userName'] 		= validate_input(
			isset($request['userName'])?$request['userName']:''
			,array(
				'name'=>'user name',
				'required'=>true,
				'type'=>'varchar',
				'maxlength'=>32
			)
		);
		$data['lastUpdate'] 	= date('Y-m-d H:i:s');
		
		if($data['idOperator'] == 0)
		{
			$check_username = $this->operator_model->get(array('userName'=>$data['userName']));
			if($check_username['idOperator']!='')
			{
				$this->error('user name sudah dipakai');
			}
			$check_email = $this->operator_model->get(array('email'=>$data['email']));
			
			if($check_email['idOperator']!='')
			{
				$this->error('email sudah dipakai');
			}
			$check_phone = $this->operator_model->get(array('phone'=>$data['phone']));
			
			if($check_phone['idOperator']!='')
			{
				$this->error('no handphone sudah dipakai');
			}
			if(!$pass1)
			{
				$this->error('password belum di isi');
			}
			$datenow = date('Y-m-d H:i:s');
			$data['expiryDate']			= date('Y-m-d',strtotime(date("Y-m-d", strtotime($datenow)) . " +20 year"));
		}

		if($pass1)
		{
			if($pass1!=$pass2)
			{
				$this->error('password yang dimasukan tidak sama');
			}
			$data['passWord'] 	= md5($pass1);
		}
		
		if($oprType)
		{
			$data['fidOperatorType']	= $oprType;
			if($data['idOperator'] == $this->session->userdata('idOperator'))
			{
				$newdata['fidOperatorType'] = $oprType;
				$this->session->set_userdata($newdata);	 
			}
		}
		$new_id = $data['idOperator'];
		$defaultMenu 	= $this->input->post('defaultMenu');
		if($defaultMenu)
		{
			$data['fidMenu'] = substr($defaultMenu[0]['id'], strpos($defaultMenu[0]['id'], "_") + 1);
		}
		if($data['idOperator'] == 0)
		{
			$new_id = $this->operator_model->saveTo($data);
		} else{
			$this->operator_model->save($data);
			
			// begin save menu access
			
			$this->db->delete('msOperatorAccess', array('fidOperator' => $data['idOperator']));
			$selectedMenu = $this->input->post('selectedMenu');
			$selectedMenuParent = $this->input->post('selectedMenuParent');
			if(is_array($selectedMenuParent))
			{
				foreach($selectedMenuParent as $row)
				{
					foreach($row as $selectedMenuParentChild)
					{
						$str = str_replace('#','',$selectedMenuParentChild);
						if($str)
						$selectedMenu[] = $str;
					}
				}
				$selectedMenu = array_unique($selectedMenu);
				$operator_access = array();
				
				foreach($selectedMenu as $row)
				{
					$idMenu = substr($row, strpos($row, "_") + 1);
					$operator_access[] = array('fidOperator'=>$data['idOperator'],'fidMenu'=>$idMenu);
				}
				// echo $this->db->last_query();
				$this->db->insert_batch('msOperatorAccess', $operator_access);
			}
			// end save menu access
			// cek privileg akses default
			if (isset($data['fidMenu']))
			{
				$get_priv_access = $this->operator_access_model->get(array('fidOperator'=>$data['idOperator'],'fidMenu'=>$data['fidMenu']));
				if($get_priv_access['idOperatorAccess']=='')
				$this->error('User tidak memiliki Privilege ke Default Menu Access yang dipilih');
			}
		}
		
		$this->result['idOperator'] = $new_id;

		if ($this->db->trans_status() === false) {
			$this->db->trans_rollback();
			$error = $this->db->error();
			$this->error($error);
		} else {
			$this->db->trans_commit();
			$this->success('Data berhasil di simpan');
		}
	}

	public function deleteUser()
	{
		$idOperator		= validate_input(
			$this->input->post('idOperator')
			,array(
				'name'=>'Operator',
				'required'=>true,
				'type'=>'int',
				'maxlength'=>32
			)
		);
		
		$this->db->trans_start();

		$this->db->delete('msOperator', array('idOperator' => $idOperator));
		$this->db->delete('msOperatorAccess', array('fidOperator' => $idOperator));
		
		$this->db->trans_complete();

		if ($this->db->trans_status() === false) {
			$this->db->trans_rollback();
			$error = $this->db->error();
			$this->error($error);
		} else {
			$this->db->trans_commit();
			$this->success('Data berhasil di hapus');
		}
	}
}