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

class informasi_gaji_temp extends MY_Controller {

	public function __construct(){
        parent::__construct();
        $this->load->model(array('Informasi_gaji_temp_m'));
        $this->load->library(array('PHPExcel/Excel', 'PHPExcel/PHPExcel', 'Uploadfile'));

        $this->id_karyawan = $this->session->userdata('id_karyawan');
        $this->id_company = $this->session->userdata('id_company');
    }


	public function index(){
		$data['judul'] = 'Import Informasi Gaji';
		$data['aktif'] = 'gaji';
        $data['menu'] = $this->load->view('main_menu', $data, true);
		$data['content'] = $this->load->view('informasi_gaji_temp/home', $data, true);
		$this->load->view('main_template', $data, false);
	}

	public function list_data(){
		$list = $this->Informasi_gaji_temp_m->get_datatables();
		$data = array();
		$no = $_POST['start'];
		foreach ($list as $field) {
			$no++;
			$row = array();

			$row[] = $no;
			$row[] = $field->periode;
			$row[] = $field->nama_karyawan."<br><span class='font-size-xsmall'>".$field->nik."</span>";
			$row[] = $field->kode_cabang." - ".$field->nama_cabang;
			$row[] = $field->kode_departemen." - ".$field->nama_departemen;
			$row[] = $field->kode_jabatan." - ".$field->nama_jabatan;
			$row[] = "Rp. ".number_format($field->gaji_pokok,0,",",".");

			$row[] = "Rp. ".number_format($field->t_jabatan,0,",",".");
			$row[] = "Rp. ".number_format($field->t_transport,0,",",".");
			$row[] = "Rp. ".number_format($field->t_makan,0,",",".");
			$row[] = "Rp. ".number_format($field->t_istri,0,",",".");
			$row[] = "Rp. ".number_format($field->t_anak,0,",",".");
			$row[] = "Rp. ".number_format($field->lembur,0,",",".");
			$row[] = "Rp. ".number_format($field->komisi,0,",",".");
			$row[] = "Rp. ".number_format($field->t_lain,0,",",".");

			$row[] = "Rp. ".number_format($field->ttl_tunjangan,0,",",".");
			$row[] = "Rp. ".number_format($field->ttl_penerimaan,0,",",".");

			$row[] = "Rp. ".number_format($field->tbp_bpjs_tk,0,",",".");
			$row[] = "Rp. ".number_format($field->tbp_bpjs_kesehatan,0,",",".");
			$row[] = "Rp. ".number_format($field->tbp_lain,0,",",".");
			$row[] = "Rp. ".number_format($field->ttl_tbp,0,",",".");

			$row[] = "Rp. ".number_format($field->p_absensi,0,",",".");
			$row[] = "Rp. ".number_format($field->p_keterlambatan,0,",",".");
			$row[] = "Rp. ".number_format($field->p_koperasi,0,",",".");
			$row[] = "Rp. ".number_format($field->p_asuransi_kesehatan,0,",",".");
			$row[] = "Rp. ".number_format($field->p_bpjs_tk,0,",",".");
			$row[] = "Rp. ".number_format($field->p_bpjs_kesehatan,0,",",".");
			$row[] = "Rp. ".number_format($field->p_lain,0,",",".");

			$row[] = "Rp. ".number_format($field->ttl_potongan,0,",",".");
			$row[] = "Rp. ".number_format($field->gaji_diterima,0,",",".");

			$aksi ='<a href="'.route("informasi.gaji.import.form.edit").'/'.md5($field->id).'" id="'.md5($field->id).'" title="EDIT">
							<i class="fa fa-edit '.(($field->flag == 1)?"text-warning":"text-white").'"></i></a>';
					// <a href="#" id="'.md5($field->id).'" class="btn_form_hapus" title="HAPUS">
					// 		<i class="fa fa-trash '.(($field->flag == 1)?"text-danger":"text-white").'"></i></a>&nbsp;';

			$row[] = $aksi;
			$row[] = $field->flag;


			$data[] = $row;
		}

			$output = array("draw"            => $_POST['draw'],
							"recordsTotal"    => $this->Informasi_gaji_temp_m->count_all(),
							"recordsFiltered" => $this->Informasi_gaji_temp_m->count_filtered(),
							"data"            => $data);

			$output = __response($this->MY_response, $output);

		echo json_encode($output);
	}

	public function form_template_import(){
		$this->load->view('informasi_gaji_temp/form_template_import');
	}

	public function import_data_excel(){
		$periode = $this->input->post("periode");
        if(!empty($_FILES['file']['name'])) {
			$tahunbulan = date('Ym');
            $fileUpload['fname']    = 'file';
            $fileUpload['location'] = 'template_gaji/'.$tahunbulan;
            $fileUpload['allowed']  = 'xls|xlsx';
            $fileUpload['compress_image']  = false;

            $upload = $this->uploadfile->doUpload($fileUpload);
			if($upload["success"] == true){
				$dir_file = $this->config->item('base_upload').$upload['url'];
			}else{
				$message = ["message"=>$upload["message"]];
				return __response_save(false,$message);
			}
        }else{
			$message = ["message"=>'<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>Data gagal import</font>'];
			return __response_save(false,["message"=>$message]);
        }

        try{
            $inputFileType = PHPExcel_IOFactory::identify($dir_file);
            $objReader = PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($dir_file);
        }catch(Exception $e){
			$message = ["message"=>'Error loading file "' . pathinfo($dir_file, PATHINFO_BASENAME) . '": ' . $e->getMessage()];
			return __response_save(false,["message"=>$message]);
        }

        $row = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
        $end = sizeof($row);

		$data_insert = array();
        $data = array();

        $id_temp = $this->fungsi->getNextId('informasi_gaji_temp','id',$this->id_company,4);
        for ($i = 9; $i <= ($end-1); $i++){
			// var_dump($row[$i]['AJ']);
            $id_karyawan 	= (isset($row[$i]['AE']) && $row[$i]['AE'] != NULL) ? $row[$i]['AE'] : '';
            $nik 	= (isset($row[$i]['B']) && $row[$i]['B'] != NULL) ? $row[$i]['B'] : '';
            $nama_karyawan 	= (isset($row[$i]['C']) && $row[$i]['C'] != NULL) ? $row[$i]['C'] : '';
            $kode_cabang 	= (isset($row[$i]['AF']) && $row[$i]['AF'] != NULL) ? $row[$i]['AF'] : '';
            $nama_cabang 	= (isset($row[$i]['AG']) && $row[$i]['AG'] != NULL) ? $row[$i]['AG'] : '';
            $kode_departemen = (isset($row[$i]['AH']) && $row[$i]['AH'] != NULL) ? $row[$i]['AH'] : '';
            $nama_departemen = (isset($row[$i]['AI']) && $row[$i]['AI'] != NULL) ? $row[$i]['AI'] : '';
            $kode_jabatan = (isset($row[$i]['AJ']) && $row[$i]['AJ'] != NULL) ? $row[$i]['AJ'] : '';
            $nama_jabatan = (isset($row[$i]['AK']) && $row[$i]['AK'] != NULL) ? $row[$i]['AK'] : '';

			# GAJI POKOK
            $gaji_pokok = (isset($row[$i]['G']) && $row[$i]['G'] != NULL) ? str_replace(',','',$row[$i]['G']) : '0';

			# TUNJANGAN
            $jabatan 	= (isset($row[$i]['H']) && $row[$i]['H'] != NULL) ? str_replace(',','',$row[$i]['H']) : '0';
            $transport 	= (isset($row[$i]['I']) && $row[$i]['I'] != NULL) ? str_replace(',','',$row[$i]['I']) : '0';
            $makan 		= (isset($row[$i]['J']) && $row[$i]['J'] != NULL) ? str_replace(',','',$row[$i]['J']) : '0';
            $tunj_istri = (isset($row[$i]['K']) && $row[$i]['K'] != NULL) ? str_replace(',','',$row[$i]['K']) : '0';
            $tunj_anak 	= (isset($row[$i]['L']) && $row[$i]['L'] != NULL) ? str_replace(',','',$row[$i]['L']) : '0';
            $lembur 	= (isset($row[$i]['M']) && $row[$i]['M'] != NULL) ? str_replace(',','',$row[$i]['M']) : '0';
            $komisi 	= (isset($row[$i]['N']) && $row[$i]['N'] != NULL) ? str_replace(',','',$row[$i]['N']) : '0';
            $tunj_lain 	= (isset($row[$i]['O']) && $row[$i]['O'] != NULL) ? str_replace(',','',$row[$i]['O']) : '0';

            $total_tunjangan	= (isset($row[$i]['P']) && $row[$i]['P'] != NULL) ? str_replace(',','',$row[$i]['P']) : '0';
            $total_penerimaan 	= (isset($row[$i]['Q']) && $row[$i]['Q'] != NULL) ? str_replace(',','',$row[$i]['Q']) : '0';

			# ASURANSI DIBIAYAI PERUSAHAAN
            $tbp_bpjs_tk 	= (isset($row[$i]['R']) && $row[$i]['R'] != NULL) ? str_replace(',','',$row[$i]['R']) : '0';
            $tbp_bpjs_kes 	= (isset($row[$i]['S']) && $row[$i]['S'] != NULL) ? str_replace(',','',$row[$i]['S']) : '0';
            $tbp_lain 		= (isset($row[$i]['T']) && $row[$i]['T'] != NULL) ? str_replace(',','',$row[$i]['T']) : '0';
            $ttl_tbp 		= (isset($row[$i]['U']) && $row[$i]['U'] != NULL) ? str_replace(',','',$row[$i]['U']) : '0';

			# POTONGAN
            $pot_absensi 	= (isset($row[$i]['V']) && $row[$i]['V'] != NULL) ? str_replace(',','',$row[$i]['V']) : '0';
            $pot_terlambat 	= (isset($row[$i]['W']) && $row[$i]['W'] != NULL) ? str_replace(',','',$row[$i]['W']) : '0';
            $pot_koperasi 	= (isset($row[$i]['X']) && $row[$i]['X'] != NULL) ? str_replace(',','',$row[$i]['X']) : '0';
            $pot_askes 		= (isset($row[$i]['Y']) && $row[$i]['Y'] != NULL) ? str_replace(',','',$row[$i]['Y']) : '0';
            $pot_bpjs_tk 	= (isset($row[$i]['Z']) && $row[$i]['Z'] != NULL) ? str_replace(',','',$row[$i]['Z']) : '0';
            $pot_bpjs_kes 	= (isset($row[$i]['AA']) && $row[$i]['AA'] != NULL) ? str_replace(',','',$row[$i]['AA']) : '0';
            $pot_lain 		= (isset($row[$i]['AB']) && $row[$i]['AB'] != NULL) ? str_replace(',','',$row[$i]['AB']) : '0';

            $total_potongan = (isset($row[$i]['AC']) && $row[$i]['AC'] != NULL) ? str_replace(',','',$row[$i]['AC']) : '0';
            $gaji_diterima 	= (isset($row[$i]['AD']) && $row[$i]['AD'] != NULL) ? str_replace(',','',$row[$i]['AD']) : '0';

            if ($gaji_pokok == '0') {
                $flag = "0";
            }else{
				$flag = "1";
			}

            $data = array('id' => $id_temp,
							'periode' => $periode,
							'nik' => $nik,
							'id_karyawan' => $id_karyawan,
							'nama_karyawan' => $nama_karyawan,
							'kode_cabang' => $kode_cabang,
							'nama_cabang' => $nama_cabang,
							'kode_departemen' => $kode_departemen,
							'nama_departemen' => $nama_departemen,
							'kode_jabatan' => $kode_jabatan,
							'nama_jabatan' => $nama_jabatan,

							'gaji_pokok' => $gaji_pokok,
							't_jabatan' => $jabatan,
							't_transport' => $transport,
							't_makan' => $makan,
							't_istri' => $tunj_istri,
							't_anak' => $tunj_anak,
							'lembur' => $lembur,
							'komisi' => $komisi,
							't_lain' => $tunj_lain,

							'ttl_tunjangan' => $total_tunjangan,
							'ttl_penerimaan' => $total_penerimaan,

							'tbp_bpjs_tk' => $tbp_bpjs_tk,
							'tbp_bpjs_kesehatan' => $tbp_bpjs_kes,
							'tbp_lain' => $tbp_lain,
							'ttl_tbp' => $ttl_tbp,

							'p_absensi' => $pot_absensi,
							'p_keterlambatan' => $pot_terlambat,
							'p_koperasi' => $pot_koperasi,
							'p_asuransi_kesehatan' => $pot_askes,
							'p_bpjs_tk' => $pot_bpjs_tk,
							'p_bpjs_kesehatan' => $pot_bpjs_kes,
							'p_lain' => $pot_lain,

							'ttl_potongan' => $total_potongan,
							'gaji_diterima' => $gaji_diterima,

							'flag' => $flag,
							'user_input' => $this->id_karyawan,
							'id_company' => $this->id_company);

			$last_id = substr($id_temp,-4);
			$next_id = $last_id+1;
			$id_temp = substr($id_temp,0,-4).sprintf("%04d", $next_id);

			$data_insert[] = $data;
        }

		$this->db->trans_start();

		$this->db->where("id_company",$this->id_company);
		$this->db->delete("informasi_gaji_temp");

		$this->db->insert_batch('informasi_gaji_temp', $data_insert);

		$this->db->trans_complete();

		if ($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			$message = ["message"=>'<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>Data gagal diimport</font>'];
			return __response_save(false,["message"=>$message]);
		}else{
			$this->db->trans_commit();
			$message = ["message"=>'<font color="#009900"><i class="fa fa-check-square">&nbsp;</i>Data berhasil diimport</font>'];
			return __response_save(true,["message"=>$message]);
		}
    }

	public function detail($id){
		$data['judul'] = 'Detail Informasi Gaji';
		$data['aktif'] = 'gaji';
		$data['data'] = $this->Informasi_gaji_m->getDataById($id);
		$data['ref'] = $id;
		$data['menu'] = $this->load->view('main_menu', $data, true);
		$data['content'] = $this->load->view('informasi_gaji/detail', $data, true);
		$this->load->view('main_template', $data);
	}

	public function form_edit($id=null){
		$data['judul'] = 'Ubah Informasi Gaji Temp';
		$data['aktif'] = 'gaji';
		$data['data'] = $this->Informasi_gaji_temp_m->getData($id);
		$data['ref'] = $id;
        $data['menu'] = $this->load->view('main_menu', $data, true);
		$data['content'] = $this->load->view('informasi_gaji_temp/form', $data, true);
		$this->load->view('main_template', $data, false);

	}

	public function update(){
		$id = $this->input->post('id');

        $gaji_pokok  = str_replace('.','',$this->input->post('gaji_pokok'));

		$t_jabatan   = str_replace('.','',$this->input->post('t_jabatan'));
		$t_transport = str_replace('.','',$this->input->post('t_transport'));
		$t_makan 	 = str_replace('.','',$this->input->post('t_makan'));
		$t_istri 	 = str_replace('.','',$this->input->post('t_istri'));
		$t_anak 	 = str_replace('.','',$this->input->post('t_anak'));
		$lembur 	 = str_replace('.','',$this->input->post('lembur'));
		$komisi      = str_replace('.','',$this->input->post('komisi'));
		$t_lain 	 = str_replace('.','',$this->input->post('t_lain'));
		$ttl_tunjangan 	 = str_replace('.','',$this->input->post('ttl_tunjangan'));
		$ttl_penerimaan 	 = str_replace('.','',$this->input->post('ttl_penerimaan'));

		$p_absensi 	 		  = str_replace('.','',$this->input->post('p_absensi'));
		$p_keterlambatan 	  = str_replace('.','',$this->input->post('p_keterlambatan'));
		$p_koperasi  		  = str_replace('.','',$this->input->post('p_koperasi'));
		$p_asuransi_kesehatan = str_replace('.','',$this->input->post('p_asuransi_kesehatan'));
		$p_bpjs_tk 			  = str_replace('.','',$this->input->post('p_bpjs_tk'));
		$p_bpjs_kesehatan  	  = str_replace('.','',$this->input->post('p_bpjs_kesehatan'));
		$p_lain 			  = str_replace('.','',$this->input->post('p_lain'));
		$ttl_tbp 			  = str_replace('.','',$this->input->post('ttl_tbp'));

		$ttl_potongan 			  = str_replace('.','',$this->input->post('ttl_potongan'));
		$gaji_diterima 			  = str_replace('.','',$this->input->post('gaji_diterima'));

		if($gaji_pokok > 0){
			$flag = "1";
		}else{
			$flag = "2";
		}

        $data = array('id_karyawan'		=>$this->input->post('id_karyawan'),
					'gaji_pokok'		=>$gaji_pokok,
					't_jabatan'			=>$t_jabatan,
					't_transport'		=>$t_transport,
					't_makan'			=>$t_makan,
					't_istri'			=>$t_istri,
					't_anak'			=>$t_anak,
					'lembur'			=>$lembur,
					'komisi'			=>$komisi,
					't_lain'			=>$t_lain,
					'ttl_tunjangan'		=>$ttl_tunjangan,
					'ttl_penerimaan'	=>$ttl_penerimaan,
					'tbp_bpjs_tk'		=>str_replace('.','',$this->input->post('tbp_bpjs_tk')),
					'tbp_bpjs_kesehatan'=>str_replace('.','',$this->input->post('tbp_bpjs_kesehatan')),
					'tbp_lain'			=>str_replace('.','',$this->input->post('tbp_lain')),
					'p_absensi'			=>$p_absensi,
					'p_keterlambatan'	=>$p_keterlambatan,
					'p_koperasi'		=>$p_koperasi,
					'p_asuransi_kesehatan'=>$p_asuransi_kesehatan,
					'p_bpjs_tk'			=>$p_bpjs_tk,
					'p_bpjs_kesehatan'	=>$p_bpjs_kesehatan,
					'p_lain'			=>$p_lain,
					'ttl_tbp' 			=>$ttl_tbp,
					'ttl_potongan'		=>$ttl_potongan,
					'gaji_diterima'		=>$gaji_diterima,
					'flag'				=>$flag,
					'user_input'		=>$this->id_karyawan,
					'id_company'		=>$this->id_company);


		$this->Informasi_gaji_temp_m->update($data,$id);
	}

	public function save_all(){
		$get_data_temp = $this->db->select('*')
								->from('informasi_gaji_temp')
								->where('id_company',$this->id_company)
								->get()
								->result();

		$data_update = array();
		$data_insert = array();
        $data = array();
        $id_informasi_gaji = $this->fungsi->getNextId('informasi_gaji','id',$this->id_company,4);

		$jml_berahasil_simpan = 0;
		$jml_gagal_simpan = 0;

		foreach ($get_data_temp as $rows) {
			if($rows->flag == "1"){
				$data_existing = $this->Informasi_gaji_temp_m->getDataExisting($rows->periode, $rows->id_karyawan);
				if($data_existing == 0){
					$jml_berahasil_simpan++;

					$data = array('id'	=>$id_informasi_gaji,
							'periode'			=>$rows->periode,
							'id_karyawan'		=>$rows->id_karyawan,
							'nik'				=>$rows->nik,
							'nama_karyawan'		=>$rows->nama_karyawan,
							'kode_cabang'		=>$rows->kode_cabang,
							'nama_cabang'		=>$rows->nama_cabang,
							'kode_departemen'	=>$rows->kode_departemen,
							'nama_departemen'	=>$rows->nama_departemen,
							'kode_jabatan'		=>$rows->kode_jabatan,
							'nama_jabatan'		=>$rows->nama_jabatan,
							'gaji_pokok'		=>$rows->gaji_pokok,
							't_jabatan'			=>$rows->t_jabatan,
							't_transport'		=>$rows->t_transport,
							't_makan'			=>$rows->t_makan,
							't_istri'			=>$rows->t_istri,
							't_anak'			=>$rows->t_anak,
							'lembur'			=>$rows->lembur,
							'komisi'			=>$rows->komisi,
							't_lain'			=>$rows->t_lain,
							'ttl_tunjangan'		=>$rows->ttl_tunjangan,
							'ttl_penerimaan'	=>$rows->ttl_penerimaan,
							'tbp_bpjs_tk'		=>$rows->tbp_bpjs_tk,
							'tbp_bpjs_kesehatan'=>$rows->tbp_bpjs_kesehatan,
							'tbp_lain'			=>$rows->tbp_lain,
							'ttl_tbp' 			=>$rows->ttl_tbp,
							'p_absensi'			=>$rows->p_absensi,
							'p_keterlambatan'	=>$rows->p_keterlambatan,
							'p_koperasi'		=>$rows->p_koperasi,
							'p_asuransi_kesehatan'=>$rows->p_asuransi_kesehatan,
							'p_bpjs_tk'			=>$rows->p_bpjs_tk,
							'p_bpjs_kesehatan'	=>$rows->p_bpjs_kesehatan,
							'p_lain'			=>$rows->p_lain,
							'ttl_potongan'		=>$rows->ttl_potongan,
							'gaji_diterima'		=>$rows->gaji_diterima,
							'user_input'		=>$this->id_karyawan,
							'id_company'		=>$this->id_company);

					$last_id = substr($id_informasi_gaji,-4);
					$next_id = $last_id+1;
					$id_informasi_gaji = substr($id_informasi_gaji,0,-4).sprintf("%04d", $next_id);

					$data_insert[] = $data;
				}else{
					$jml_gagal_simpan++;
					$data_update[] = array('id'	=>	$rows->id,
											'flag'	=> "3");

				}
			}else{
				$jml_gagal_simpan++;
			}

		}

		$this->db->trans_start();

		# UPDATE DATA TEMP JIKA DATA SUDAH ADA DI TABEL INFORMASI GAJI
		if(count($data_update) > 0){
			$this->db->update_batch('informasi_gaji_temp', $data_update, 'id');
		}

		# MEMINDAHKAN DATA DARI TEMP KE INFORMASI GAJI
		if(count($data_insert) > 0){
			$this->db->insert_batch('informasi_gaji', $data_insert);
		}

		# DELETE DATA TEMP YANG SUDAH DI PINDAH
		$this->db->where("flag","1");
		$this->db->where("id_company",$this->id_company);
		$this->db->delete("informasi_gaji_temp");

		$this->db->trans_complete();

		if($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			$message = ["message"=>'<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>Data gagal disimpan</font>'];
			return __response_save(false,$message);
		}else{
			$this->db->trans_commit();
			$message = ["message"=>'<font color="#ffffff"><i class="fa fa-check-square">&nbsp;</i>'.$jml_berahasil_simpan.' Data berhasil disimpan dan '.$jml_gagal_simpan.' Data gagal disimpan</font>'];
			return __response_save(true,$message);
		}

    }

	public function delete(){
		$id = $this->input->post("id");
		$this->db->where('MD5(id)',$id);
		$this->db->where('id_company',$this->id_company);
        $delete =$this->db->delete('informasi_gaji_temp');
        return  __response_delete($delete);
	}

	public function delete_all(){
		$this->db->where('id_company',$this->id_company);
        $delete =$this->db->delete('informasi_gaji_temp');
        return  __response_delete($delete);
	}
}
