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

class Account extends CI_Controller 
{	
	public function __construct() {
		parent::__construct();
		$this->load->model('Admin_m');
		$this->load->model('Content_m');
		$this->load->model('M_home');
		$this->load->model('M_function');
	}

	public function index()
	{
		if($this->session->userdata('logged_in') == TRUE) {
			if (in_array(1, $this->session->userdata('id_global_hakakses')) || in_array(2, $this->session->userdata('id_global_hakakses'))) {	
					redirect('/front_office/reg_dir/registrasi');
			}
			else if(in_array(7, $this->session->userdata('id_global_hakakses'))) {
				redirect('/apotek/dashboard');
			}
			else if(in_array(8, $this->session->userdata('id_global_hakakses'))) {
				redirect('/front_office/ugd_dir/ugd/laboratorium');
			} else {
				
				redirect('/front_office/dashboard');
			}
		} else {
			$this->load->view('login');
		}	

	}

	public function change_password($dari)
	{
		$userid = $this->session->userdata('userid');

		if($dari == 'mahasiswa') {
			$this->edit_mahasiswa($userid);
		}
		if($dari == 'dosen') {
			$this->edit_dosen($userid);
		}
		if($dari == 'front_office') {
			$this->edit_front_office($userid);
		}
	}

	public function edit_mahasiswa($id_user)
	{
		$data['judul']='Ubah Sandi';
		$data['desc_judul']='mohon di ingat kata sandi anda. dikarenakan semua proses akademik akan di lakukan pada sistem ini';
		$data['page']='change_password';
		$data['jenis_page']="mahasiswa/";
		$data['controller']='dashboard';
		$data['active']='dashboard';

		$data['breadcumb'][]=array('icon'=>'lock',
															 'link'=>'',
															 'judul'=>'Ubah Password');

		$data['row'] = $this->Content_m->select_db('pddikti_tr_mahasiswa_pt','id_reg_pd',$id_user)->row();
		$data['nm_pd'] = $this->Content_m->select_db('pddikti_tr_mahasiswa','id_pd',$data['row']->id_pd)->row()->nm_pd;

		$this->load->view('template',$data);
	}


	public function edit_dosen($id_user)
	{
		$data['judul']='Ubah Sandi';
		$data['desc_judul']='mohon di ingat kata sandi anda. dikarenakan semua proses akademik akan di lakukan pada sistem ini';
		$data['page']='change_password';
		$data['jenis_page']="dosen/";
		$data['controller']='dashboard';
		$data['active']='dashboard';

		$data['breadcumb'][]=array('icon'=>'lock',
																'link'=>'',
																'judul'=>'Ubah Password');		
	
		$data['row'] = $this->Content_m->select_db('pddikti_tr_dosen','id_sdm',$id_user)->row();
							
		$this->load->view('template',$data);
	}

	

	public function update_password()
	{
		extract($_POST);				
		if(isset($_POST))
		{
			if($password == '' && $confirm_password == '')
			{
				redirect('/account/change_password/'.$dari.'/'.$this->session->userdata('userid'));
			}
			else
			{
				$cek=$this->M_home->cek_username($username);
				if($cek->num_rows()==0)
				{
					if($confirm_password == $password)
					{
						if(isset($password) && $password != ''){
							$data2=array(
								'username'=>$username,
								'password'=>md5($password),
							);
							$this->session->set_flashdata('sukses',TRUE);
							$this->M_function->update_db('global_user', 'id_user', $id_reg_pd, $data2);
							redirect('/account/change_password/'.$dari.'/'.$this->session->userdata('userid'));
						}	
					}
					else
					{
						$this->session->set_flashdata('pass_tidak_sama',TRUE);
						redirect('/account/change_password/'.$dari.'/'.$this->session->userdata('userid'));
					}

				}
				else if($cek->num_rows()==1)
				{
					$get_username_id_user = $this->Content_m->get_row_custom('global_user','username', $username)->id_user;
					if($get_username_id_user == $id_reg_pd)
					{
						if($confirm_password == $password)
						{
							if(isset($password) && $password != ''){
								$data2=array(
									'username'=>$username,
									'password'=>md5($password),
								);
								$this->M_function->update_db('global_user', 'id_user', $id_reg_pd, $data2);
								$this->session->set_flashdata('sukses',TRUE);
								redirect('/account/change_password/'.$dari.'/'.$this->session->userdata('userid'));
							}
							else
							{
								$this->session->set_flashdata('pass_tidak_boleh_kosong',TRUE);
								redirect('/account/change_password/'.$dari.'/'.$this->session->userdata('userid'));
							}	
						}
						else
						{
							$this->session->set_flashdata('pass_tidak_sama',TRUE);
							redirect('/account/change_password/'.$dari.'/'.$this->session->userdata('userid'));
						}
					}
					else
					{
						$this->session->set_flashdata('username_sudah_ada',TRUE);
						redirect('/account/change_password/'.$dari.'/'.$this->session->userdata('userid'));
					}
				}
				else{
					$this->session->set_flashdata('username_sudah_ada',TRUE);
					redirect('/account/change_password/'.$dari.'/'.$this->session->userdata('userid'));
				}
			}			
		}
		else{ 
			$this->session->set_flashdata('error',TRUE);
			redirect('/account/change_password/'.$dari.'/'.$this->session->userdata('userid'));
		}	
	}


	public function authentication()
	{
		extract($_POST);

		$model = $this->Admin_m->cek_login($username,md5($password));

		if(!$model)
		{
			$this->session->set_flashdata('login_error',TRUE);
			$this->load->view('login');
		}
		else
		{
			$get= $this->Content_m->get_row_custom('global_user','username', $username);
			$nama="";
			$id_cabang = 0;
			$cek_employee_non_dosen = $this->Content_m->exists('bbmc_re_staff','id_re_staff', $get->id_user);
			if($cek_employee_non_dosen == 1) {
				$c = $this->Content_m->get_row_custom('bbmc_re_staff','id_re_staff', $get->id_user);
				$nama = $c->nama_staff;
				$id_jabatan = $c->id_jabatan;
				$id_unit = $c->id_unit;
			} else {
				$nama = "User Uncategorized";
				$id_jabatan = "0";
			}

			//GET ALL ID_GLOBAL_HAK_AKSES 
			$arr_id_global_hakakses = array();
			$arr_id_sp = array();
			$arr_id_sms = array();
			foreach ($this->Content_m->select_db('global_user_hakakses_bbmc','id_user',$get->id_user)->result() as $key) {
				array_push($arr_id_global_hakakses, $key->id_hakakses);
			}
			
			$main_session =  array(
				'logged_in' => TRUE , 
				'userid' => $get->id_user ,
				'name' => $nama ,
				'id_jabatan' => $id_jabatan,
				'id_unit'=> $id_unit,
				'id_global_hakakses' => $arr_id_global_hakakses,
			);
			//echo "<pre>";
			//echo print_r($main_session);
			$this->session->set_userdata($main_session);	
			if (in_array(1, $arr_id_global_hakakses) || in_array(2, $arr_id_global_hakakses)) {	
				redirect('/front_office/reg_dir/registrasi');
			}
			else if(in_array(7, $arr_id_global_hakakses)){
				redirect('/apotek/dashboard');
			}
			else if(in_array(8, $arr_id_global_hakakses)){
				redirect('/front_office/ugd_dir/ugd/laboratorium');
			}
			else{
				redirect('/front_office/dashboard');
			}
		}
	}

	public function log_update()
	{
		$this->load->view('log_update');	
	}

	public function logout()
	{
		$this->session->sess_destroy();
		redirect('');
	}

	public function proses_upload()
	{
		extract($_POST);

		$this->load->helper(array('form', 'url'));
	  $this->load->library('upload');
		$config['upload_path'] = getcwd().'/media/images/foto/'; //path folder
		$config['allowed_types'] = 'jpg|jpeg';
		$config['overwrite'] = TRUE;
		$config['file_name'] = $id_reg_pd;
		$berita_acara = "";
		$this->upload->initialize($config);       

		if(!empty($_FILES['userfile_beritaacara']['name'])){
			if ($this->upload->do_upload('userfile_beritaacara')){
				$berita_acara = $_FILES['userfile_beritaacara']['name'];
				//echo $_FILES['userfile_beritaacara']['name'];
				$a = $this->upload->data();
				$file_data=$id_reg_pd.$a['file_ext'];
				$new_name_by_you=$id_reg_pd.'.jpg';
				$new_path=$a['file_path'].$new_name_by_you;
				rename($a['full_path'],  $new_path);
				redirect($_SERVER['HTTP_REFERER'],'refresh');
			} else {		
				echo "<center>".$this->upload->display_errors()."<br><br><a href=".$_SERVER['HTTP_REFERER'].">Back</a></center>";
			}
		}
	}

	public function proses_upload_ktp()
	{
		extract($_POST);

		$this->load->helper(array('form', 'url'));
	  $this->load->library('upload');
		$config['upload_path'] = getcwd().'/media/images/ktp/'; //path folder
		$config['allowed_types'] = 'gif|jpg|png|jpeg';
		$config['overwrite'] = TRUE;
		$config['file_name'] = $id_reg_pd;
		$berita_acara = "";
		$this->upload->initialize($config);
		if(!empty($_FILES['userfile_beritaacara']['name'])) {
				if ($this->upload->do_upload('userfile_beritaacara')) {
					$berita_acara = $_FILES['userfile_beritaacara']['name'];
					redirect($_SERVER['HTTP_REFERER'],'refresh');
				} else {
					echo "<center>".$this->upload->display_errors()."<br><br><a href=".$_SERVER['HTTP_REFERER'].">Back</a></center>"; 	
				}
		}      
	}


	public function edit_front_office_proses()
	{
		extract($_POST);			
		if(isset($_POST))
		{
			$data=array(
				'nm_sdm'=>$nm_sdm,
				'id_cabang'=>$id_cabang
			);		
			$this->M_function->update_db('global_employee_non_dosen', 'id_sdm', $id_sdm, $data);
			if($password == '' && $confirm_password == '')
			{
				redirect($_SERVER['HTTP_REFERER'],'refresh');
			}
			else
			{
				$cek=$this->M_home->cek_username($username);
				if($cek->num_rows()==0)
				{
					if($confirm_password == $password)
					{
						if(isset($password) && $password != ''){
							$data2=array(
								'username'=>$username,
								'password'=>md5($password),
							);
							$this->M_function->update_db('global_user', 'id_user', $id_sdm, $data2);
							redirect($_SERVER['HTTP_REFERER'],'refresh');
						}	
					}
					else
					{
						$this->session->set_flashdata('pass_tidak_sama',TRUE);
						redirect($_SERVER['HTTP_REFERER'],'refresh');
					}
				}
				else if($cek->num_rows()==1)
				{
					$get_username_id_user = $this->Content_m->get_row_custom('global_user','username', $username)->id_user;
					if($get_username_id_user == $id_sdm)
					{
						if($confirm_password == $password)
						{
							if(isset($password) && $password != ''){
								$data2=array(
									'username'=>$username,
									'password'=>md5($password),
								);
								$this->M_function->update_db('global_user', 'id_user', $id_sdm, $data2);
								$this->session->set_flashdata('sukses',TRUE);
								redirect($_SERVER['HTTP_REFERER'],'refresh');
							}
							else
							{
								$this->session->set_flashdata('pass_tidak_boleh_kosong',TRUE);
								redirect($_SERVER['HTTP_REFERER'],'refresh');
							}	
						}
						else
						{
							$this->session->set_flashdata('pass_tidak_sama',TRUE);
							redirect($_SERVER['HTTP_REFERER'],'refresh');
						}
					}
					else
					{
						$this->session->set_flashdata('username_sudah_ada',TRUE);
						redirect($_SERVER['HTTP_REFERER'],'refresh');
					}
				}
				else{
					$this->session->set_flashdata('username_sudah_ada',TRUE);
					redirect($_SERVER['HTTP_REFERER'],'refresh');
				}
			}		
		}
		else{
			$this->session->set_flashdata('error',TRUE);
			redirect($_SERVER['HTTP_REFERER'],'refresh');
		}
		//echo $this->db->last_query();	
	}

	public function data_diri($dari)
	{
		$id = $this->session->userdata('userid');
		$data['active'] = '';
		$data['controller']='data_diri';
		if($dari == 'front_office') {
			$data['staff']=$this->db->get_where('global_employee_non_dosen',array('id_sdm'=>$id))->row();
			$aaa = $data['staff'];
			$data['active']='data_diri';
		
		}
		if($dari == 'apotek') {
			$dsn = $this->db->get_where('pddikti_tr_dosen',array('id_sdm'=>$id));
			if($dsn->num_rows() > 0){
				$data['dosen']=$dsn->row();
				$aaa = $data['dosen'];
				$data['active']='data_diri';
			}
			else
			{
				$aaa = "";
				echo "<center>Hubungi admin dikarenakan data anda tidak valid</center>";
			}
			
		}
		$this->db->select('deskripsi_pengalaman');
		$this->db->from('siakad_tr_pengalaman_kerja');
		$this->db->where('id_sdm', $id);
		$q = $this->db->get();
		$data['pengalaman_kerja']=$q;

		if($aaa && $data['pengalaman_kerja'])
		{
			$data['judul']='Edit Data '.$dari;
			$data['desc_judul']='Mengubah Data '.$dari;

			if($dari == 'apotek') {
				$data['jenis_page']="dosen/";
				$data['page']='dosen_area/data_diri';
			}
			if($dari == 'front_office') {
				$data['jenis_page']="front_office/";
				$data['controller_dir']='account';
				$data['controller']='staff';
				$data['parent_controller']='';
				$data['page']='staff/edit';
			}	        
			$data['dari']=$dari;    
			$data['breadcumb'][]=array('icon'=>'user-secret',
											'link'=>site_url('front_office/dosen_dir/dosen'),
											'judul'=>$dari);

			$data['breadcumb'][]=array('icon'=>'edit',
											'link'=>'',
											'judul'=>$data['judul']);

			$this->db->select('id_agama as id, nm_agama text');
			$this->db->where('id_agama!=', '98');
			$this->db->where('deleted','0');
			$data['agama']=json_encode($this->db->get('pddikti_re_agama')->result());

			$this->db->select('id_stat_pegawai as id, nm_stat_pegawai text');
			$this->db->where('deleted','0');
			$data['status_peg']=json_encode($this->db->get('pddikti_re_status_kepegawaian')->result());

			$this->db->select('id_pekerjaan as id, nm_pekerjaan text');
			$this->db->where('deleted','0');
			$data['pekerjaan']=json_encode($this->db->get('pddikti_re_pekerjaan')->result());


			$this->db->select('kec.id_wil as id, concat(kec.nm_wil," - ",kab.nm_wil," - ",prov.nm_wil) as text');
			$this->db->join('pddikti_re_wilayah kab', 'kec.id_induk_wilayah = kab.id_wil and kab.id_level_wil="2"');
			$this->db->join('pddikti_re_wilayah prov', 'kab.id_induk_wilayah = prov.id_wil and prov.id_level_wil="1"');
			$this->db->where(array('kec.id_level_wil'=>'3','kec.id_wil'=>$aaa->id_wil));
			$data['dosen_wilayah']=$this->db->get('pddikti_re_wilayah kec')->row();

			$this->db->select('kec.id_wil as id, concat(kec.nm_wil," - ",kab.nm_wil," - ",prov.nm_wil) as text');
			$this->db->join('pddikti_re_wilayah kab', 'kec.id_induk_wilayah = kab.id_wil and kab.id_level_wil="2"');
			$this->db->join('pddikti_re_wilayah prov', 'kab.id_induk_wilayah = prov.id_wil and prov.id_level_wil="1"');
			$this->db->where(array('kec.id_level_wil'=>'3','kec.id_wil'=>$aaa->id_wil_ktp));
			$data['dosen_wilayah_ktp']=$this->db->get('pddikti_re_wilayah kec')->row();
			$data['dosen_negara']=$this->db->get_where('pddikti_re_negara',array('id_negara'=>$aaa->kewarganegaraan))->row();
			$data['id'] = $id;
	        $this->load->view('template',$data);
	    }
	}

	public function edit_data_proses($dari)
	{	
		if($this->validasi())
		{
			$pk = null;
			foreach ($_POST as $key => $value) {
				if($key != 'pengalaman_kerja') {
					$data[$key] = $value != '' ? $value : null;
				}
			}
			if(isset($_POST["pengalaman_kerja"]) && is_array($_POST["pengalaman_kerja"])) {  
					foreach($_POST["pengalaman_kerja"] as $key => $value) {
						$pk[$key] = $value != '' ? $value : null;
					}
			}
			
			date_default_timezone_set('Asia/Makassar');
			$data['date_modified'] = date("Y-m-d H:i:s");
			
			if($dari == 'front_office')
				$this->db->update('global_employee_non_dosen',$data,array("id_sdm"=>$data['id_sdm']));
			if($dari == 'apotek')
				$this->db->update('pddikti_tr_dosen',$data,array("id_sdm"=>$data['id_sdm']));
			
			$this->db->where('id_sdm', $data['id_sdm']);
			$this->db->delete('siakad_tr_pengalaman_kerja');

			//tambah data pengalaman kerja ke db
			for($i=0; $i<count($pk); $i++){
				$p_kerja = array(
					'id_sdm' => $data['id_sdm'], 
					'deskripsi_pengalaman' => $pk[''.$i]	
				);
				$this->db->insert('siakad_tr_pengalaman_kerja',$p_kerja);
			}
			redirect($_SERVER['HTTP_REFERER'],'refresh');	
		}
	}

	public function validasi()
	{
		$this->form_validation->set_rules('nm_sdm', 'Nama Dosen', 'trim|required|max_length[100]');
		/*
        $this->form_validation->set_rules('tmpt_lahir', 'Tempat Lahir', 'trim|required|max_length[32]');
        $this->form_validation->set_rules('tgl_lahir', 'Tanggal Lahir', 'trim|required');
        $this->form_validation->set_rules('jk', 'Jenis Kelamin', 'trim|required');
        $this->form_validation->set_rules('id_agama', 'Agama', 'trim|required');
        $this->form_validation->set_rules('nik', 'NIK', 'trim|required|numeric|max_length[16]');
        //$this->form_validation->set_rules('nip', 'NIP', 'trim|max_length[18]');
        //$this->form_validation->set_rules('nidn', 'NIDN/NUP/NIDK', 'trim|numeric|required|max_length[30]');
        $this->form_validation->set_rules('npwp', 'NPWP', 'trim|max_length[15]');
        //$this->form_validation->set_rules('nm_ibu_kandung', 'Nama Ibu', 'trim|required|max_length[100]');
        //$this->form_validation->set_rules('id_stat_aktif', 'Status Aktif', 'trim|required');
        $this->form_validation->set_rules('id_stat_pegawai', 'Status Pegawai', 'trim');

        $this->form_validation->set_rules('kontrak_dari', 'Periode Kontrak Dari', 'trim');
        $this->form_validation->set_rules('kontrak_sampai', 'Periode Kontrak Sampai', 'trim');
        //$this->form_validation->set_rules('id_lemb_angkat', 'Lembaga Pengangkatan', 'trim');
        //$this->form_validation->set_rules('id_pangkat_gol', 'Pangkat Golongan', 'trim');
        //$this->form_validation->set_rules('sk_cpns', 'No. SK CPNS', 'trim|max_length[80]');
        //$this->form_validation->set_rules('tgl_sk_cpns', 'Tanggal SK CPNS', 'trim');
        //$this->form_validation->set_rules('sk_angkat', 'No. SK Pengangkatan', 'trim|max_length[80]');
        //$this->form_validation->set_rules('tmt_sk_angkat', 'Tanggal SK Pengangkatan', 'trim');
        $this->form_validation->set_rules('jln', 'Alamat', 'trim|max_length[80]');
        //$this->form_validation->set_rules('nm_dsn', 'Dusun', 'trim|max_length[60]');
        $this->form_validation->set_rules('ds_kel', 'Kelurahan', 'trim|required|max_length[60]');
        //$this->form_validation->set_rules('rt', 'RT', 'trim|numeric');
        //$this->form_validation->set_rules('rw', 'RW', 'trim|numeric');
        $this->form_validation->set_rules('id_wil', 'Kecamatan', 'trim|required');
        $this->form_validation->set_rules('kode_pos', 'Kode Pos', 'trim|numeric|max_length[5]');
        $this->form_validation->set_rules('kewarganegaraan', 'Kewarganegaraan', 'trim|required');
        $this->form_validation->set_rules('no_tel_rmh', 'No Telepon', 'trim|max_length[20]');
        $this->form_validation->set_rules('no_hp', 'No HP', 'trim|max_length[20]');
        $this->form_validation->set_rules('email', 'Email', 'trim|valid_email|max_length[60]');
        $this->form_validation->set_rules('fb_account', 'FB Account', 'trim|max_length[60]');
        $this->form_validation->set_rules('stat_kawin', 'Status Pernikahan', 'trim');
        //$this->form_validation->set_rules('nm_suami_istri', 'Nama Suami / Istri', 'trim|max_length[100]');
        //$this->form_validation->set_rules('nip_suami_istri', 'NIP Suami / Istri', 'trim|max_length[18]');
        //$this->form_validation->set_rules('tmt_pns', 'TMT PNS', 'trim');
        $this->form_validation->set_rules('id_pekerjaan_suami_istri', 'Pekerjaan', 'trim');
        //$this->form_validation->set_rules('pengalaman_kerja', 'Pengalaman Kerja', 'trim|max_length[60]');

        $this->form_validation->set_rules('program_studi', 'Program Studi', 'trim|max_length[60]');
        $this->form_validation->set_rules('stat_kawin', 'Status Pernikahan', 'trim');
        $this->form_validation->set_rules('pendidikan', 'Pendidikan Terakhir', 'trim');
        $this->form_validation->set_rules('status_sertifikasi_metodologi', 'Status Sertifikasi Metodologi', 'trim');

        //$this->form_validation->set_rules('filename', 'File Name', 'trim|required|max_length[32]');
        //$this->form_validation->set_rules('cek_upload', 'Cek Upload', 'trim|required|max_length[32]');

        $this->form_validation->set_message('required', '{field} harus diisi!');
        $this->form_validation->set_message('numeric', '{field} harus berupa angka!');
        $this->form_validation->set_message('max_length', '{field} tidak boleh lebih dari {param} karakter!');
        $this->form_validation->set_message('valid_email', '{field} tidak valid!');
        */

        $valid=$this->form_validation->run();
        if($valid)
        {
        	return $valid;
        }
        else
        {
        	echo json_encode(array("status"=>"2","title"=>"Error!","message"=>"Terjadi kesalahan, silahkan periksa kembali data yang diinputkan","detail_error"=>$this->form_validation->field_data()));
        }
	}


}

