<?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'] = '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);
	}

	// function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null) {
    //     // This function will search the revisions for a certain value
    //     // related to the associative key you are looking for.
    //     $keys = null;
    //     foreach ($dataArray as $key => $cur_value) {
    //         if ($cur_value[$key_to_search] == $search_value) {
    //             if (isset($other_matching_key) && isset($other_matching_value)) {
    //                 if ($cur_value[$other_matching_key] == $other_matching_value) {
    //                     $keys = $key;
    //                 }
    //             } else {
    //                 // I must keep in mind that some searches may have multiple
    //                 // matches and others would not, so leave it open with no continues.
    //                 $keys = $key;
    //             }
    //         }
    //     }
    //     return $keys;
    // }

	public function view_data($tgl_mulai=0, $tgl_selesai=0, $id_karyawan=0, $id_cabang=0, $id_departemen=0){
        $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;
		$data['header'] 		= $this->_tabelHeader($data['tgl_mulai'], $data['tgl_selesai']);
		$data['usergroup'] 		= $this->level_user;
		$this->load->view('pengaturan/pengaturan_shift/list_data', $data, false);
	}

    private function _tabelHeader($tgl_mulai, $tgl_selesai){
		$akhir		= date_create($tgl_selesai);
		$awal 		= date_create($tgl_mulai);
		$selisih 	= date_diff($akhir, $awal)->format("%a");
		$hasil 		= array();
		$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);
		foreach ($period as $dt) {
			$hasil[] = indo_date($dt->format("Y-m-d"), $d);
		}
		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 	= $_POST['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"            => $_POST['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'] = '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);
            $this->load->view('pengaturan/pengaturan_shift/form_edit', $data);
        }else{
            $data['data'] = $this->Pengaturan_shift_m->detailShift($id_shift_karyawan);
            $this->load->view('pengaturan/pengaturan_shift/form_delete', $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($id_cabang,$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
                );

                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>Data berhasil diperbarui</font>';
            $json['type']  = 'update';
            $json['success'] = true;
        } else {
            $json['message'] = '<font color="#009900"><i class="fa fa-check-square">&nbsp;</i>Data berhasil disimpan</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);
    }

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