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

class Pengaturan_shift_import extends MY_Controller {

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

	public function index(){
		$data['judul'] = 'Import Shift';
		$data['aktif'] = 'pengaturan_shift';


        $data['menu'] = $this->load->view('main_menu', $data, true);
		$data['content'] = $this->load->view('pengaturan/pengaturan_shift/import/home', $data, true);
		$this->load->view('main_template', $data, false);
	}

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

	public function view_data(){
		$ttl_periode = $this->Pengaturan_shift_import_m->getCountPeriodeShift();
		$data['ttl_periode'] = $ttl_periode;

		if($ttl_periode > 0){
			$periode = $this->Pengaturan_shift_import_m->getPeriodeShift();
			$tgl_mulai = $periode->tgl_mulai;
			$tgl_selesai = $periode->tgl_selesai;

			$kolom_header = $this->__kolom_periode($tgl_mulai, $tgl_selesai);
			$data['kolom_header'] = $kolom_header;
		}
		$this->load->view('pengaturan/pengaturan_shift/import/list_data',$data);
	}

	public function list_data(){
		$periode = $this->Pengaturan_shift_import_m->getPeriodeShift();
		$tgl_mulai = $periode->tgl_mulai;
		$tgl_selesai = $periode->tgl_selesai;
		$kolom_header = $this->__kolom_periode($tgl_mulai, $tgl_selesai);

		$data_shift = $this->Pengaturan_shift_import_m->getDataShift();

		$list = $this->Pengaturan_shift_import_m->get_datatables();
		$data = array();
		$no = $_POST['start'];
		foreach ($list as $field) {
			$no++;
			$row = array();
			$row[] = $no;
			$row[] = $field->nama_lengkap."<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;

			foreach($kolom_header as $tanggal){
				$tgl_shift = date_format(date_create($tanggal),"Y-m-d");
				$kode_shift = $data_shift[$field->id_karyawan."-".$tgl_shift]["kode_shift"];
				$flag = $data_shift[$field->id_karyawan."-".$tgl_shift]["flag"];

				if($flag == "2"){
					if(!empty($kode_shift)){
						$class = "badge badge-warning";
					}else{
						$class = "badge badge-danger";
						$kode_shift = "Data Kosong";
					}

				}else if($flag == "3"){
					$class = "badge badge-warning";
				}else if($flag == "4"){
					$class = "badge badge-success";
				}else{
					$class = "";
				}

				$row[] = "<div class='".$class."'>".$kode_shift."</div>";
			}


			$data[] = $row;
		}

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

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

		echo json_encode($output);
	}

	private function __kolom_periode($tgl_mulai="-", $tgl_selesai="-"){
		$awal		= date_create($tgl_mulai);
		$akhir 		= date_create($tgl_selesai);
		$selisih 	= date_diff($akhir, $awal)->format("%a");
		$d 			= "d M";

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

		$header		= array();
		foreach ($period as $dt) {
			$header[] = $dt->format("d-m-Y");
		}

		return $header;
	}

	function download_template($tgl_mulai="-", $tgl_selesai="-", $id_cabang="-", $id_departemen="-"){

		$nama_cabang = $this->db->select("nama")
								->from("master_cabang")
								->where("id_cabang",$id_cabang)
								->where("id_company",$this->id_company)
								->get()
								->row("nama");

		if($id_departemen != "-") {
			$nama_departemen = $this->db->select("nama")
								->from("master_departemen")
								->where("id_departemen",$id_departemen)
								->where("id_company",$this->id_company)
								->get()
								->row("nama");
			$filename 		  = "Template Import Shift Cabang " . $nama_cabang . " Departemen " . $nama_departemen;
		}else{
			$filename = "Template Import Shift Cabang " . $nama_cabang . " Semua Departemen";
		}

		$header = $this->__kolom_periode($tgl_mulai,$tgl_selesai);

		$colspan = count($header) + 7;
		$data['colspan'] = $colspan;
		$data['header'] = $header;
		$data['nama'] = $filename;
		$data['tanggal_mulai'] 		= date('d-m-Y', strtotime($tgl_mulai));
		$data['tanggal_selesai'] 	= date('d-m-Y', strtotime($tgl_selesai));

		$data['jumlah']	= count($header);

		$data_karyawan = $this->Pengaturan_shift_import_m->getDataKaryawan($id_cabang, $id_departemen);

		$data['data'] = $data_karyawan;

		$output = true;
		$data['is_excel'] = true;
		$sb_view = $this->load->view('pengaturan/pengaturan_shift/import/download', $data, $output);

		$param = [
			'download' => true,
			'cLength'    => $colspan,
			'file_name'    => strtoupper($filename),
			'paper_size'	=> 'A4',
			'font-size'		=> 12,
			// 'pagebreak'		=> true,
			'page_margin'	=> ['top' => 0, 'right' => 0.75, 'left' => 0.75, 'botom' => 0],
			'orientation'	=> 'potrait',
			'header'    => [
				'1' => ['merge' => true, 'align' => 'center', 'weight' => 'bold'],
				'2' => ['merge' => true, 'align' => 'center', 'weight' => 'bold'],
				'3' => ['merge' => true, 'align' => 'center', 'weight' => 'bold'],
				'4' => ['merge' => true, 'align' => 'center', 'weight' => 'bold'],
			],
			'freezecolumn'	   => ['D7'],
			'thead'        => ['5', '6'],
			'tbody'        => [
				'start' => '5',
				'height'	=> 13,
				// 'runFunction'	=> ['highlightlibur' => 'P'],
				'wrap' => ['B', 'C'],
				'column' => [
					'A'    => ['width' => 5, 'align' => 'center', 'valign' => 'middle'],
					'B'    => ['width' => 10, 'align' => 'center', 'valign' => 'middle','format'=>'text'],
					'C'    => ['width' => 40],
					'D'    => ['width' => 20],
					'E'    => ['width' => 20],
					'F'    => ['width' => 20],
					'G'    => ['width' => 0,'format'=>'text'],
					'H'    => ['width' => 0,'format'=>'text'],
				],
			],
		];
		$this->excel->generateExcel($sb_view, $param);

	}

	public function import_data_excel(){
        if(!empty($_FILES['file']['name'])) {
			$tahunbulan = date('Ym');
            $fileUpload['fname']    = 'file';
            $fileUpload['location'] = 'template_shift/'.$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]);
        }

		$id_cabang = $objPHPExcel->setActiveSheetIndex(0)->getCell("H7")->getValue();
		$master_shift = $this->Pengaturan_shift_import_m->masterShift($id_cabang);
		$id_temp = $this->fungsi->getNextId('data_shift_karyawan_temp','id',$this->id_company,5);

		$highestColumm = $objPHPExcel->setActiveSheetIndex(0)->getHighestColumn();
		$highestRow = $objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
		$data_insert = array();
		// $highestColumm++;
		for ($row = 7; $row < $highestRow; $row++) {
			$dataset = array();
			for ($column = 'I'; $column != $highestColumm; $column++) {
				$id_karyawan 	= $objPHPExcel->setActiveSheetIndex(0)->getCell("G". $row)->getValue();

				$tgl_shift = $objPHPExcel->setActiveSheetIndex(0)->getCell($column ."6")->getValue();
				$tgl_shift = date_format(date_create($tgl_shift),"Y-m-d");

				$kode_shift = $objPHPExcel->setActiveSheetIndex(0)->getCell($column . $row)->getValue();
				$kode_shift = strtoupper(strtolower(trim($kode_shift)));
				if(empty($kode_shift)){
					$flag = '2';
				}else{
					if(strtotime($tgl_shift) < strtotime(date("Y-m-d"))){
						$flag = '3';
					}else{
						$flag = '1';
					}
				}

				if(empty($master_shift[$kode_shift])){
					$id_master_shift = $kode_shift;
					$flag = '2';
				}else{
					$id_master_shift = $master_shift[$kode_shift];
				}

				if(!empty($id_karyawan)){
					$data = array("id" => $id_temp,
								"id_karyawan"=>$id_karyawan,
								"tanggal"=>$tgl_shift,
								"id_master_shift" =>$id_master_shift,
								"flag" =>$flag,
								"user_input" =>$this->id_karyawan,
								"id_company" => $this->id_company);

					$data_insert[] = $data;

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

				}
			}

		}

		$this->db->trans_start();

		$this->db->where("id_company",$this->id_company);
		$this->db->where("user_input",$this->id_karyawan);
		$this->db->delete("data_shift_karyawan_temp");

		$this->db->insert_batch('data_shift_karyawan_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);
		}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);
		}
    }

	public function publish_all(){

		$periode = $this->Pengaturan_shift_import_m->getPeriodeShift();
		$tgl_mulai = $periode->tgl_mulai;
		$tgl_selesai = $periode->tgl_selesai;

		$data_shift_ready = $this->Pengaturan_shift_import_m->getDataShiftReady($tgl_mulai,$tgl_selesai);

		$id_shift_karyawan = $this->fungsi->getNextId('data_shift_karyawan','id_shift_karyawan',$this->id_company,5);

		$tgl_now = date("Y-m-d");
		$data_insert = [];
		$data_update = [];
		$data_delete = [];

		$data_shift = $this->Pengaturan_shift_import_m->getDataShiftTemp();

		foreach($data_shift as $rows){
			$id = $rows->id;
			$tanggal = $rows->tanggal;
			$id_karyawan = $rows->id_karyawan;
			$id_master_shift = $rows->id_master_shift;

			if(strtotime($tanggal) >= strtotime($tgl_now)){
				$flag = "4";
				$data_insert[] = ["id_shift_karyawan"=>$id_shift_karyawan,
								"tanggal" => $tanggal,
								"id_karyawan" =>  $id_karyawan,
								"id_master_shift" => $id_master_shift,
								"user_input" =>  $this->id_karyawan,
								"id_company" => $this->id_company];

				$last_id = substr($id_shift_karyawan,-5);
				$next_id = $last_id+1;
				$id_shift_karyawan = substr($id_shift_karyawan,0,-5).sprintf("%05d", $next_id);

				if(!empty($data_shift_ready[$id_karyawan."-".$tanggal])){
					$data_delete[] = $data_shift_ready[$id_karyawan."-".$tanggal];
				}
			}else{
				$flag = "3";
			}

			$data_update[] = ["id"=>$id,
								"flag" => $flag];



		}
		// echo "<prev>";
		// print_r($data_insert);
		// print_r($data_delete);
		// print_r($data_update);
		// die();

		$this->db->trans_start();

		if(count($data_delete) > 0){
			$this->db->where_in('id_shift_karyawan', $data_delete);
			$this->db->delete('data_shift_karyawan');
		}

		$this->db->insert_batch('data_shift_karyawan', $data_insert);
		$this->db->update_batch('data_shift_karyawan_temp', $data_update, 'id');

		$this->db->trans_complete();

		if($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			return __response_save(false);
		}else{
			$this->db->trans_commit();
			return __response_save(true);
		}
	}

	public function delete_all_temp(){
		$this->db->where("id_company",$this->id_company);
		$this->db->where("user_input",$this->id_karyawan);
		$delete = $this->db->delete("data_shift_karyawan_temp");
		return __response_delete($delete);
	}
}
