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

class Rekap_absensi extends MY_Controller
{

	public function __construct()
	{
		parent::__construct();

		$this->load->model('Rekap_absensi_m', 'rekap_absen');
	}

	public function index(){
		$data['judul'] = $this->lang->line('menu_rekap_absensi');
		$data['aktif'] = 'rekap_absensi';
		$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['level_user'] = $this->level_user;
		$data['multi_cabang'] = $this->multi_cabang;
		$data['multi_departemen'] = $this->multi_departemen;
		$data['menu'] = $this->load->view('main_menu', $data, true);
		$data['content'] = $this->load->view('rekap_absensi/main', $data, true);
		$this->load->view('main_template', $data, false);
	}

	public function view_data($mulai=0, $selesai=0, $id_cabang=0, $id_departemen=0)
	{
		$data['judul']      	= 'Laporan Absensi';
		$data['aktif']      	= 'rekap_absensi';
		$data['cabang']     	= $id_cabang;
		$data['departemen']		= $id_departemen;
		$data['mulai']  		= date('Y-m-d', strtotime($mulai));
		$data['selesai']  		= date('Y-m-d', strtotime($selesai));
		$tanggal_mulai 			= date('Y-m-d', strtotime($mulai));
		$tanggal_selesai		= date('Y-m-d', strtotime($selesai));

		$tgl_mulai 				= date_create($tanggal_mulai);
		$tgl_selesai			= date_create($tanggal_selesai);

		$diff                       = date_diff($tgl_mulai, $tgl_selesai);
		$data['jumlah']             = ($diff->format("%a%"))+1;
		$header                     = $this->buat_tabel_header($tanggal_mulai, $tanggal_selesai, $id_cabang);
		$data['header']             = $header['data_tanggal'];
		$data['targets_libur_left'] = $header['targets_libur_left'];
		$data['targets_libur_sisa'] = $header['targets_libur_sisa'];
		$data['usergroup']          = $this->level_user;
		if ($this->paket_arr['flexible_jam_kerja'] == true) {
			$data['colspan']          = 8;
		}else{
			$data['colspan']          = 10;
		}
		$this->load->view('rekap_absensi/list_data', $data, false);
	}

	function buat_tabel_header($mulai, $selesai, $id_cabang)
	{
		$this->load->model('Pengaturan_shift_m');
		$this->load->helper('datatables');
		$this->load->config('excel');

		$m_jam_kerja_libur = ["6", "7"];
        $m_libur_nasional  = $this->Pengaturan_shift_m->m_libur_nasional($mulai, $selesai);

		$akhir		= date_create($selesai);
		$awal 		= date_create($mulai);
		$selisih 	= date_diff($akhir, $awal)->format("%a");
		$hasil   = [
            'data_tanggal'  => [],
            'targets_libur' => []
        ];
        if ($this->paket_arr['flexible_jam_kerja'] == true) {
			$kolom = 11;
        }else{
			$kolom = 13;
        }
		$d     = "l-d M";

		$akhir		= date_create(date('Y-m-d', strtotime('+1 days ' . $selesai)));
		$interval = DateInterval::createFromDateString('1 day');
		$period = new DatePeriod($awal, $interval, $akhir);
		foreach ($period as $dt) {
			$Y_m_d   = $dt->format("Y-m-d");
            $tanggal = indo_date($Y_m_d, $d);
            $tanggal = str_replace("-", "<br>", $tanggal);
            $temp    = [
                'tanggal_view' => $tanggal,
                'tanggal'      => $Y_m_d,
                'libur'        => false,
                'warna'        => '',
                'warna_teks'   => ''
            ];

            if(in_array($dt->format("N"), $m_jam_kerja_libur) or in_array($Y_m_d, $m_libur_nasional)) {
                $temp['libur'] = true;
                $temp['warna'] = $this->config->item('warna_background_libur');
                $temp['warna_teks'] = $this->config->item('warna_teks_libur');

                $hasil['targets_libur'][] = $kolom;
            }

            $hasil['data_tanggal'][] = $temp;
            $kolom++;
		}
		$targets_libur               = targets_libur($hasil['targets_libur']);
        $hasil['targets_libur_left'] = implode(", ", $targets_libur['left']);
        $hasil['targets_libur_sisa'] = implode(", ", $targets_libur['sisa']);
		return $hasil;
	}

	function list_data($tanggal_mulai, $tanggal_selesai, $cabang = 0, $departemen = 0){

		$date_now 	= date("Y-m-d");
		$nm_kode	= $this->rekap_absen->getNmKode();

		$akhir		= date_create($tanggal_selesai);
		$awal 		= date_create($tanggal_mulai);
		$selisih 	= date_diff($akhir, $awal)->format("%a");

		$list = $this->rekap_absen->get_datatables($tanggal_mulai, $tanggal_selesai, $cabang, $departemen);
		$ambil_absen = $this->rekap_absen->data_absensi_arr($tanggal_mulai, $tanggal_selesai, $cabang, $departemen);
		$data 	= array();
		$no 	= $_POST['start'];
		foreach ($list as $field) {

			$no++;
			$row = array();
			$id_karyawan = $field->id_karyawan; //$temp[$keys[0]];

			$row[] = $no;
			$row[] = $field->nama_karyawan . '<br>' . $field->nik;
			$row[] = $field->kode_cabang.' - '.$field->nama_cabang . '<br>' . $field->kode_departemen.' - '.$field->nama_departemen;

			$rkp['H'] = 0;
			$rkp['T'] = 0;
			$rkp['PC'] = 0;
			$rkp['TAP'] = 0;
			$rkp['Izin'] = 0;
			$rkp['Sakit'] = 0;
			$rkp['Cuti'] = 0;

			$rkp['Alpha'] = 0;
			$rkp['Libur'] = 0;

			$rkp['menit_t'] = 0;
			$rkp['menit_pc'] = 0;

			$arr_jam_masuk  = array();
			$arr_jam_pulang = array();

			$akhir		= date_create(date('Y-m-d', strtotime('+1 days ' . $tanggal_selesai)));
			$interval = DateInterval::createFromDateString('1 day');
			$period = new DatePeriod($awal, $interval, $akhir);
			foreach ($period as $dt) {

				$tgg = $dt->format("Y-m-d");
				$key_absensi = $id_karyawan.$dt->format("Y-m-d");
				$res = array_search($key_absensi, array_column($ambil_absen, 'key_absensi'));

				$res = ($res !== false) ? $ambil_absen[$res] : null;
				$kode_absensi = ($res['tgl_absen'] !== null) ? $res['kode_absensi'] : '-';
				$jenis_absen = ($res['tgl_absen'] !== null) ? $res['jenis_absen'] : null;
				$pulang_cepat = ($res['tgl_absen'] !== null) ? $res['pulang_cepat'] : 0;
				// $row[] = $kode_absensi;

				//star total jam kerja
				$absen_masuk  = ($res['tgl_absen'] !== null) ? strtotime($res['absen_masuk']) : '-';
                $absen_pulang = ($res['tgl_absen'] !== null) ? strtotime($res['absen_pulang']) : '-';

                if ($absen_pulang == '-62170009632' || $absen_pulang == false || $res['absen_pulang'] == '0000-00-00 00:00:00') {
                    $absen_pulang1 = $absen_masuk;
                }else{
                    $absen_pulang1 = $absen_pulang;
                }

                array_push($arr_jam_masuk, $absen_masuk);
                $total_jam_masuk = (array_sum($arr_jam_masuk));

                array_push($arr_jam_pulang, $absen_pulang1);
                $total_jam_pulang = (array_sum($arr_jam_pulang));
                //end total jam kerja

				foreach ($rkp as $k => $v) {

					if (in_array($jenis_absen, ['reguler', 'shift'])) {
						if (strtoupper($k) === strtoupper('H')) {
							$rkp[$k] += 1;
						} else {
							$exp_kode_absensi = explode(',', str_replace(['(', ')'], '', trim($kode_absensi)));

							if (in_array($k, $exp_kode_absensi)) {
								if($k == "T"){
									$rkp['menit_t'] = $rkp['menit_t'] + $res['terlambat'];
								}

								if($k == "PC"){
									$rkp['menit_pc'] = $rkp['menit_pc'] + $res['pulang_cepat'];
								}

								$rkp[$k] += 1;
							}
						}

						if($tgg == $date_now AND $k == 'menit_pc' AND $pulang_cepat > 0 ){
							$rkp['menit_pc'] = $rkp['menit_pc'] + $res['pulang_cepat'];
							$rkp['PC'] = $rkp['PC'] + 1;
						}
					} else {
						if (strtoupper($k) === strtoupper($jenis_absen)) {
							$rkp[$k] += 1;
						}
					}
				}
			}

			$row[] = $rkp['H']; //$field->H;
			// $row[] = $rkp['T']." Kali (".$rkp['menit_t']." Menit)";; //$field->T;
			// $row[] = $rkp['PC']." Kali (".$rkp['menit_pc']." Menit)";; //$field->PC;
			$row[] = $rkp['T']
						." "
						.$this->lang->line('kali')
						." (".$rkp['menit_t']
						." "
						.$this->lang->line('menit') 
						.")"; 
						//$field->T;
			$row[] = $rkp['PC']
						." "
						.$this->lang->line('kali')
						." (".$rkp['menit_pc']
						." "
						.$this->lang->line('menit') 
						.")"; 
						//$field->PC;
			$row[] = $rkp['TAP']; //$field->AP;
			$row[] = $rkp['Izin']; //$field->I;
			$row[] = $rkp['Sakit']; //$field->S;
			$row[] = $rkp['Cuti']; //$field->C;
			if ($this->paket_arr['flexible_jam_kerja'] == false) {
				$row[] = $rkp['Alpha']; //$field->A;
				$row[] = $rkp['Libur']; //$field->L;
			}
			// $list[$key]->menit_t = ;

			//star total jam kerja
			$diff  = $total_jam_pulang - $total_jam_masuk;
            $jam   = floor($diff / (60 * 60));
            $menit = $diff - ( $jam * (60 * 60) );

            $row[] = $jam. ' '. $this->lang->line('jam'). ' '. floor($menit/60). ' '. $this->lang->line('menit');
            //end total jam kerja

			foreach ($period as $dt) {
				$tgg = $dt->format("Y-m-d");
				$key_absensi = $id_karyawan.$dt->format("Y-m-d");
				$res = array_search($key_absensi, array_column($ambil_absen, 'key_absensi'));
				$res = ($res !== false) ? $ambil_absen[$res] : null;
				$kode_absensi = ($res['tgl_absen'] !== null) ? $res['kode_absensi'] : '-';
				if($kode_absensi == "-"){
					$kode_absensi = $kode_absensi;
				}else{
					$split_kode = explode(",",$kode_absensi);
					$kode_absensi = "";
					foreach($split_kode as $a=>$kode){
						if($a != "0"){
							$kode_absensi .= ", ";
						}
						$kd = str_replace(['(', ')'],'',trim($kode));
						$kode_absensi .= '<a data-toggle="tooltip" title="'.$nm_kode[$kd].'" style="cursor:pointer; color:#434343">'.$kode.'</a>';
					}
				}
				$jenis_absensi = ($res['tgl_absen'] !== null) ? $res['jenis_absen'] : null;
				$row[] = $kode_absensi."<span style='display:none'>".$jenis_absensi."</span>";
			}

			$data[] = $row;
		}

		$recordsTotal = $this->rekap_absen->count_all($tanggal_mulai, $tanggal_selesai, $cabang, $departemen);

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

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

		echo json_encode($output);
	}

	function download($tgl_mulai, $tgl_selesai, $id_cabang=0, $id_departemen=0, $jenis='excel'){
		$this->load->helper('excel');
		
		$date_now = date('Y-m-d');

		if ($id_departemen != "0") {
			$nama_cab 	  = $this->rekap_absen->nama_cabang($id_cabang);
			$nama_dep 	  = $this->rekap_absen->nama_departemen($id_departemen);
			$nama 		  = $this->lang->line('cabang_for_download'). " ". $nama_cab. ", ". $this->lang->line('departemen_for_download'). " ". str_replace("/","-",$nama_dep);
			$filename 	  = $this->lang->line('rekap_abs_for_download'). " ". $nama;
		} else {
			if($id_cabang != 0) {
				$nama 	  = $this->rekap_absen->nama_cabang($id_cabang);
				$filename = $this->lang->line('rekap_abs_for_download')." ". $this->lang->line('cabang_for_download'). " " . $nama . " ". $this->lang->line('semua_departemen');
			} else {
				$nama 	  = " ". $this->lang->line('semua_cabang');
				$filename = $this->lang->line('rekap_abs_for_download'). " ". $this->lang->line('semua_cabang');
			}
		}
		$header = $this->buat_tabel_header($tgl_mulai, $tgl_selesai, $id_cabang);
		$colspan = count($header['data_tanggal']) + 12;
		$data['colspan'] = $colspan;
		$data['header'] = $header['data_tanggal'];
		$data['nama'] = $nama;
		$data['tanggal_mulai'] 		= date('d-m-Y', strtotime($tgl_mulai));
		$data['tanggal_selesai'] 	= date('d-m-Y', strtotime($tgl_selesai));

		$data['jenis']	= $jenis;

		$awal			= date_create($tgl_mulai);
		$akhir 			= date_create($tgl_selesai);
		$data['jumlah']	= date_diff($akhir, $awal)->format("%a");

		$list = $this->rekap_absen->get_datatables($tgl_mulai, $tgl_selesai, $id_cabang, $id_departemen);
		$ambil_absen = $this->rekap_absen->data_absensi_arr($tgl_mulai, $tgl_selesai, $id_cabang, $id_departemen);

		$addcol = [];

		foreach ($list as $key => $value) {
			$id_karyawan = $value->id_karyawan;


			$rkp['H'] = 0;
			$rkp['T'] = 0;
			$rkp['PC'] = 0;
			$rkp['TAP'] = 0;
			$rkp['Izin'] = 0;
			$rkp['Sakit'] = 0;
			$rkp['Cuti'] = 0;
			$rkp['Alpha'] = 0;
			$rkp['Libur'] = 0;

			$rkp['menit_t'] = 0;
			$rkp['menit_pc'] = 0;

			$arr_jam_masuk  = array();
			$arr_jam_pulang = array();

			#manipulasi tanggal akhir

			$akhir		= date_create(date('Y-m-d', strtotime('+1 days ' . $tgl_selesai)));
			$interval = DateInterval::createFromDateString('1 day');
			$period = new DatePeriod($awal, $interval, $akhir);

			$absen = [];
			$acol = 0;
			foreach ($period as $dt) {
				$acol += 1;

				$tgg = $dt->format("Y-m-d");
				$key_absensi = $id_karyawan.$dt->format("Y-m-d");
				$res = array_search($key_absensi, array_column($ambil_absen, 'key_absensi'));

				$res = ($res !== false) ? $ambil_absen[$res] : null;
				// $res['tgl_absen'].'<br>'.
				$kode_absensi = ($res['tgl_absen'] !== null) ? $res['kode_absensi'] : '-';
				$jenis_absen = ($res['tgl_absen'] !== null) ? $res['jenis_absen'] : null;
				$pulang_cepat = ($res['tgl_absen'] !== null) ? $res['pulang_cepat'] : 0;
				$absen[] = $kode_absensi;

				// start total jam kerja
				$absen_masuk  = ($res['tgl_absen'] !== null) ? strtotime($res['absen_masuk']) : '-';
				$absen_pulang = ($res['tgl_absen'] !== null) ? strtotime($res['absen_pulang']) : '-';


                if ($absen_pulang == '-62170009632' || $absen_pulang == false || $res['absen_pulang'] == '0000-00-00 00:00:00') {
					$absen_pulang1 = $absen_masuk;
				}else{
					$absen_pulang1 = $absen_pulang;
				}

				array_push($arr_jam_masuk, $absen_masuk);
                $total_jam_masuk = (array_sum($arr_jam_masuk));

                array_push($arr_jam_pulang, $absen_pulang1);
                $total_jam_pulang = (array_sum($arr_jam_pulang));
				// end total jam kerja

				foreach ($rkp as $k => $v) {
					// $rkp[$k] += $res['terlambat'];
					if (in_array($jenis_absen, ['reguler', 'shift'])) {
						if (strtoupper($k) === strtoupper('H')) {
							$rkp[$k] += 1;
						} else {
							$exp_kode_absensi = explode(',', str_replace(['(', ')'], '', trim($kode_absensi)));

							if (in_array($k, $exp_kode_absensi)) {
								if($k == "T"){
									$rkp['menit_t'] = $rkp['menit_t'] + $res['terlambat'];
								}

								if($k == "PC"){
									$rkp['menit_pc'] = $rkp['menit_pc'] + $res['pulang_cepat'];
								}
								$rkp[$k] += 1;
							}
						}

						if($tgg == $date_now AND $k == 'menit_pc' AND $pulang_cepat > 0 ){
							$rkp['menit_pc'] = $rkp['menit_pc'] + $res['pulang_cepat'];
							$rkp['PC'] = $rkp['PC'] + 1;
						}
					} else {
						if (strtoupper($k) === strtoupper($jenis_absen)) {
							$rkp[$k] += 1;
						}
					}
				}
			}

			if (count($addcol) == 0) {
				$addcol[] = $acol;
			}

			$list[$key]->kode_absen = (isset($absen)) ? $absen : null;

			// star total jam kerja
			$diff  = $total_jam_pulang - $total_jam_masuk;
			$jam   = floor($diff / (60 * 60));
			$menit = $diff - ( $jam * (60 * 60) );

			$list[$key]->ttl_jam_kerja = $jam  .  ' jam ' . floor($menit / 60 ) . ' menit';
			// end total jam kerja

			$list[$key]->H 		= $rkp['H'];
			$list[$key]->T 		= $rkp['T']
									." "
									.$this->lang->line('kali')
									." (".$rkp['menit_t']
									." "
									.$this->lang->line('menit') 
									.")";

			$list[$key]->PC 	= $rkp['PC']
									." "
									.$this->lang->line('kali')
									." (".$rkp['menit_pc']
									." "
									.$this->lang->line('menit') 
									.")"; 

			$list[$key]->TAP 	= $rkp['TAP'];
			$list[$key]->Izin 	= $rkp['Izin'];
			$list[$key]->Sakit 	= $rkp['Sakit'];
			$list[$key]->Cuti 	= $rkp['Cuti'];
			if ($this->paket_arr['flexible_jam_kerja'] == false) {
				$list[$key]->Alpha 	= $rkp['Alpha'];
				$list[$key]->Libur 	= $rkp['Libur'];
			}

		}


		$data['data'] = $list;

		$output = true;

		if ($jenis == "excel") {
			$data['is_excel'] = true;
			$sb_view = $this->load->view('rekap_absensi/download', $data, $output);
			$tcol    = (isset($addcol[0])) ? $addcol[0] : 0;

			if ($this->paket_arr['flexible_jam_kerja'] == true) {

				$p_kolom = 12;

				$column = [
					'A'    => ['width' => 5, 'align' => 'center', 'valign' => 'middle'],
					'B'    => ['width' => 15, 'align' => 'center', 'valign' => 'middle', 'format'=>'text', 'bentuk'=>'bentuk-text'],
					'C'    => ['width' => 30],
					'F'    => ['align' => 'center', 'width' => 5],
					'G'    => ['align' => 'center', 'width' => 16],
					'H'    => ['align' => 'center', 'width' => 16],
					'I'    => ['align' => 'center', 'width' => 5],
					'J'    => ['align' => 'center', 'width' => 5],
					'K'    => ['align' => 'center', 'width' => 5],
					'L'    => ['align' => 'center', 'width' => 5],
					'M'    => ['align' => 'center', 'width' => 15]
				];

				$freezecolumn = 'N';
			}else{

				$p_kolom = 14;

				$column = [
					'A'    => ['width' => 5, 'align' => 'center', 'valign' => 'middle'],
					'B'    => ['width' => 15, 'align' => 'center', 'valign' => 'middle', 'format'=>'text', 'bentuk'=>'bentuk-text'],
					'C'    => ['width' => 30],
					'F'    => ['align' => 'center', 'width' => 5],
					'G'    => ['align' => 'center', 'width' => 16],
					'H'    => ['align' => 'center', 'width' => 16],
					'I'    => ['align' => 'center', 'width' => 5],
					'J'    => ['align' => 'center', 'width' => 5],
					'K'    => ['align' => 'center', 'width' => 5],
					'L'    => ['align' => 'center', 'width' => 5],
					'M'    => ['align' => 'center', 'width' => 5],
					'N'    => ['align' => 'center', 'width' => 5],
					'O'    => ['align' => 'center', 'width' => 15]
				];

				$freezecolumn = 'P';
				
			}

			$c_length = $p_kolom + $tcol;

			$column = kolom_highlight_libur($column, $header['data_tanggal'], $tgl_mulai, $tgl_selesai, $id_cabang, 5);

			$param = [
				'download'    => true,
				'cLength'     => $c_length,
				'file_name'   => strtoupper($filename),
				'paper_size'  => 'LEGAL',
				'font-size'   => 9,
				'page_margin' => ['top' => 0, 'right' => 0.75, 'left' => 0.75, 'botom' => 0],
				'orientation' => 'landscape',
				'header'      => [
					'1' => ['merge' => true, 'align' => 'center', 'weight' => 'bold'],
					'2' => ['merge' => true, 'align' => 'center', 'weight' => 'bold'],
					'3' => ['merge' => true, 'align' => 'center', 'weight' => 'bold'],
				],
				'freezecolumn' => [$freezecolumn.'6'],
				'thead'        => ['4', '5'],
				'tbody'        => [
					'start'  => '4',
					'height' => 13,
					'wrap'   => ['B', 'C','D','E'],
					'column' => $column,
					'row'    => [
						5 => ['height' => 30]
					]
				],
			];
			$this->load->library('PHPExcel/Excel');
			if ($tcol > 0) {
				$sd = $tcol + $p_kolom;
				for ($i = $p_kolom; $i <= $sd; $i++) {
					$key   = strtoupper($this->excel->al($i));
					$style = ['width' => 15, 'align' => 'center', 'valign' => 'top'];
					if(array_key_exists($key, $param['tbody']['column'])) {
						$param['tbody']['column'][$key] = array_merge($param['tbody']['column'][$key], $style);
					} else {
						$param['tbody']['column'][$key] = $style;
					}
				}
			}

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

			if ($output) {
				$this->excel->generateExcel($sb_view, $param);
			}
		} else {
			$html = $this->load->view('rekap_absensi/download', $data, $output);

			if ($output) {

				$this->load->library('mpdf');
				$param['page_number'] = true;
				$param['show_watermark'] = false;
				$param['custom_font'] = false;
				$param['download']	= false;
				$this->mpdf->generate($html,  $filename, 'LEGAL', 'L', $param);
			}
		}
	}

	function nama_file($jenis, $id)
	{
		if ($jenis == "excel_per_opd" or $jenis == "pdf_per_opd") {
			$result = $this->rekap_absen->nama_opd($id);
		} else {
		}

		return $result;
	}
}
