<?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');
		$this->load->model('Master_plan_m');

		$this->level_user           = $this->session->userdata('level_user');
        $this->id_company           = $this->session->userdata('id_company');
        $this->multi_cabang         = $this->session->userdata('multi_cabang');
        $this->id_cabang            = $this->session->userdata('id_cabang');
        $this->id_cabang_arr        = $this->session->userdata('id_cabang_arr');
        $this->multi_departemen     = $this->session->userdata('multi_departemen');
        $this->id_departemen        = $this->session->userdata('id_departemen');
        $this->id_departemen_arr    = $this->session->userdata('id_departemen_arr');
        $this->id_karyawan          = $this->session->userdata('id_karyawan');
	}

	public function index(){
		$data['judul'] = '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['button_sso'] = $this->Master_plan_m->button_sso();
		$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;
		$data['header'] 		= $this->buat_tabel_header($tanggal_mulai, $tanggal_selesai);
		$data['usergroup'] 		= $this->level_user;
		$this->load->view('rekap_absensi/list_data', $data, false);
	}

	function buat_tabel_header($mulai, $selesai)
	{
		$akhir		= date_create($selesai);
		$awal 		= date_create($mulai);
		$selisih 	= date_diff($akhir, $awal)->format("%a");
		$hasil 		= array();
		$d 			= "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) {
			$hasil[] = indo_date($dt->format("Y-m-d"), $d);
		}
		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;

			$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;
				// $row[] = $kode_absensi;

				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;
							}
						}
					} 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['TAP']; //$field->AP;
			$row[] = $rkp['Izin']; //$field->I;
			$row[] = $rkp['Sakit']; //$field->S;
			$row[] = $rkp['Cuti']; //$field->C;
			$row[] = $rkp['Alpha']; //$field->A;
			$row[] = $rkp['Libur']; //$field->L;
			// $list[$key]->menit_t = ;

			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'){
		$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 		  = "Cabang " . $nama_cab . ", Departemen " . str_replace("/","-",$nama_dep);
			$filename 	  = "Rekap Absensi " . $nama;
		} else {
			if($id_cabang != 0) {
				$nama 	  = $this->rekap_absen->nama_cabang($id_cabang);
				$filename = "Rekap Absensi Cabang " . $nama . " Semua Departemen";
			} else {
				$nama 	  = "";
				$filename = "Rekap Absensi Semua Cabang";
			}
		}
		$header = $this->buat_tabel_header($tgl_mulai, $tgl_selesai);
		$colspan = count($header) + 12;
		$data['colspan'] = $colspan;
		$data['header'] = $header;
		$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;

			#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;
				$absen[] = $kode_absensi;

				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;
							}
						}
					} else {
						if (strtoupper($k) === strtoupper($jenis_absen)) {
							$rkp[$k] += 1;
						}
					}
				}
			}

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

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

			$list[$key]->H = $rkp['H'];
			$list[$key]->T = $rkp['T']." Kali (".$rkp['menit_t']." Menit)";
			$list[$key]->PC = $rkp['PC']." Kali (".$rkp['menit_pc']." Menit)";
			$list[$key]->TAP = $rkp['TAP'];
			$list[$key]->Izin = $rkp['Izin'];
			$list[$key]->Sakit = $rkp['Sakit'];
			$list[$key]->Cuti = $rkp['Cuti'];
			$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;
			$c_length = 13 + $tcol;

			$param = [
				'download' => true,
				'cLength'    => $c_length,
				'file_name'    => strtoupper($filename),
				'paper_size'	=> 'LEGAL',
				'font-size'		=> 9,
				// 'pagebreak'		=> true,
				'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'	   => ['O6'],
				'thead'        => ['4', '5'],
				'tbody'        => [
					'start' => '4',
					'height'	=> 13,
					// 'runFunction'	=> ['highlightlibur' => 'P'],
					'wrap' => ['B', 'C','D','E'],
					'column' => [
						'A'    => ['width' => 5, 'align' => 'center', 'valign' => 'middle'],
						'B'    => ['width' => 10, 'align' => 'center', 'valign' => 'middle', 'format'=>'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],

						// 'D'    => ['width' => 15, 'align' => 'center', 'valign' => 'top'],

						// 'E'    => ['width' => 6, 'align' => 'center', 'valign' => 'top'],
					],
				],
			];
			$this->load->library('PHPExcel/Excel');
			if ($tcol > 0) {
				$sd = $tcol + 13;
				for ($i = 14; $i <= $sd; $i++) {
					$wd = 15;
					$param['tbody']['column'][strtoupper($this->excel->al($i))] = ['width' => $wd, 'align' => 'center', 'valign' => 'top'];
					// $ar[$this->excel->al($i)] = ['width' => 15, 'align' => 'center', 'valign' => 'top'];
				}
			}

			// 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;
	}
}
