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

class Kalender extends MY_Controller {

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

    public function index(){
        $data['judul'] = 'Hari Libur';
        $data['aktif'] = 'kalender';
        $data['kalender'] = $this->kalender();
        $data['menu'] = $this->load->view('main_menu', $data, true);
        $data['content'] = $this->load->view('kalender/home', $data, true);
        $this->load->view('main_template', $data, false);
    }

	public function view_data(){
        $data['judul'] = 'Hari Libur';
        $data['aktif'] = 'kalender';
        $this->load->view('kalender/list_view', $data, false);
    }

    public function kalender_data(){
        $data['data_kelender'] = $this->kalender();
        $this->load->view('kalender/kalender_view', $data, false);
    }

	public function kalender(){
        $company = $this->session->userdata('id_company');
        $libur = $this->db->get_where('holidays', array('id_company' => $company))->result();

        $json = array();
        foreach($libur as $qq){
            $isi    = array();
            $isi['id_holiday']  = md5($qq->id); 
            $isi['title']   	=  ucwords($qq->keterangan);
            $isi['start']   	= date_format(date_create($qq->tanggal), "Y-m-d H:i:s");
            $isi['id_company']  = intval($qq->id_company);
            $isi['color'] 		= $qq->color;
            $isi['textColor'] 	= 'white';
            $json[] = $isi;
        }
        // echo json_encode($json);
        return json_encode($json);
    }

	public function list_data(){
		$list = $this->Kalender_m->get_datatables();
		$data = array();
		$no = $_GET['start'];
		foreach ($list as $field) {
			$no++;
			$row = array();
			$row[] = $no;
			$row[] = $this->fungsi->tgl_indo($field->tanggal);
			$row[] = $field->keterangan;
            if (in_array($this->session->userdata('level_user'), array("1"))) {
			     $row[] = '<a href="#" class="text-warning" title="EDIT">
							<i id="'.md5($field->id).'" class="btn_edit fa fa-edit (alias) "> </i></a>&nbsp;
						<a href="#" class="text-danger" title="HAPUS">
							<i id="'.md5($field->id).'" class="btn_delete fa fa-trash"></i>
						</a>';
            }
	
			$data[] = $row;
		}
	
			$output = array("draw"            => $_GET['draw'],
							"recordsTotal"    => $this->Kalender_m->count_all(),
							"recordsFiltered" => $this->Kalender_m->count_filtered(),
							"data"            => $data);
	
		$output = __response($this->MY_response, $output);
				
		echo json_encode($output);
	}

	public function form($id=null){
		if($id==null){
			$this->load->view('kalender/form');
		}else{
			$data['data'] = $this->Kalender_m->getDataById($id);
			$this->load->view('kalender/form',$data);
		}
		
	}

	public function save(){
		$id = $this->input->post('id');
	
		$data = array('tanggal'		=> date('Y-m-d', strtotime($this->input->post('tanggal'))),
					'keterangan'	=> $this->input->post('keterangan'),
					'id_company' 	=> $_SESSION['id_company']);
	
		$this->Kalender_m->save($data,$id); 
	}

	// public function update(){
    //     $response = array();
    //     $this->form_validation->set_rules('keterangan', 'Keterangan', 'callback_keterangan_check');
    //     $this->form_validation->set_rules('tanggal', 'Tanggal', 'callback_tanggal_check');
    //     if ($this->form_validation->run() == TRUE) {
    //         $param = $this->input->post();
    //         $holiday_id = $param['holiday_id'];
    //         unset($param['holiday_id']);

    //         if ($holiday_id == 0) {
    //             $tanggal = $param['tanggal'];
    //             $cek_tanggal = $this->db->select("id")->from("holidays")->where("tanggal", $tanggal)->get();
    //             if ($cek_tanggal->num_rows() > 0) {
    //                 $message = array('message'=>'<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>Tanggal sudah digunakan</font>');
    //                 return __response_save(false, $message);
    //             }else{
    //                 $insert = $this->db_model->tambah('holidays', $param);
    //                 return __response_update($insert);
    //             }
                
    //         }else{
    //             $tanggal = $param['tanggal'];
    //             $cek_tanggal = $this->db->select("id")->from("holidays")->where("tanggal", $tanggal)->where('id !=', $holiday_id)->get();
    //             if ($cek_tanggal->num_rows() > 0) {
    //                 $message = array('message'=>'<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>Tanggal sudah digunakan</font>');
    //                 return __response_update(false, $message);
    //             }else{
    //                 $where = ['id' => $holiday_id];
    //                 $update = $this->db_model->update('holidays', $param, $where);
    //                 return __response_save($update);
    //             }
    //         }
    //     }else{
    //         return __response_save(false);
    //     }

    // }

    public function keterangan_check($str){
        if($str == ''){
            $this->form_validation->set_message('keterangan_check', 'Keterangan belum diisi');
            return FALSE;
        }else{
            return TRUE;
        }
    }

    public function tanggal_check($str){
        if ($str == ''){
            $this->form_validation->set_message('tanggal_check', 'Tanggal belum diisi');
            return FALSE;
        }else{
            return TRUE;
        }
    }

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

	public function delete_holiday(){
        $response = array();
        $holiday_id = $this->input->post('id');
        if (!empty($holiday_id)) {
            $where = ['id' => $holiday_id];
            $delete = $this->db_model->delete('holidays', $where);
            return __response_delete($delete);
        }else{
            return __response_delete(false);
        }
    }

	public function cek_tanggal(){
		$tanggal = date('Y-m-d', strtotime($this->input->post('tanggal')));
		if(!empty($tanggal)) {

		  $query =  $this->db->select("id")->from("holidays")->where("tanggal", $tanggal)->get();
          //$this->db->query("SELECT id FROM holidays WHERE tanggal = '$tanggal'");
		  
		  if($query->num_rows() > 0) {
		  	 echo "sudah";
		      //echo "<span class='status-not-available' style='color: red;'> Tanggal Libur sudah digunakan.</span>";
		      //echo $this->db->last_query();
		  }else{
		  	echo "belum";
		      //echo "<span class='status-available' style='color: green;'> Tanggal Libur belum digunakan.</span>";
		  }
		}
	}

	 public function import() {
        $status = 'unsuccess';
        $notifikasi = '';
        if (!empty($_FILES['file']['name'])) {
            $file_name = time() . $_FILES['file']['name'];
            $fileTmpLoc = $_FILES["file"]["tmp_name"];
            $split_filename = explode(".", $_FILES['file']['name']);
            $fileExt = end($split_filename);
            if (!in_array($fileExt, array('xls', 'xlsx'))) {
                $notifikasi = "GAGAL: Format / ekstensi file harus .xls, .xlsx";
            }
            $mkdir = "./kalender/import_kalender";

            if (!is_dir($mkdir)) {
                mkdir($mkdir, 0777, TRUE); //create the folder if it's not already exists
            }

            move_uploaded_file($fileTmpLoc, "$mkdir/$file_name");
            $dir_file = $mkdir . '/' . $file_name;
        } else {
            $notifikasi = "GAGAL: Silahkan unggah berkas terlebih dahulu";
        }

        try {
            $inputFileType = PHPExcel_IOFactory::identify($dir_file);
            $objReader = PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($dir_file);
        } catch (Exception $e) {
            die('Error loading file "' . pathinfo($dir_file, PATHINFO_BASENAME) . '": ' . $e->getMessage());
        }

        $sheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);

        $data = [];
        $numrow = 1;
        foreach ($sheet as $row) {
            if ($numrow > 1) {
                $tanggal 	= isset($row['B']) ? $row['B'] : 'x';
                $keterangan = isset($row['C']) ? $row['C'] : 'x';
                $id_company = $this->session->userdata('id_company');

                $query_cek = $this->db_model->get('holidays', 'id', array('tanggal' => date('Y-m-d', strtotime($tanggal))));
                if ($tanggal != 'x') {
                    if ($query_cek->num_rows() > 0) {
                        $data = array('tanggal'	   => date('Y-m-d', strtotime($tanggal)),
                            		  'keterangan' => $keterangan,
                            		  'id_company' => $id_company,
                        		);
                        $this->db_model->update('holidays', $data, array('tanggal' => date('Y-m-d', strtotime($tanggal))));
                        $status = 'success';
                    } else {
                        $data = array('tanggal'    => date('Y-m-d', strtotime($tanggal)),
                            		  'keterangan' => $keterangan,
                            		  'id_company' => $id_company,
                        );
                        $this->db_model->add('holidays', $data);
                       
                        $status = 'success';
                    }
                }
            }
            $numrow++;
        }

      	unlink('kalender/import_kalender/'.$file_name);

        $json['status'] = $status;
        $json['notifikasi'] = $notifikasi;
        echo json_encode($json);
    }

       public function export($tahun='0')
    {
        include APPPATH.'third_party/PHPExcel/PHPExcel.php';
        if ($tahun != '0') {
            $data = $this->db->select("*")->from("holidays")->where("YEAR(tanggal)",$tahun)->order_by("tanggal","DESC")->get()->result();
            // /$this->db->query("SELECT holidays.* FROM holidays WHERE YEAR(holidays.tanggal) = '$tahun' ORDER BY holidays.tanggal DESC")->result();
        }else{
            $data = $this->db->select("*")->from("holidays")->order_by("tanggal","DESC")->get()->result();
            //$this->db->query("SELECT holidays.* FROM holidays ORDER BY holidays.tanggal DESC")->result();
        }
        $data['data']  = $data;
        $data['tahun'] = $tahun;

        ob_start();
        $this->load->view('kalender/cetak_data', $data);
        $html = ob_get_contents();
        ob_end_clean();
        $nama = "Data Hari Libur.xls";   
        // Proses file excel
        @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\"");
        echo $this->load->view('kalender/cetak_data',$data,true);            
    }
}
