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

class Pengaturan_shift extends MY_Controller {

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

	public function index(){
		$data['judul'] = $this->lang->line('menu_pengaturan_shift');
		$data['aktif'] = 'pengaturan_shift';
        $data['periode_awal'] = date('d-m-Y',  strtotime(date('Y-m-').'01'));
        $data['periode_akhir'] = date('t-m-Y',  strtotime(date('Y-m-d')));
		$data['level_user'] = $this->session->userdata('level_user');
		$data['multi_cabang'] = $this->session->userdata('multi_cabang');
		$data['multi_departemen'] = $this->session->userdata('multi_departemen');
        $data['menu'] = $this->load->view('main_menu', $data, true);
		$data['content'] = $this->load->view('pengaturan/pengaturan_shift/home', $data, true);
		$this->load->view('main_template', $data, false);
	}

	public function view_data($tgl_mulai=0, $tgl_selesai=0, $id_karyawan=0, $id_cabang=0, $id_departemen=0){
        $this->load->config('datatables');

		$data['tgl_mulai']     = date('Y-m-d', strtotime($tgl_mulai));
		$data['tgl_selesai']   = date('Y-m-d', strtotime($tgl_selesai));
		$data['id_cabang']     = $id_cabang;
		$data['id_departemen'] = $id_departemen;
		$data['id_karyawan']   = $id_karyawan;

		$diff                       = date_diff(date_create($data['tgl_mulai']), date_create($data['tgl_selesai']));
		$data['jumlah']             = ($diff->format("%a%"))+1;
		$header                     = $this->_tabelHeader($data['tgl_mulai'], $data['tgl_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;
		$this->load->view('pengaturan/pengaturan_shift/list_data', $data, false);
	}

    private function _tabelHeader($tgl_mulai, $tgl_selesai, $id_cabang){
        $this->load->helper('datatables');
        $this->config->load('excel');

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

        $akhir   = date_create($tgl_selesai);
        $awal    = date_create($tgl_mulai);
        $selisih = date_diff($akhir, $awal)->format("%a");
        $hasil   = [
            'data_tanggal'  => [],
            'targets_libur' => []
        ];
        $kolom = 4;
        $d     = "l-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);
		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'    => $tanggal,
                '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;
	}

    public function list_data($tanggal_mulai, $tanggal_selesai, $id_karyawan=0, $id_cabang = 0, $id_departemen = 0){

		$date_now 	= date("Y-m-d");
		$data_shift	= $this->Pengaturan_shift_m->dataShift($tanggal_mulai, $tanggal_selesai, $id_karyawan, $id_cabang, $id_departemen);

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

		$list = $this->Pengaturan_shift_m->get_datatables($tanggal_mulai, $tanggal_selesai, $id_karyawan, $id_cabang, $id_departemen);
		$data 	= array();
		$no 	= $_GET['start'];
		foreach ($list as $field) {

			$no++;
			$row = array();

			$row[] = $no;
			$row[] = $field->nama_karyawan.'<br>'.$field->nik;
			$row[] = $field->cabang."<br>".$field->departemen;
			$row[] = $field->jabatan;



            $periode_akhir  = date_create(date('Y-m-d', strtotime('+1 days ' . $tanggal_selesai)));
			$interval       = DateInterval::createFromDateString('1 day');
			$period         = new DatePeriod($awal, $interval, $periode_akhir);
			foreach ($period as $dt) {
				$tgg = $dt->format("Y-m-d");
                $id_shift_karyawan = $data_shift[$tgg."_".$field->id_karyawan]['id_shift_karyawan'];

                $kode_absensi   = $data_shift[$tgg."_".$field->id_karyawan]['kode_shift'];
                $nama_shift     = $data_shift[$tgg."_".$field->id_karyawan]['nama_shift'];
                $jam_shift      = $data_shift[$tgg."_".$field->id_karyawan]['jam_masuk']." - ".$data_shift[$tgg."_".$field->id_karyawan]['jam_pulang'];
                $shift          = '<a data-toggle="tooltip" title="'.$nama_shift.'('.$jam_shift.')" style="cursor:pointer; color:#434343">'.$kode_absensi.'</a>';

                $btn_edit   = "";
                $btn_delete = "";
                if(!empty($kode_absensi) && (strtotime($tgg) >= strtotime($date_now))){
                    $btn_edit   = '<a href="#" onclick="form_edit(`'.md5($id_shift_karyawan).'`)"><i class="fa fa-edit text-warning"></i></a>';
                    $btn_delete = '<a href="#" onclick="form_delete(`'.md5($id_shift_karyawan).'`)"><i class="fa fa-trash text-danger"></i></a>';
                }
                $row[] = $shift."<br>".$btn_edit."&nbsp;".$btn_delete;
			}

			$data[] = $row;
		}

		$recordsTotal = $this->Pengaturan_shift_m->count_all($tanggal_mulai, $tanggal_selesai, $id_karyawan, $id_cabang, $id_departemen);
		$recordsFiltered = $this->Pengaturan_shift_m->count_filtered($tanggal_mulai, $tanggal_selesai, $id_karyawan, $id_cabang, $id_departemen);

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

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

		echo json_encode($output);
	}

	public function form($jenis="hapus", $id_shift_karyawan="0"){
        if($jenis == "tambah"){
            $data['judul'] = $this->lang->line('tambah_shift_karyawan');
            $data['aktif'] = 'pengaturan_shift';
            $data['menu'] = $this->load->view('main_menu', $data, true);
            $data['content'] = $this->load->view('pengaturan/pengaturan_shift/form', $data, true);
            $this->load->view('main_template', $data, false);
        }else if($jenis == "edit"){
            $data['data'] = $this->Pengaturan_shift_m->detailShift($id_shift_karyawan);
            $id_karyawan = $data['data']->id_karyawan;
            $tgl_absen = $data['data']->tanggal;

            $cek_absen = $this->db->query("SELECT id_karyawan 
                                            FROM absensi_masuk 
                                            WHERE id_company = '$this->id_company' 
                                            AND id_karyawan = '$id_karyawan'
                                            AND tgl_absen = '$tgl_absen'")->num_rows();

            $data['cek_absen'] = $cek_absen;
            $this->load->view('pengaturan/pengaturan_shift/form_edit', $data);
        }else{
            $data['data'] = $this->Pengaturan_shift_m->detailShift($id_shift_karyawan);
            $id_karyawan = $data['data']->id_karyawan;
            $tgl_absen = $data['data']->tanggal;

            $cek_absen = $this->db->query("SELECT id_karyawan 
                                            FROM absensi_masuk 
                                            WHERE id_company = '$this->id_company' 
                                            AND id_karyawan = '$id_karyawan'
                                            AND tgl_absen = '$tgl_absen'")->num_rows();

            $data['cek_absen'] = $cek_absen;
            $this->load->view('pengaturan/pengaturan_shift/form_delete', $data);
        }
	}

    // public function edit($id=null){
    //     if($id==null){
    //         $this->load->view('pengaturan/pengaturan_shift/form_edit');
    //     }else{
    //         $data['data'] = $this->Pengaturan_shift_m->getDataById($id);
    //         $this->load->view('pengaturan/pengaturan_shift/form_edit',$data);
    //     }

    // }

    public function edit(){
        $id_shift_karyawan = $this->input->post('id_shift_karyawan');

        $data = array('id_master_shift' =>$this->input->post('id_shift'));

        $this->Pengaturan_shift_m->save($data,$id_shift_karyawan);
    }

	public function delete(){
		$id = $this->input->post("id_shift_karyawan");
		$this->Pengaturan_shift_m->delete($id);
	}

    public function save(){
        $tanggal_mulai = date('Y-m-d', strtotime($this->input->post('tanggal_mulai')));
        $tanggal_selesai = date('Y-m-d', strtotime($this->input->post('tanggal_selesai')));
        $id_cabang = $this->input->post('id_cabang');
        $departemen_arr = $this->Pengaturan_shift_m->dataDepartemen($id_cabang);

        $id_karyawan_arr = json_decode($this->input->post('id_karyawan'));

        $insert_shift = array();
        $delete_shift = array();
        $current = strtotime($tanggal_mulai);
        $last = strtotime($tanggal_selesai);

        $data_shift_karyawan_arr = $this->Pengaturan_shift_m->dataShiftKaryawan($tanggal_mulai,$tanggal_selesai);

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

        while ($current <= $last) {
            $date = date('Y-m-d', $current);
            foreach ($id_karyawan_arr as $val) {
                $data_add = array(
                    'id_shift_karyawan' => $id_shift_karyawan,
                    'id_karyawan' => $val,
                    'id_master_shift' => $this->input->post('id_shift'),
                    'tanggal' => $date,
                    'id_company' => $this->id_company,
                    'id_departemen' => $departemen_arr[$val],
                    'id_cabang' => $id_cabang,
                    'user_input' => $this->id_karyawan
                );

                $cek_absensi_masuk = $this->db->query("SELECT id_karyawan FROM absensi_masuk WHERE id_karyawan IN('$val') AND tgl_absen = '$date'")->num_rows();

                if ($cek_absensi_masuk > 0) {
                    $message = array('message' => '<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>' . $this->lang->line('error_tambah_shift') . '</font>');
                    return __response_save(false, $message);
                }

                if(!empty($data_shift_karyawan_arr[$val."_".$date])){
                    array_push($delete_shift, $data_shift_karyawan_arr[$val."_".$date]);
                }

                array_push($insert_shift, $data_add);

                $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);
            }
            $current = strtotime("+1 day", $current);
        }

        // print_r($delete_shift);
        // print_r($insert_shift);
        // die();

        $this->db->trans_start();

        $this->db->insert_batch('data_shift_karyawan', $insert_shift);

        if(!empty($delete_shift)){
            $this->db->where_in('id_shift_karyawan', $delete_shift);
            $this->db->delete('data_shift_karyawan');
        }

        $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 update()
    {
        $company = $this->session->userdata('id_company');
        $where_company = "id_company = '$company'";

        $zona = $this->db->where('id_company', $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');
        }

        // $tgl_masuk = $this->convertion->reverse_date2($this->input->post('tanggal'));
        // $tgl_akhir = $this->convertion->reverse_date2($this->input->post('tanggal_akhir'));
        $tgl_masuk = date('Y-m-d', strtotime($this->input->post('tanggal_mulai')));
        $tgl_akhir = date('Y-m-d', strtotime($this->input->post('tanggal_akhir')));

        $karyawan_arr = json_decode($this->input->post('karyawan'));
        $id_shift_karyawan = $this->input->post('id_shift_karyawan');
        $insert_shift = array();
        $delete_shift = array();
        $current = strtotime($tgl_masuk);
        $last = strtotime($tgl_akhir);
        while ($current <= $last) {
            $date = date('Y-m-d', $current);
            foreach ($karyawan_arr as $val) {
                $data_add = array(
                    'id_karyawan' => $val,
                    'id_master_shift' => $this->input->post('shift'),
                    'tanggal' => $date,
                    'id_company' => $company,
                    'id_departemen' => $this->input->post('departemen'),
                    'id_cabang' => $this->input->post('cabang')
                );
                $query = $this->Pengaturan_shift_m->cek_shift_id($id_shift_karyawan);

                //jika belum ada
                if ($query->num_rows() > 0) {
                  //jika sudah ada maka masuk list hapus
                  foreach ($query->result() as $row) {
                      array_push($delete_shift, $row->id_shift_karyawan);
                  }
                }
                array_push($insert_shift, $data_add);
            }
            $current = strtotime("+1 day", $current);
        }

        //cek shift tidak kosong
        if(!empty($delete_shift)) {
            //hapus Multiple
            $this->Pengaturan_shift_m->hapus_multiple_id_shift($delete_shift);
            $json['message'] = '<font color="#009900"><i class="fa fa-check-square">&nbsp;</i>'.$this->lang->line('success_update').'</font>';
            $json['type']  = 'update';
            $json['success'] = true;
        } else {
            $json['message'] = '<font color="#009900"><i class="fa fa-check-square">&nbsp;</i>'.$this->lang->line('success_update').'</font>';
            $json['type']  = 'save';
            $json['success'] = true;
        }

        //insert multiple
        $this->Pengaturan_shift_m->insert_multiple_shift($insert_shift);
        $this->logger->create_log('daftar shift', 'tambah', $this->db->last_query());
        echo json_encode($json);
    }

    // public function export_xls($awal,$akhir,$divisi,$shift)
    // {
    //     $company = $this->session->userdata('id_company');
    //     $where_company = "data_shift_karyawan.id_company = '$company'";

    //     $zona = $this->db->where('id_company', $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');
    //     }

    //     $tgl_masuk = date('Y-m-d', strtotime($awal));
    //     $tgl_akhir = date('Y-m-d', strtotime($akhir));

    //     $where = array(
    //         "data_shift_karyawan.tanggal >='" . $tgl_masuk . "'" => null,
    //         "data_shift_karyawan.tanggal <='" . $tgl_akhir . "'" => null,
    //         $where_company => null
    //     );

    //     $get_karyawan = $_GET['parameter'];

    //     $karyawan = json_decode($get_karyawan);

    //     /*var_dump($karyawan);
    //     exit();*/

    //     if (!empty($karyawan)) {
    //         //$where["id_karyawan IN('" . str_replace(":", "','", $karyawan) . "')"] = null;
    //         $items = array();
    //         $tags = $karyawan;

    //         foreach ($tags as $key) {
    //             $items[] = "data_shift_karyawan.id_karyawan = '$key'";
    //         }

    //         $txt = implode(" OR ", $items);

    //         $where["($txt)"] = null;
    //     }

    //     $where["data_shift_karyawan.id_departemen"] = $divisi;

    //     if ($shift != "" && $shift != "-" && $shift != "null") {
    //         $where["data_shift_karyawan.id_master_shift"] = $shift;
    //     }

    //     $where["data_karyawan.id_karyawan IS NOT NULL"] = null;

    //     $query = $this->db_model->get('data_shift_karyawan', 'data_shift_karyawan.*, data_karyawan.id_departemen', $where, "data_shift_karyawan.id_karyawan, data_shift_karyawan.tanggal", '', '', '', array(
    //         array(
    //             'table' => 'data_karyawan',
    //             'on' => 'data_shift_karyawan.id_karyawan = data_karyawan.id_karyawan',
    //             'pos' => "left"
    //         )
    //     ));

    //     //        echo $this->db->last_query();
    //     //        echo '<br>';

    //     $query_distnct_karyawan = $this->db_model->get('data_shift_karyawan', "DISTINCT(data_shift_karyawan.id_karyawan)", $where, "data_shift_karyawan.id_karyawan, data_shift_karyawan.tanggal", '', '', '', array(
    //         array(
    //             'table' => 'data_karyawan',
    //             'on' => 'data_shift_karyawan.id_karyawan = data_karyawan.id_karyawan',
    //             'pos' => "left"
    //         )
    //     ));
    //     //        echo $this->db->last_query();
    //     //        echo '<br>';

    //     $data_absen = $query->result();
    //     $data_distnct_karyawan = $query_distnct_karyawan->result();

    //     $dates = array();
    //     $current = strtotime($tgl_masuk);
    //     $last = strtotime($tgl_akhir);
    //     while ($current <= $last) {
    //         $dates[] = date("Y-m-d", $current);
    //         $current = strtotime("+1 day", $current);
    //     }

    //     $data_order = array();
    //     $i = 0;
    //     $nama_kary = "";

    //     foreach ($data_distnct_karyawan as $val) {
    //         $date = $tgl_masuk;
    //         while ($date <= $akhir) {
    //             if ($nama_kary == "") {
    //                 $nama_kary = $this->fungsi->get_nama_kar($val->id_karyawan);
    //             } else {
    //                 $nama_kary = $nama_kary . ", " . $this->fungsi->get_nama_kar($val->id_karyawan);
    //             }
    //             $a = json_encode($data_absen);
    //             $b = json_decode($a, True);
    //             $index = $this->search_revisions($b,$val->id_karyawan, 'id_karyawan', $date, 'tanggal');
    //             $holiday = $this->fungsi->isHoliday2($val->id_karyawan,$date);
    //             if (isset($index)) {
    //                 // $data_order[$val->id_karyawan][$date] = $data_absen[$i];
    //                 // $data_order[$val->id_karyawan][$date]->holiday = $holiday;
    //                 $data_order[$val->id_karyawan][$date] = (object)array(
    //                     'id_shift_karyawan' => $b[$index]['id_shift_karyawan'], 'id_karyawan' => $val->id_karyawan, 'tanggal' => $date, 'id_shift' => $b[$index]['id_master_shift'], 'holiday' => $holiday
    //                 );
    //             } else {
    //                 $data_order[$val->id_karyawan][$date] = (object)array(
    //                     'id_shift_karyawan' => '', 'id_karyawan' => $val->id_karyawan, 'tanggal' => $date, 'id_shift' => "", 'holiday' => $holiday
    //                 );
    //             }
    //             $date = date('Y-m-d', strtotime($date . " +1 days"));
    //         }
    //     }

    //     $data['jumlah'] = $query->num_rows();
    //     $data['data'] = $data_order;
    //     $data['tanggal'] = $dates;
    //     $data['nama_kary'] = $nama_kary;
    //     $data['tgl_mulai'] = $awal;
    //     $data['tgl_akhir'] = $akhir;
    //     $data['divisi'] = $this->fungsi->get_data_nama_dep($divisi);

    //     $nama = "Daftar Shift Karyawan.xls";
    //     @header("Cache-Control: "); // leave blank to avoid IE errors
    //     @header("Pragma: "); // leave blank to avoid IE errors
    //     @header("Content-type: application/msexcel");
    //     @header("Content-Disposition: attachment; filename=\"$nama\"");
    //     $this->load->view('pengaturan/pengaturan_shift/export_xls', $data, false);
    // }

//    public function import()
//     {
//         $company = $this->session->userdata('id_company');
//         $where_company = "id_company = '$company'";
//         $cabang = $this->input->post('id_cabang');
//         $divisi = $this->input->post('id_departemen');
//         //$targetFolder = '.template/shift/';
//         //$mulai = strtotime($this->convertion->reverse_date2($this->input->post('tanggal_mulai')));
//         //$selesai = strtotime($this->convertion->reverse_date2($this->input->post('tanggal_akhir')));
//         $awal = $this->input->post('tanggal_mulai');
//         $tgl = date('Y-m-d', $mulai);
//         $akhir = $this->input->post('tanggal_akhir');

//         $mulai = date('Y-m-d', strtotime($awal));
//         $selesai = date('Y-m-d', strtotime($akhir));
//         //buat array id karyawan
//         $karyawan = $this->Pengaturan_shift_m->karyawan($company, $cabang, $divisi);
//         $id_karyawan = array();
//         $nik_karyawan = array();
//         $divisi_karyawan = array();
//         foreach ($karyawan->result() as $row) {
//           array_push($id_karyawan, $row->id_karyawan);
//           array_push($nik_karyawan, $row->nik);
//           array_push($divisi_karyawan, $row->id_departemen);
//         }

//         //buat array shift
//         $shift = $this->Pengaturan_shift_m->shift($company, $cabang);
//         $id_shift = array();
//         $kode_shift = array();
//         $insert_shift = array();
//         $delete_shift = array();
//         foreach ($shift->result() as $row) {
//           array_push($id_shift, $row->id_master_shift);
//           array_push($kode_shift, $row->kode_shift);
//         }

//         if (!empty($_FILES['file'])) {
//             $tempFile = $_FILES['file']['tmp_name'];
//             $targetFolder = "./templates/import_shift/";

//             if (!is_dir($targetFolder)) {
//                 mkdir($targetFolder, 0777, TRUE); //create the folder if it's not already exists
//             }
//             $name = $_FILES['file']['name'];
//             $fileParts = pathinfo($name);
//             $nama_company_trim4 = substr(trim($this->Pengaturan_shift_m->nama_company_trim4($company)),0,4);
//             $targetName = $company.'_'.$nama_company_trim4.'_'.$cabang.'_'.$mulai.'_'.rand().'.'.$fileParts['extension'];
//             $targetFile = $targetFolder . $targetName;
//             // Validate the file type
//             $fileTypes = array('xls', 'xlsx', 'csv'); // File extensions
//             $fileSize = $_FILES['file']['size'];
//             for ($seq = 1; file_exists($targetFile); $seq++) {
//                 if (file_exists($targetFile)) {
//                     $targetName = substr($fileParts['basename'], 0, strlen($fileParts['basename']) - strlen($fileParts['extension']) - 1) . '_' . $seq . '.' . $fileParts['extension'];
//                     $targetFile = $targetFolder . $targetName;
//                 }
//             }
//             if (in_array($fileParts['extension'], $fileTypes)) {
//                 if (move_uploaded_file($tempFile, $targetFile)) {

//                     /*$this->load->library('PHPExcel');

//                     $inputFileName = $targetFile;
//                     try {
//                         require_once APPPATH.'libraries/PHPExcel/IOFactory.php';
//                         $objPHPExcel = IOFactory::load($inputFileName);
//                     } catch (Exception $e) {
//                         echo 'Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage();
//                         exit;
//                     }*/
//                     try {
//                         $inputFileType = PHPExcel_IOFactory::identify($targetFile);
//                         $objReader = PHPExcel_IOFactory::createReader($inputFileType);
//                         $objPHPExcel = $objReader->load($targetFile);
//                     } catch (Exception $e) {
//                         die('Error loading file "' . pathinfo($targetFile, PATHINFO_BASENAME) . '": ' . $e->getMessage());
//                     }

//                     $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
//                     $error = 0;
//                     if( sizeof($sheetData) < 3 OR
//                         $sheetData[1]["B"] != "NIP" OR
//                         $sheetData[1]["C"] != "Tanggal" OR
//                         $sheetData[2]["C"] != "Nama / Hari"){
//                         $msg = "format excel tidak sesuai template";
//                         $json['status'] = $msg;
//                         unlink($targetFile);
//                     } else {
//                         $end = sizeof($sheetData);
//                         for ($i = 3; $i <= $end; $i++) {
//                             if( $sheetData[$i]["B"] == "" AND $sheetData[$i]["C"] == "" AND $sheetData[$i]["D"] == "") {
//                                 $json['status'] = "berhasil";
//                                 $json['alert'] = "Berhasil import data shift";
//                                 break;
//                             }
//                             $nip = $sheetData[$i]['B'];
//                             if ($nip == '') {
//                                 //hapus file jika tidak sesuai
//                                 unlink($targetFile);
//                                 echo "NIP kosong pada baris ke $i";
//                                 exit;
//                             }

//                             if (!in_array($nip, $nik_karyawan)) {
//                                 //hapus file jika tidak sesuai
//                                 unlink($targetFile);
//                                 echo "NIP '$nip' tidak ditemukan di sistem";
//                                 exit;
//                             }

//                             $num_col = 4;
//                             $current = strtotime($mulai);
//                             $last = strtotime($selesai);
//                             while ($current <= $last) {
//                                 $chr_col = $this->getNameFromNumber($num_col);
//                                 //jika shift addslashes
//                                 //variabel baris kolom
//                                 $cell = trim($sheetData[$i][$chr_col]);
//                                 $cari_array = array_search($cell, $kode_shift);
//                                 if($cari_array !== false) {
//                                   $kode_shift_import = $id_shift[$cari_array];
//                                 } else {
//                                   //jika shift kosong
//                                   if($sheetData[$i][$chr_col] == "") {
//                                       //hapus file jika tidak sesuai
//                                       unlink($targetFile);
//                                       echo "Kode shift kolom $chr_col baris ke $i kosong";
//                                       exit;
//                                   } elseif($sheetData[$i][$chr_col] == "-") {
//                                       $kode_shift_import = "-";
//                                   } else {
//                                       $kode_shift_import = $sheetData[$i][$chr_col];
//                                       //hapus file jika tidak sesuai
//                                       unlink($targetFile);
//                                       echo "Kode shift $kode_shift_import kolom $chr_col baris ke $i tidak ditemukan di dalam sistem, silahkan menambahkan kode shift terlebih dahulu";
//                                       exit;
//                                   }
//                                 }

//                                 $date = date('Y-m-d', $current);
//                                 $divisi_array = array_search($nip, $nik_karyawan);
//                                 if($divisi_array !== false) {
//                                   $divisi_import = $divisi_karyawan[$divisi_array];
//                                   $id_karyawan_import = $id_karyawan[$divisi_array];
//                                 } else {
//                                   $divisi_import = $divisi;
//                                   $id_karyawan_import = $nip;
//                                 }

//                                 $data_add = array(
//                                     'id_karyawan' => $id_karyawan_import,
//                                     'tanggal' => $date,
//                                     'id_master_shift' => $kode_shift_import,
//                                     'id_company' => $company,
//                                     'id_departemen' => $divisi_import,
//                                     'id_cabang' => $cabang
//                                 );
//                                 //cek jika sudah terdapat shift atau belum di data shift karyawan
//                                 $query = $this->Pengaturan_shift_m->cek_shift($id_karyawan_import, $date, $company);
//                                 //jika belum ada
//                                 if ($query->num_rows() > 0) {
//                                   //jika sudah ada maka masuk list hapus
//                                   foreach ($query->result() as $row) {
//                                       array_push($delete_shift, $row->id_shift_karyawan);
//                                   }
//                                 }
//                                 array_push($insert_shift, $data_add);
//                                 $current = strtotime("+1 day", $current);
//                                 $num_col++;
//                             }
//                         }
//                         //cek shift tidak kosong
//                         if(!empty($delete_shift)) {
//                           //hapus Multiple
//                           $this->Pengaturan_shift_m->hapus_multiple_id_shift($delete_shift);
//                         }

//                         //insert multiple
//                         $this->Pengaturan_shift_m->insert_multiple_shift($insert_shift);

//                         $json['status'] = "berhasil";
//                         $json['alert'] = "Berhasil import data shift ".$end;
//                         $this->logger->create_log('daftar shift', 'import', $targetName);
//                     }
//                 } else {
//                     $json['status'] = "Gagal Import Data tiga";
//                 }
//             } else {
//                 $json['status'] = "Gagal Import Data dua";
//             }
//         } else {
//             $json['status'] = "Gagal Import Data satu";
//         }
//         unlink($targetFile);
//         echo json_encode($json);
//     }

    function getNameFromNumber($num)
    {
        $numeric = ($num - 1) % 26;
        $letter = chr(65 + $numeric);
        $num2 = intval(($num - 1) / 26);
        if ($num2 > 0) {
            return $this->getNameFromNumber($num2) . $letter;
        } else {
            return $letter;
        }
    }
}
