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

class Pengajuan_izin extends MY_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('Pengajuan_izin_m');
		$this->load->model('Db_model', 'db_model');
		$this->load->model('Master_plan_m');
	}

	//CRUD
	public function index()
	{
		$data['judul'] = 'Pengajuan Izin';
		$data['aktif'] = 'izin';
		$data['level_user'] = $this->level_user;
		$data['multi_cabang'] = $this->multi_cabang;
		$data['multi_departemen'] = $this->multi_departemen;
		$data['periode_awal'] = date('d-m-Y',  strtotime(date('Y-m-').'01'));
		$data['periode_akhir'] = date('d-m-Y',  strtotime(date('Y-m-d')));
		$data['button_sso'] = $this->Master_plan_m->button_sso();
		$data['menu'] = $this->load->view('main_menu', $data, true);
		$data['content'] = $this->load->view('pengajuan_izin/home', $data, true);
		$this->load->view('main_template', $data, false);
	}

	public function view_data($tgl_mulai, $tgl_selesai, $jenis, $status, $id_karyawan, $id_cabang, $id_departemen)
	{
		$data['judul']      	= 'Pengajuan Izin';
		$data['aktif']      	= 'izin';
		$data['tgl_mulai']		= date('Y-m-d', strtotime($tgl_mulai));
		$data['tgl_selesai']	= date('Y-m-d', strtotime($tgl_selesai));
		$data['jenis']  		= $jenis;
		$data['status']  		= $status;
		$data['id_karyawan']	= $id_karyawan;
		$data['id_cabang']     	= $id_cabang;
		$data['id_departemen']	= $id_departemen;
		$this->load->view('pengajuan_izin/list_data', $data, false);
	}

	public function detail($id){
		$data['data'] = $this->db_model->get('data_izin', 'data_izin.*, master_jabatan.level_user as usergroup, data_karyawan.nama_lengkap, file_izin.file as file_izin ', 'md5(data_izin.id_izin) = "' . $id . '"', '', '', '', '', 			 array(
			array(
				'table' => 'data_karyawan',
				'on' => 'data_karyawan.id_karyawan = data_izin.id_karyawan AND data_karyawan.id_company = data_izin.id_company'
			),
			array(
				'table' => 'master_jabatan',
				'on' => 'master_jabatan.id_jabatan = data_karyawan.id_jabatan AND master_jabatan.id_company = data_karyawan.id_company'
			),
			array(
				'table' => 'file_izin',
				'on' => 'file_izin.id_izin = data_izin.id_izin',
				'pos'	=> 'left'
			)
		))->row();

		$approval_spv 		= $data['data']->approval_spv;
		if($approval_spv != '0'){
			$data['stts_spv']	 	= $this->_statusAproval($approval_spv);
			$data['usr_apv_spv'] 	= $this->Pengajuan_izin_m->userApproval($data['data']->user_spv);
		}else{
			$data['stts_spv']		= '-';
			$data['usr_apv_spv']	= '';
		}

		$approval_kedep 	= $data['data']->approval_kedep;
		if($approval_kedep != '0'){
			$data['stts_kedep']	 	= $this->_statusAproval($approval_kedep);
			$data['usr_apv_kedep'] 	= $this->Pengajuan_izin_m->userApproval($data['data']->user_kedep);
		}else{
			$data['stts_kedep']		= '-';
			$data['usr_apv_kedep']	= '';
		}

		$approval_kacab 	= $data['data']->approval_kacab;
		if($approval_kacab != '0'){
			$data['stts_kacab']	 	= $this->_statusAproval($approval_kacab);
			$data['usr_apv_kacab'] 	= $this->Pengajuan_izin_m->userApproval($data['data']->user_kacab);
		}else{
			$data['stts_kacab']		= '-';
			$data['usr_apv_kacab']	= '';
		}

		$approval_direksi 	= $data['data']->approval_direksi;
		if($approval_direksi != '0'){
			$data['stts_direksi']	 	= $this->_statusAproval($approval_direksi);
			$data['usr_apv_direksi'] 	= $this->Pengajuan_izin_m->userApproval($data['data']->user_direksi);
		}else{
			$data['stts_direksi']		= '-';
			$data['usr_apv_direksi']	= '';
		}

		$approval_hrd 		= $data['data']->approval_hrd;
		if($approval_hrd != '0'){
			$data['stts_hrd']	 	= $this->_statusAproval($approval_hrd);
			$data['usr_apv_hrd'] 	= $this->Pengajuan_izin_m->userApproval($data['data']->user_hrd);
		}else{
			$data['stts_hrd']		= '-';
			$data['usr_apv_hrd']	= '';
		}

		$this->load->view('pengajuan_izin/detail', $data);
	}

	private function _statusAproval($status='0'){
		switch ($status) {
			case '1':
				return '<span class="badge badge-primary">Pengajuan</span>';
				break;
			case '2':
				return '<span class="badge badge-secondary">Dibatalkan</span>';
				break;
			case '3':
				return '<span class="badge badge-danger">Ditolak</span>';
				break;
			case '4':
				return '<span class="badge badge-success">Disetujui</span>';
				break;
			default:
				return '-';
		}
	}

	public function detail_izin($id)
	{
		$data['judul'] = 'Pengajuan Izin';
		$data['sub_judul'] = 'Detail Izin';
		$data['aktif'] = 'izin';

		$data['data'] = $this->db_model->get('data_izin', 'data_izin.*, master_jabatan.level_user as usergroup, data_karyawan.nik, data_karyawan.nama_lengkap, ', 'md5(data_izin.id_izin) = "' . $id . '"', '', '', '', '', 			 array(
			array(
				'table' => 'data_karyawan',
				'on' => 'data_karyawan.id_karyawan = data_izin.id_karyawan AND data_karyawan.id_company = data_izin.id_company'
			),
			array(
				'table' => 'master_jabatan',
				'on' => 'master_jabatan.id_jabatan = data_karyawan.id_jabatan AND master_jabatan.id_company = data_karyawan.id_company'
			)
		))->row();

		if ($data['data'] != null) {
			foreach ($data['data'] as $k => $v) {
				$res = $this->db->select('file')
					->from('file_izin')
					->where('id_izin', $data['data']->id_izin)
					->get()
					->result();
				if ($res != null) {
					$data['data']->fl_izin = $res;
				}
			}
		}

		$data['menu'] = $this->load->view('main_menu', $data, true);
		$data['content'] = $this->load->view('pengajuan_izin/detail_izin', $data, true);
		$this->load->view('main_template', $data, false);
	}

	public function list_data($tgl_mulai="0", $tgl_selesai="0", $jenis = "SM", $status="0", $id_karyawan="0", $id_cabang="0", $id_departemen="0")
	{
		$lvl = $this->session->userdata('level_user');
		switch ($lvl) {
			case '1':
				$str = 'hrd';
				break;
			case '2':
				$str = 'kedep';
				break;
			case '4':
				$str = 'direksi';
				break;
			case '5':
				$str = 'kacab';
				break;
			case '7':
				$str = 'spv';
				break;

			default:
				$str = 'hrd';
				break;
		}

		$appv_sts = [];
		if ($status == '1') {
			$appv_sts = ['1'];
		} elseif ($status == '2') {
			$appv_sts = ['3'];
		} elseif ($status == '3') {
			$appv_sts = ['4'];
		} elseif ($status == '0') {
			$appv_sts = ['1', '2', '3', '4'];
		}
		$appv_lvl = 'approval_' . $str;
		$stts['appv_lvl'] = $appv_lvl;
		$stts['appv_sts'] = $appv_sts;
		$stts['appv_flt'] = $status;

		$recordsTotal       = $this->Pengajuan_izin_m->count_all($tgl_mulai, $tgl_selesai, $jenis, $stts, $id_karyawan, $id_cabang, $id_departemen);
        $recordsFiltered    = $this->Pengajuan_izin_m->count_filtered($tgl_mulai, $tgl_selesai, $jenis, $stts, $id_karyawan, $id_cabang, $id_departemen);

		$list = $this->Pengajuan_izin_m->get_datatables($tgl_mulai, $tgl_selesai, $jenis, $stts, $id_karyawan, $id_cabang, $id_departemen);

		$data = array();
		$no = $_POST['start'];
		foreach ($list as $field) {
			$no++;
			$row = array();
			$row[] = $no;
			$row[] = $field->nama_lengkap."<br>".$field->nik;
			$row[] = $field->nama_izin;
			$row[] = date('d-m-Y', strtotime($field->tgl_pengajuan));
			$row[] = date('d-m-Y', strtotime($field->tgl_mulai_izin)) . "<br>s/d<br>" . date('d-m-Y', strtotime($field->tgl_selesai_izin));
			$row[] = $field->jml_izin;
			$row[] = $field->ket_izin;


			if (in_array($this->level_user,['1','7'])) {
				if ($field->approval_spv == 1) {
					$spv = '<a href="#" id="' . md5($field->id_izin) . '" class="btn_verifikasi btn btn-primary" level_verifikasi="7" title="VERIFIKASI">
							<i class="fa fa-check"> </i> VERIFIKASI</a>&nbsp;';
				} else {
					$spv = $this->fungsi->get_approval($field->approval_spv);
				}
			} else {
				$spv = $this->fungsi->get_approval($field->approval_spv);
			}

			$row[] = $spv;


			if (in_array($this->level_user,['1','2'])) {
				if($field->approval_kedep == '1') {
					$kedep = '<a href="#" id="' . md5($field->id_izin) . '" class="btn_verifikasi btn btn-primary" level_verifikasi="2" title="VERIFIKASI">
					<i class="fa fa-check"> </i> VERIFIKASI</a>&nbsp;';
				} else {
					$kedep = $this->fungsi->get_approval($field->approval_kedep);
				}
			}else{
				$kedep = $this->fungsi->get_approval($field->approval_kedep);
			}

			$row[] = $kedep;

			if (in_array($this->level_user,['1','5'])) {
				if($field->approval_kacab == '1') {
					$kacab = '<a href="#" id="' . md5($field->id_izin) . '" class="btn_verifikasi btn btn-primary" level_verifikasi="5" title="VERIFIKASI">
					<i class="fa fa-check"> </i> VERIFIKASI</a>&nbsp;';
				} else {
					$kacab = $this->fungsi->get_approval($field->approval_kacab);
				}
			}else{
				$kacab = $this->fungsi->get_approval($field->approval_kacab);
			}

			$row[] = $kacab;

			if (in_array($this->level_user,['1','4'])) {
				if($field->approval_direksi == '1') {
					$direksi = '<a href="#" id="' . md5($field->id_izin) . '" class="btn_verifikasi btn btn-primary" level_verifikasi="4" title="VERIFIKASI">
					<i class="fa fa-check"> </i> VERIFIKASI</a>&nbsp;';
				} else {
					$direksi = $this->fungsi->get_approval($field->approval_direksi);
				}
			} else {
				$direksi = $this->fungsi->get_approval($field->approval_direksi);
			}

			$row[] = $direksi;

			if ($this->level_user == 1) {
				if($field->approval_hrd == '1') {
					$hrd = '<a href="#" id="' . md5($field->id_izin) . '" class="btn_verifikasi btn btn-primary" level_verifikasi="1" title="VERIFIKASI">
					<i class="fa fa-check"> </i> VERIFIKASI</a>&nbsp;';
				} else {
					$hrd = $this->fungsi->get_approval($field->approval_hrd);
				}
			} else {
				$hrd = $this->fungsi->get_approval($field->approval_hrd);
			}

			$row[] = $hrd;

			if ($this->level_user == 1) {
				$row[] = '<a href="#" class="text-primary" title="DETAIL">
							<i id="' . md5($field->id_izin) . '" class="btn_detail fa fa-info-circle (alias) "> </i></a>&nbsp;
						<a href="#" class="text-warning" title="EDIT">
							<i id="' . md5($field->id_izin) . '" class="btn_edit fa fa-edit (alias) "> </i></a>&nbsp;
						<a href="#" class="text-danger" title="HAPUS">
							<i id="' . md5($field->id_izin) . '" class="btn_delete fa fa-trash"></i>
						</a>';
			} else {
				$row[] = '<a href="#" class="text-primary" title="DETAIL">
							<i id="' . md5($field->id_izin) . '" class="btn_detail fa fa-info-circle (alias) "> </i></a>&nbsp;';
			}


			$data[] = $row;
		}

		$output = array(
			"draw"            => $_POST['draw'],
			"recordsTotal"    => $recordsTotal,
			"recordsFiltered" => $recordsFiltered,
			"data"            => $data,
			// "query"			  => $query
		);

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

		echo json_encode($output);
	}

	public function form()
	{
		$data['judul'] = 'Tambah Pengajuan Izin';
		$data['aktif'] = 'izin';
		$data['ref'] = 0;
		$data['menu'] = $this->load->view('main_menu', $data, true);
		$data['content'] = $this->load->view('pengajuan_izin/form', $data, true);
		$this->load->view('main_template', $data, false);
	}

	public function edit($id = 0)
	{
		$data['judul'] = 'Ubah Pengajuan Izin';
		$data['aktif'] = 'izin';
		$data['data'] = $this->Pengajuan_izin_m->getDataById($id);
		$data['ref'] = $id;
		$data['menu'] = $this->load->view('main_menu', $data, true);
		$data['content'] = $this->load->view('pengajuan_izin/form', $data, true);
		$this->load->view('main_template', $data, false);
	}

	public function modal_verifikasi($level_verifikasi="-", $id_izin="-"){
		$data['data'] 	= $this->Pengajuan_izin_m->getDetailIzin($id_izin);
		$data['id'] 	= $id_izin;
		$data['level'] 	= $level_verifikasi;
		$this->load->view('pengajuan_izin/modal', $data);
	}


	public function save()
	{
		$this->load->library('Uploadfile');

		$id 			= $this->input->post('id_izin');
		$id_company 	= $this->session->userdata('id_company');
		$id_karyawan	= $this->input->post('karyawan');
		$id_cabang 		= $this->input->post('cabang');
		$id_jenis 		= $this->input->post('jenis');
		$foto_lama 		= $this->input->post('file_lama');
		$detail_master_izin = $this->Pengajuan_izin_m->detail_master_izin($id_jenis);
		$zona = $this->db->where('id_company', $id_company)->get('master_company')->row()->zona_waktu;

		if ($zona == 1) {
			date_default_timezone_set("Asia/Jakarta");
		} else if ($zona == 2) {
			date_default_timezone_set('Asia/Makassar');
		} else if ($zona == 3) {
			date_default_timezone_set('Asia/Jayapura');
		}
		$tanggal_mulai		= $this->input->post('tanggal_mulai');
		$tanggal_selesai	= $this->input->post('tanggal_selesai');
		$hari 			= $this->get_holidays_count($id_karyawan,$tanggal_mulai,$tanggal_selesai);
		$max_izin 		= (int)$detail_master_izin->max_izin;
		$izin_memotong	= $detail_master_izin->flag;
		$data_karyawan 	= $this->Pengajuan_izin_m->data_karyawan($id_karyawan);
		$jatah_cuti		= $data_karyawan->jatah_cuti;
		if($max_izin > 0 and $hari > $max_izin) {
			//jika terdapat max izin dan pengajuan melebihi max izin
			$message = '<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>Pengajuan izin melebihi batas maksimal</font>';
			return __response_save(false, array('message' => $message));
		} elseif($izin_memotong == '1' and $jatah_cuti < $hari and $id == null) {
			//jika izin memotong dan pengajuan izin melebihi sisa cuti
			$message = '<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>Pengajuan izin melebihi sisa cuti</font>';
			return __response_save(false, array('message' => $message));
		} else {
			$date = date("Ym");
			$time = date("dhis");

			$file1 = $_FILES['file'];
			if($file1['name'] == ""){
				$foto_file = $foto_lama;
			}else{
				$fileUpload['fname']    = 'file';
				$fileUpload['location'] = 'izin';
				$fileUpload['allowed']  = 'jpg|png|jpeg';
				$fileUpload['compress_image']  = true;
				$fileUpload['filename']  = preg_replace('/[^A-Za-z0-9\-]/', '', $no_induk_karyawan);

				$upload = $this->uploadfile->doUploadizin($fileUpload);
				if($upload["success"] == true){
					$foto_file = $upload['url'];
					if(!empty($foto_lama)){
						if($foto_profil != $foto_lama){
							$path = $this->config->item('base_upload_absensi').$foto_lama;
            				unlink($path);
						}
					}

				}else{
					$message = ["message"=>$upload["message"]];
					return __response_save(false,["params"=>$message]);
				}
			}

			$jenis_izin = $this->db_model->get('master_jenis_izin', 'nama, jenis_izin, max_izin', array('kode_izin' => $id_jenis, 'id_company' => $this->id_company))->row();
			$id_jabatan = $this->db_model->get('data_karyawan', 'id_jabatan', array('id_karyawan' => $id_karyawan))->row()->id_jabatan;
			$level_user = $this->db_model->get('master_jabatan', 'level_user', array('id_jabatan' => $id_jabatan))->row()->level_user;
			$approval = $this->db_model->get('p_approval_izin', 'level_approval', array('level_user' => $level_user, 'id_cabang' => $data_karyawan->id_cabang, 'id_company' => $id_company))->row()->level_approval;

			$data_approv = $this->fungsi->approved_data($approval);

			$data = array(
				'id_cabang'			=> $data_karyawan->id_cabang,
				'id_departemen'		=> $data_karyawan->id_departemen,
				'jenis_izin'		=> $jenis_izin->jenis_izin,
				'flag'				=> $izin_memotong,
				'jml_izin'			=> $hari,
				'kode_izin'			=> $id_jenis,
				'nama_izin'			=> $jenis_izin->nama,
				'id_karyawan'		=> $id_karyawan,
				'tgl_mulai_izin'    => date('Y-m-d', strtotime($this->input->post('tanggal_mulai'))),
				'tgl_selesai_izin'	=> date('Y-m-d', strtotime($this->input->post('tanggal_selesai'))),
				'file'     			=> $foto_file,
				'ket_izin'		   	=> $this->input->post('keterangan'),
				'user_hrd'			=> $this->id_karyawan,
				'tgl_apv_hrd'		=> date('Y-m-d H:i:s'),
				'id_company'		=> $id_company
			);

			if($id == null) {
				$data['status']	= '4';
			}

			if ($id != null) {
				$save = $this->Pengajuan_izin_m->save($data, $id);
			}else{
				$result = array_merge($data_approv, $data);
				$save = $this->Pengajuan_izin_m->save($result, $id);
			}

			if($save) {
				if($id != null) {
					//jika update
					return  __response_update($save);
				} else {
					if (!empty($foto_file)) {
						$this->insert_file_izin($foto_file);
						$this->insert_rekap($id_karyawan,$id_jenis, $jenis_izin->jenis_izin, $jenis_izin->nama, $tanggal_mulai, $tanggal_selesai, $izin_memotong);
						$this->insert_absensi_masuk($id_karyawan, $id_jenis, $jenis_izin->jenis_izin, $jenis_izin->nama, $tanggal_mulai, $tanggal_selesai);
					}else{
						$this->insert_rekap($id_karyawan,$id_jenis, $jenis_izin->jenis_izin, $jenis_izin->nama, $tanggal_mulai, $tanggal_selesai, $izin_memotong);
						$this->insert_absensi_masuk($id_karyawan, $id_jenis, $jenis_izin->jenis_izin, $jenis_izin->nama, $tanggal_mulai, $tanggal_selesai);
					}
					return  __response_save($save);
				}
			}
		}
	}

	public function delete()
	{
		$id = $this->input->post("id_izin");
		$this->Pengajuan_izin_m->delete($id);
	}
	//CRUD

	public function approve_izin(){
		$id_izin = $this->input->post('id');
		$con = $this->input->post('status');
		$res = $this->__approve_to_service($con, $id_izin);

		if ($res['status'] == true) {
			$color = '#009900';
			$icon = 'fa-check-square';
		} else {
			$color = '#eb3a28';
			$icon = 'fa-close';
		}

		$json['message'] = '<font color="'.$color.'"><i class="fa '.$icon.'">&nbsp;</i> '.$res['message'].'</font>';
		$json['success'] = $res['status'];

		$json = __response($this->MY_response, $json);
		echo json_encode($json);
	}

	private function __approve_to_service($act, $id_izin){
		$id_izin = $this->db->select('id_izin')->from('data_izin')->where('md5(id_izin)', $id_izin)->get()->row()->id_izin;
		$id_pengaprove = $this->session->userdata('id_karyawan');
		$id_company	   = $this->session->userdata('id_company');
		$base = $this->config->item('url_api');

		if($act == '4')
		{
			#setujui
			$url_act = $base.'/izin/setujui/'.$id_izin.'/'.$id_pengaprove.'/'.$id_company;
		}elseif($act == '3')
		{
			#tolak
			$url_act = $base.'/izin/tolak/'.$id_izin.'/'.$id_pengaprove;
		}else{
			$url_act = false;
		}

		// echo '<pre>'.var_export($url_act, true).'</pre>';
		// exit;

		if($url_act !== false)
		{
			$curl = curl_init();
			curl_setopt_array($curl, array(
			CURLOPT_URL => $url_act,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => '',
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 0,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => 'PATCH',
			));
			$response = curl_exec($curl);
			curl_close($curl);

			if($response != ''){
				$json = json_decode($response);

				$data['status'] = $json->success;
				$data['message'] = $json->message;

		// 		echo '<pre>'.var_export($data, true).'</pre>';
		// exit;
			}else{
				$data['status'] = false;
				$data['message'] = 'Request tidak diketahui';
			}
		}else{
			$data['status'] = false;
			$data['message'] = 'Request tidak diketahui';
		}

		return $data;
	}

	//DROPDOWn
	public function get_jenis($id = null)
	{
		$search = $this->input->get("q");
		$this->Pengajuan_izin_m->get_jenis($id, $search);
	}

	public function get_jenis_form($id = null)
	{
		$search = $this->input->get("q");
		$this->Pengajuan_izin_m->get_jenis_form($id, $search);
	}

	public function get_cabang($id = null)
	{
		$search = $this->input->get("q");
		$this->Pengajuan_izin_m->get_cabang($id, $search);
	}

	public function get_departemen($id = null)
	{
		$search = $this->input->get("q");
		$this->Pengajuan_izin_m->get_departemen($id, $search);
	}

	public function get_karyawan($cabang = null, $departemen = null)
	{
		$search = $this->input->get("q");
		$this->Pengajuan_izin_m->get_karyawan($cabang, $departemen, $search);
	}

	public function get_shift($id = null)
	{
		$search = $this->input->get("q");
		$this->Karyawan_m->get_shift($id, $search);
	}

	function get_holidays() {
		$id_karyawan 	= $this->input->get('id_karyawan');
		$date_start		= $this->input->get('date_start');
		$date_end		= $this->input->get('date_end');
		echo $this->get_holidays_count($id_karyawan, $date_start, $date_end);
	}

	function insert_rekap($id_karyawan, $id_jenis, $jenis_izin, $nama_izin, $date_start, $date_end, $flag_memotong_cuti) {
		//insert rekap untuk izin

		$this->load->library('fungsi');
		$data = $tanggal_arr = array();
		$date_start		= $this->fungsi->reverse_date2($date_start);
		$date_end		= $this->fungsi->reverse_date2($date_end);
		$start 			= new DateTime($date_start);
		$end 			= new DateTime($date_end);
		$detail_karyawan	= $this->Pengajuan_izin_m->detail_karyawan($id_karyawan);
		$potongan		= 0;
		$end->modify('+1 day');

		// create an iterateable period of date (P1D equates to 1 day)
		$period = new DatePeriod($start, new DateInterval('P1D'), $end);

		// best stored as array, so you can add more than one
		$holidays 		= $this->holidays_array($id_karyawan, $date_start, $date_end);
		$week_holidays	= "";
		$shift_off		= $this->Pengajuan_izin_m->shift_off($id_karyawan, $date_start, $date_end);
		if($shift_off->num_rows() == 0) {
			$week_holidays 	= $this->week_holidays_array($id_karyawan);
		}

		foreach($period as $dt) {
			$curr = $dt->format('N');

			if (!in_array($curr,$week_holidays) and !in_array($dt->format('Y-m-d'), $holidays)) {
				$data_rekap = array(
					'id_karyawan'	=> $id_karyawan,
					'nik'			=> $detail_karyawan->nik,
					'nama_karyawan'	=> $detail_karyawan->nama_karyawan,
					'id_cabang'		=> $detail_karyawan->id_cabang,
					'kode_cabang'	=> $detail_karyawan->kode_cabang,
					'nama_cabang'	=> $detail_karyawan->nama_cabang,
					'id_departemen'	=> $detail_karyawan->id_departemen,
					'kode_departemen'	=> $detail_karyawan->kode_departemen,
					'nama_departemen'	=> $detail_karyawan->nama_departemen,
					'id_jabatan'	=> $detail_karyawan->id_jabatan,
					'kode_jabatan'	=> $detail_karyawan->kode_jabatan,
					'nama_jabatan'	=> $detail_karyawan->nama_jabatan,
					'supervisi'		=> $detail_karyawan->supervisi == NULL ? '' : $detail_karyawan->supervisi,
					'nama_supervisi'	=> $detail_karyawan->nama_supervisi == NULL ? '' : $detail_karyawan->nama_supervisi,
					'tgl_absen'		=> $dt->format('Y-m-d'),
					'jenis_absen'	=> $jenis_izin,
					'kode_absensi'	=> $id_jenis,
					'ket_kode'		=> $nama_izin,
					'id_company'	=> $detail_karyawan->id_company
				);

				array_push($tanggal_arr, $dt->format('Y-m-d'));
				array_push($data, $data_rekap);

				if($flag_memotong_cuti == '1') {
					$potongan++;
				}
			}
		}

		$this->db->trans_start();
		$this->Pengajuan_izin_m->hapus_absensi($id_karyawan, $tanggal_arr);
		//insert rekap
		$this->db->insert_batch('r_absensi', $data);
		//jika potongan > 0 maka update jatah cuti
		if($potongan > 0) {
			$this->Pengajuan_izin_m->update_jatah_cuti($id_karyawan, $potongan);
		}
		$this->db->trans_complete();
	}

	function insert_absensi_masuk($id_karyawan, $id_jenis, $jenis_izin, $nama_izin, $date_start, $date_end) {
		//insert absensi masuk untuk izin

		$this->load->library('fungsi');
		$date_start		= $this->fungsi->reverse_date2($date_start);
		$date_end		= $this->fungsi->reverse_date2($date_end);
		$start 			= new DateTime($date_start);
		$end 			= new DateTime($date_end);
		$potongan		= 0;
		$end->modify('+1 day');

		// create an iterateable period of date (P1D equates to 1 day)
		$period = new DatePeriod($start, new DateInterval('P1D'), $end);

		// best stored as array, so you can add more than one
		$holidays 		= $this->holidays_array($id_karyawan, $date_start, $date_end);
		$week_holidays	= "";
		$shift_off		= $this->Pengajuan_izin_m->shift_off($id_karyawan, $date_start, $date_end);
		if($shift_off->num_rows() == 0) {
			$week_holidays 	= $this->week_holidays_array($id_karyawan);
		}

		foreach($period as $dt) {
			$curr = $dt->format('N');

			if (!in_array($curr,$week_holidays) and !in_array($dt->format('Y-m-d'), $holidays)) {

				$data_insert = array();

				$id_absensi_masuk = $this->fungsi->getNextId('absensi_masuk','id_absensi_masuk',$this->id_company,5);

				$tanggal1 = date('Y-m-d',strtotime($date_start));
				$tanggal2 = date('Y-m-d',strtotime($date_end));

				while ($tanggal1 <= $tanggal2) {
	        			$data_rekap = array(
						'id_absensi_masuk' => $id_absensi_masuk,
						'id_karyawan'	=> $id_karyawan,
						'tgl_absen'		=> $tanggal1,
						'jenis_absen'	=> $jenis_izin,
						'jam_kerja' 	=> '00:00:00',
						'jam_absen' 	=> '0000-00-00 00:00:00',
						'terlambat' 	=> '',
						'kode_absen'	=> $id_jenis,
						'ket_kode'		=> $nama_izin,
						'lokasi_absen' 	=> '',
						'timezone' 		=> '',
						'gmt' 			=> '',
						'latitude' 		=> '',
						'longitude' 	=> '',
						'keterangan' 	=> '',
						'foto'  		=> '',
						'id_company'	=> $this->id_company
					);
	        	$tanggal1 = date('Y-m-d',strtotime('+1 days',strtotime($tanggal1)));

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

				$data_insert[] = $data_rekap;

    			}
			}
		}

		$this->db->trans_start();
		//insert absensi_masuk
		$this->db->insert_batch('absensi_masuk', $data_insert);
		$this->db->trans_complete();
	}

	function insert_file_izin($foto_file) {
		$id_izin = $this->db->query("SELECT id_izin FROM data_izin WHERE file = '$foto_file'")->row()->id_izin;
		$data = array(
			'id_izin'		=> $id_izin,
			'file'  		=> $foto_file,
			'id_company' 	=>  $this->id_company
		);
		$this->db->trans_start();
		$this->db->insert('file_izin', $data);
		$this->db->trans_complete();
	}

	function get_holidays_count($id_karyawan, $date_start, $date_end) {
		//mendapatkan hari libur shift, nasional, dan libur kerja

		$this->load->library('fungsi');
		$date_start		= $this->fungsi->reverse_date2($date_start);
		$date_end		= $this->fungsi->reverse_date2($date_end);
		$start 			= new DateTime($date_start);
		$end 			= new DateTime($date_end);

		// otherwise the  end date is excluded (bug?)
		$end->modify('+1 day');

		$interval = $end->diff($start);

		// total days
		$days = $interval->days;

		// create an iterateable period of date (P1D equates to 1 day)
		$period = new DatePeriod($start, new DateInterval('P1D'), $end);

		// best stored as array, so you can add more than one
		$holidays 		= $this->holidays_array($id_karyawan, $date_start, $date_end);
		$week_holidays	= "";
		$shift_off		= $this->Pengajuan_izin_m->shift_off($id_karyawan, $date_start, $date_end);
		if($shift_off->num_rows() == 0) {
			$week_holidays 	= $this->week_holidays_array($id_karyawan);
		}

		foreach($period as $dt) {
			$curr = $dt->format('N');

			// substract if in week holidays
			if (in_array($curr,$week_holidays)) {
				$days--;
			}

			// (optional) for the updated question
			elseif (in_array($dt->format('Y-m-d'), $holidays)) {
				$days--;
			}
		}

		return $days; // 4
	}

	function holidays_array($id_karyawan, $date_start, $date_end) {
		$holidays_temp 	= $this->Pengajuan_izin_m->get_holidays($date_start, $date_end);
		$shift_off		= $this->Pengajuan_izin_m->shift_off($id_karyawan, $date_start, $date_end);

		$holidays = array();
		foreach($holidays_temp->result() as $row) {
			array_push($holidays, $row->tanggal);
		}

		foreach($shift_off->result() as $row) {
			if(!in_array($row->tanggal, $holidays)) {
				array_push($holidays, $row->tanggal);
			}
		}
		return $holidays;
	}

	function week_holidays_array($id_karyawan) {
		$week_holidays 	= $this->Pengajuan_izin_m->week_holidays($id_karyawan);
		$holidays 		= array();
		if($week_holidays->num_rows() > 0) {
			foreach($week_holidays->result() as $row) {
				array_push($holidays, $row->hari);
			}
		}

		return $holidays;
	}
}
