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

class Informasi_gaji extends MY_Controller {

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

        $this->id_karyawan = $this->session->userdata('id_karyawan');
        $this->id_company = $this->session->userdata('id_company');
    }


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

	public function list_data($periode=0, $id_karyawan=0, $kode_cabang=0, $kode_departemen=0){
		
		$list = $this->Informasi_gaji_m->get_datatables($periode, $id_karyawan, $kode_cabang, $kode_departemen);
		$data = array();
		$no = $_POST['start'];

		foreach ($list as $field) {
			$no++;
			$row = array();

			$row[] = $no;
			$row[] = $field->nama_karyawan."<br><span class='font-size-xsmall'>".$field->nik."</span>";
			$row[] = $field->periode;
			$row[] = $field->kode_cabang." - ".$field->nama_cabang;
			$row[] = $field->kode_departemen." - ".$field->nama_departemen;
			$row[] = $field->kode_jabatan." - ".$field->nama_jabatan;
			$row[] = "Rp. ".number_format($field->gaji_pokok,0,",",".");
			$row[] = "Rp. ".number_format($field->ttl_tunjangan,0,",",".");
			$row[] = "Rp. ".number_format($field->ttl_tbp,0,",",".");
			$row[] = "Rp. ".number_format($field->ttl_penerimaan,0,",",".");
			$row[] = "Rp. ".number_format($field->ttl_potongan,0,",",".");
			$row[] = "Rp. ".number_format($field->gaji_diterima,0,",",".");

			if ($field->publish == '0') {
				$checklist_publish = '';
			}else{
				$checklist_publish = 'checked';
			}

			$btn_detail = '<a href="'.route('informasi.gaji.detail').'/'.md5($field->id).'" id="'.md5($field->id).'" class="btn_detail" title="DETAIL">
							<i class="fa fa-info-circle text-primary"></i></a>';
			$btn_edit	= '<a href="'.route('informasi.gaji.edit').'/'.md5($field->id).'" id="'.md5($field->id).'" class="btn_edit" title="EDIT">
							<i class="fa fa-edit text-warning"></i></a>';
			$btn_hapus	= '<a href="#" id="'.md5($field->id).'" class="btn_delete text-danger" title="HAPUS">
							<i class="fa fa-trash"></i></a>';
			
			if(in_array($this->session->userdata("level_user"),['6'])){
				$row[] 	= '<input id="'.md5($field->id).'" type="checkbox" onclick="publish_unpublish(`'.md5($field->id).'`)" publish="'.$field->publish.'" '.$checklist_publish.'>';
				$aksi 	= $btn_detail." ".$btn_edit." ".$btn_hapus;
			}else{
				$aksi 	= $btn_detail;
			}
					
			$row[] = $aksi;	
	
			$data[] = $row;
		}
	
			$output = array("draw"            => $_POST['draw'],
							"recordsTotal"    => $this->Informasi_gaji_m->count_all($periode, $id_karyawan, $kode_cabang, $kode_departemen),
							"recordsFiltered" => $this->Informasi_gaji_m->count_filtered($periode, $id_karyawan, $kode_cabang, $kode_departemen),
							"data"            => $data);

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

	public function form_publish($id = null){
		$data['data'] = $this->Informasi_gaji_m->getDataById($id);
		$this->load->view('informasi_gaji/form_publish', $data);	
	}

	function download($periode, $cabang, $departemen) {		

		$data['bulan'] 			= $this->fungsi->get_bulan($periode);
		$data['tahun'] 			= $this->fungsi->get_tahun($periode);
		$data['cabang'] 		= $this->fungsi->get_nama_cab($cabang);
		$data['departemen'] 	= $this->fungsi->get_data_nama_dep($departemen);
		
		$data['data'] = $this->Informasi_gaji_m->download($periode, $cabang, $departemen);
		$filename = "Informasi Gaji";
		/*echo $this->db->last_query();
		exit();*/
		$filename = $filename.".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=\"$filename\"");
		$this->load->view('informasi_gaji/template', $data, false);
	}

	public function detail($id){
		$data['judul'] = 'Detail Informasi Gaji';
		$data['aktif'] = 'gaji';
		$data['data'] = $this->Informasi_gaji_m->getDataById($id);
		$data['ref'] = $id;
		$data['menu'] = $this->load->view('main_menu', $data, true);
		$data['content'] = $this->load->view('informasi_gaji/detail', $data, true);
		$this->load->view('main_template', $data);	
	}

	public function edit($id=0){
		$data['judul'] = 'Ubah Informasi Gaji';
		$data['aktif'] = 'gaji';
		$data['data'] = $this->Informasi_gaji_m->getDataById($id);
		$data['ref'] = $id;
        $data['menu'] = $this->load->view('main_menu', $data, true);
		$data['content'] = $this->load->view('informasi_gaji/form', $data, true);
		$this->load->view('main_template', $data, false);
		
	}

	public function update(){
		$id = $this->input->post('id');
		$id_company = $this->session->userdata('id_company');

		$gaji_pokok  = str_replace('.','',$this->input->post('gaji_pokok'));
		$t_jabatan   = str_replace('.','',$this->input->post('t_jabatan'));
		$t_transport = str_replace('.','',$this->input->post('t_transport'));
		$t_makan 	 = str_replace('.','',$this->input->post('t_makan'));
		$t_istri 	 = str_replace('.','',$this->input->post('t_istri'));
		$t_anak 	 = str_replace('.','',$this->input->post('t_anak'));
		$lembur 	 = str_replace('.','',$this->input->post('lembur'));
		$komisi      = str_replace('.','',$this->input->post('komisi'));
		$t_lain 	 = str_replace('.','',$this->input->post('t_lain'));
		$ttl_tunjangan	= str_replace('.','',$this->input->post('ttl_tunjangan'));
		$ttl_penerimaan	= str_replace('.','',$this->input->post('ttl_penerimaan'));

		$p_absensi 	 		  = str_replace('.','',$this->input->post('p_absensi'));
		$p_keterlambatan 	  = str_replace('.','',$this->input->post('p_keterlambatan'));
		$p_koperasi  		  = str_replace('.','',$this->input->post('p_koperasi'));
		$p_asuransi_kesehatan = str_replace('.','',$this->input->post('p_asuransi_kesehatan'));
		$p_bpjs_tk 			  = str_replace('.','',$this->input->post('p_bpjs_tk'));
		$p_bpjs_kesehatan  	  = str_replace('.','',$this->input->post('p_bpjs_kesehatan'));
		$p_lain 			  = str_replace('.','',$this->input->post('p_lain'));
		$ttl_potongan			= str_replace('.','',$this->input->post('ttl_potongan'));
		$gaji_diterima			= str_replace('.','',$this->input->post('gaji_diterima'));

        $data = array(
					'gaji_pokok'		=>$gaji_pokok,
					't_jabatan'			=>$t_jabatan,
					't_transport'		=>$t_transport,
					't_makan'			=>$t_makan,
					't_istri'			=>$t_istri,
					't_anak'			=>$t_anak,
					'lembur'			=>$lembur,
					'komisi'			=>$komisi,
					't_lain'			=>$t_lain,
					'ttl_tunjangan'		=>$ttl_tunjangan,
					'ttl_penerimaan'	=>$ttl_penerimaan,
					'tbp_bpjs_tk'		=>str_replace('.','',$this->input->post('tbp_bpjs_tk')),
					'tbp_bpjs_kesehatan'=>str_replace('.','',$this->input->post('tbp_bpjs_kesehatan')),
					'tbp_lain'			=>str_replace('.','',$this->input->post('tbp_lain')),
					'p_absensi'			=>$p_absensi,
					'p_keterlambatan'	=>$p_keterlambatan,
					'p_koperasi'		=>$p_koperasi,
					'p_asuransi_kesehatan'=>$p_asuransi_kesehatan,
					'p_bpjs_tk'			=>$p_bpjs_tk,
					'p_bpjs_kesehatan'	=>$p_bpjs_kesehatan,
					'p_lain'			=>$p_lain,
					'ttl_potongan'		=>$ttl_potongan,
					'gaji_diterima'		=>$gaji_diterima,
					'publish'			=>'0',
					'user_input'		=>$this->id_karyawan,
					'id_company'		=>$this->id_company);

	
		$this->Informasi_gaji_m->save($data,$id); 
	}

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

	public function publish_unpublish(){
		$id = $this->input->post("id");
		$getId= $this->db->query("SELECT id_karyawan, periode FROM informasi_gaji WHERE md5(id) = '$id' ")->row();
		$publish = $this->input->post("publish");
		$data = array("publish" => $publish,
						"tgl_publish" => date("Y-m-d H:i:s"),
						"user_publish" => $this->id_karyawan);

        $this->db->where(array('md5(id)'=>$id, 'id_company'=>$this->id_company));
        $update = $this->db->update('informasi_gaji',$data);
		if($update){
			if($publish == "1"){
				$message = array("message"=>'<font color="#ffffff"><i class="fa fa-check-square">&nbsp;</i>Gaji berhasil di publish</font>');
				$this->send_messageBroker_perId('Informasi Gaji', 'Gaji Bulan '.$this->fungsi->get_bulan($getId->periode).' Sudah dipublish', $getId->id_karyawan, $getId->periode);
			}else{
				$message = array("message"=>'<font color="#ffffff"><i class="fa fa-check-square">&nbsp;</i>Gaji berhasil di unpublish</font>');
			}
			return __response_save(true,$message);
		}else{
			if($publish == "1"){
				$message = '<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>Data gagal di publish</font>';
			}else{
				$message = '<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>Data gagal di unpublish</font>';
			}
			return __response_save(false,$message);
		}
	}

	public function publish_all(){
		$periode = $this->input->post("periode");

		$data = array("publish"=>"1",
						"tgl_publish" 	=> date("Y-m-d H:i:s"),
						"user_publish"	=> $this->id_karyawan);

		$this->send_messageBroker('Informasi Gaji','Gaji Bulan '.$this->fungsi->get_bulan($periode).' Sudah dipublish', $periode);

        $this->db->where('periode',$periode);
        $this->db->where('id_company',$this->id_company);
        $update = $this->db->update('informasi_gaji',$data);
        if($update){
			$message = array("message"=>'<font color="#ffffff"><i class="fa fa-check-square">&nbsp;</i>Gaji periode '.$periode.' berhasil di publish semua</font>');
			return __response_save(true,$message);
        }else{
            $message = array('message'=>'<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>Gaji periode '.$periode.' gagal di publish semua</font>');
			return __response_save(false,$message);
        }
	}

	public function unpublish_all(){
		$periode = $this->input->post("periode");

		$data = array("publish"=>"0",
						"tgl_publish" 	=> date("Y-m-d H:i:s"),
						"user_publish"	=> $this->id_karyawan);

        $this->db->where('periode',$periode);
        $this->db->where('id_company',$this->id_company);
        $update = $this->db->update('informasi_gaji',$data);
        if($update){
			$message = array("message"=>'<font color="#ffffff"><i class="fa fa-check-square">&nbsp;</i>Gaji periode '.$periode.' berhasil di unpublish semua</font>');
			return __response_save(true,$message);
        }else{
            $message = array('message'=>'<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>Gaji periode '.$periode.' gagal di unpublish semua</font>');
			return __response_save(false,$message);
        }
	}

    //DROPDOWn
	public function dropdown_cabang(){
		$search = $this->input->get("q");
		$this->Informasi_gaji_m->dropdown_cabang($$search);
	}

	public function dropdown_departemen($kode_cabang=null){
		$search = $this->input->get("q");
		// $kode_cabang = $this->input->post("kode_cabang");
		$this->Informasi_gaji_m->dropdown_departemen($kode_cabang, $search);
	}

	public function dropdown_karyawan(){
		$key = $this->input->get("q");
		$result = $this->Informasi_gaji_m->dropdown_karyawan($key);
		foreach ($result as $rows) {
			$json[] = ['id'=>$rows->id_karyawan, 'text'=>$rows->nik.' - '.$rows->nama_karyawan];
		}    
        echo json_encode($json);
    }

    function send_messageBroker_perId($judul = null, $content = null, $id_karyawan = null, $id_ref = null){
        $this->load->library('amqp');

        $timetosend =  0; //waktu delay pesan dalam milisecond, misal delay 3s = 3000
		$queue = $this->amqp->delayedQueueName();
		$exchange = $this->amqp->delayedExchangeName();

        $token_fcm = $this->db->select("users.token_fcm")
                                ->from("users")
                                ->join("data_karyawan","data_karyawan.id_karyawan = users.id_karyawan")
                                ->where_in("data_karyawan.status",["1","2","3","4"])
                                ->where("data_karyawan.id_company",$this->id_company)
                                ->where("users.token_fcm !=","")
                                ->where("users.id_karyawan","$id_karyawan")
                                ->get()
                                ->result();

        foreach($token_fcm as $row) {
        	$send['url'] = $this->config->item('url_api')."/notifikasi/send";
            $send['parameter'] = array(
                'token_fcm' => $row->token_fcm,
                'route'     => '/detail_gaji',
                'title'     => $judul,
                'body'      => strip_tags($content),
                'id_ref'    => $id_ref
            );
            $this->amqp->init_delayed();
			$this->amqp->queue($queue);
			$this->amqp->exchange($exchange);
			$this->amqp->delay($timetosend);
			$this->amqp->data($send);
			$this->amqp->send();
        }
    }

    public function send_messageBroker($judul = null, $content = null, $id_ref = null){
		$this->load->library('amqp');

		$timetosend =  0; //waktu delay pesan dalam milisecond, misal delay 3s = 3000
		$queue = $this->amqp->delayedQueueName();
		$exchange = $this->amqp->delayedExchangeName();

		$token_fcm = $this->db->select("users.token_fcm")
                                ->from("users")
                                ->join("data_karyawan","data_karyawan.id_karyawan = users.id_karyawan")
                                ->join("informasi_gaji", "informasi_gaji.id_karyawan = users.id_karyawan")
                                ->where('informasi_gaji.publish', '0')
                                ->where_in("data_karyawan.status",["1","2","3","4"])
                                ->where("data_karyawan.id_company",$this->id_company)
                                ->where("users.token_fcm !=","")
                                ->get()
                                ->result();


        foreach($token_fcm as $row) {
        	$send['url'] = $this->config->item('url_api')."/notifikasi/send";
            $send['parameter'] = array(
                'token_fcm' => $row->token_fcm,
                'route'     => '/detail_gaji',
                'title'     => $judul,
                'body'      => strip_tags($content),
                'id_ref'    => $id_ref
            );
            $this->amqp->init_delayed();
			$this->amqp->queue($queue);
			$this->amqp->exchange($exchange);
			$this->amqp->delay($timetosend);
			$this->amqp->data($send);
			$this->amqp->send();
        }
	}
}
