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

class Verifikasi extends MY_Controller {

    public function __construct(){
        parent::__construct();
        $this->load->model('pkwt/baru/Verifikasi_m');
    }

    public function list_data($tanggal_mulai="0000-00-00", $tanggal_selesai="0000-00-00", $id_cabang="", $id_departemen="", $id_karyawan=""){
        $list = $this->Verifikasi_m->get_datatables($tanggal_mulai, $tanggal_selesai, $id_cabang, $id_departemen, $id_karyawan);
        $data = array();
        $no = $_GET['start'];
        foreach ($list as $field) {
            $no++;
            $row = array();
            $row[] = $no;
            $row[] = $field->nm_karyawan. "<br><b>". $field->nik.'</b>';
            $row[] = $field->nm_jabatan. "<br><b>". $field->nm_lvl_user.'</b>';
            $row[] = $field->nm_cabang. "<br>". $field->nm_departemen;

            $row[] = $this->_get_approval($field->apv_karyawan);

            if($field->apv_direksi == '1') {
                $direksi = '<a href="#" id="' . md5($field->id_pkwt) . '" class="btn_verifikasi_pkwt btn btn-primary" title="VERIFIKASI">
                            <i class="fa fa-check"> </i> VERIFIKASI</a>&nbsp;';

                $checklist = '<input class="cek_pkwt_verifikasi" type="checkbox" name="checkbox_verifikasi" value="' . md5($field->id_pkwt) . '" >';
            } elseif(in_array($field->apv_direksi,['3','4'])) {
                $direksi = $this->_get_approval($field->apv_direksi);
                $checklist = '<input class="cek_pkwt_verifikasi" type="checkbox" name="checkbox_verifikasi" disabled >';
            }else{
                $direksi = '<a class="btn_verifikasi btn btn-light text-white" title="VERIFIKASI" disabled>
                            <i class="fa fa-check"> </i> VERIFIKASI</a>&nbsp;';

                $checklist = '<input class="cek_pkwt_verifikasi" type="checkbox" name="checkbox_verifikasi" disabled >';
            }
            $row[] = $direksi;

            $row[] = '<a href="'.site_url('pkwt/baru/download/pdf/'.md5($field->id_pkwt)).'" title="Detail" class="text-primary" target="_blank">
                                        <i class="btn_detail fa fa-info-circle (alias) "> </i>
                                    </a>&nbsp;';

            $row[]  = $checklist;

            $data[] = $row;
        }

        $output = array("draw"            => $_GET['draw'],
                        "recordsTotal"    => $this->Verifikasi_m->count_all($tanggal_mulai, $tanggal_selesai, $id_cabang, $id_departemen, $id_karyawan),
                        "recordsFiltered" => $this->Verifikasi_m->count_filtered($tanggal_mulai, $tanggal_selesai, $id_cabang, $id_departemen, $id_karyawan),
                        "data"            => $data);

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

        echo json_encode($output);
    }

    public function verifikasi_form($id_pkwt){
        $data['data'] = $this->Verifikasi_m->getDataById($id_pkwt);
        $this->load->view('pkwt/baru/form_approval', $data);
    }

    public function verifikasi_approve(){
        $this->nama_lengkap = $this->session->userdata('nama_user');
        $this->nik          = $this->session->userdata('nik');

        $id_pkwt            = $this->input->post('id');
        $apv_direksi        = $this->input->post('status');
        $path_ttd           = $this->input->post('path_ttd');
        $nm_direktur        = $this->input->post('nm_direktur');
        $tgl_pkwt_mulai     = $this->input->post('tgl_pkwt_mulai');
        $tgl_pkwt_selesai   = $this->input->post('tgl_pkwt_selesai');
        $no_pkwt            = $this->input->post('no_pkwt');
        $ket_tolak          = $this->input->post('ket_tolak');
        $id_karyawan        = $this->_get_data_pkwt($id_pkwt)->id_karyawan;

        // START PINDAH TTD DIREKTUR
        $path_master_ttd_direksi = $this->config->item('base_upload').$path_ttd;

        if($apv_direksi == '4'){
            if (file_exists($path_master_ttd_direksi)) {
                // deteksi ekstension
                $file_info      = pathinfo($path_master_ttd_direksi);
                $file_extension = isset($file_info['extension']) ? $file_info['extension'] : '';
    
                // nama file
                $sub_pkwt = str_replace('/', '_', $no_pkwt);
                $nama_file = $sub_pkwt.'_'.$id_karyawan.'_'.date("YmdHis").'.'.$file_extension;
                $path_apv_ttd_direksi = $this->config->item('base_upload').$this->id_company.'/pkwt/apv_direksi';
    
                if (!file_exists($path_apv_ttd_direksi)) {
                    mkdir($path_apv_ttd_direksi, 0755, true);
                }
                
                $copy = copy($path_master_ttd_direksi, $path_apv_ttd_direksi.'/'.$nama_file);
    
                if ($copy) {
                    // berhasil
                } else {
                    echo "gagal: " . error_get_last()['message'];
                }
            } else {
                echo "Source file does not exist";
            }
        }
        // END PINDAH TTD DIREKTUR

        $update_pkwt = array('apv_direksi'      => $apv_direksi,
                            'status'            => $apv_direksi,
                            'nm_direktur'       => $nm_direktur,
                            'ket_tolak'         => $ket_tolak,
                            'tgl_apv_direksi'   => date("Y-m-d H:i:s"),
                            'user_apv_direksi'  => $this->nik. " - ". $this->nama_lengkap);

        $update_data_karyawan = array('tgl_aktif_bekerja' => $tgl_pkwt_mulai,
                                        'tgl_berhenti_bekerja' => $tgl_pkwt_selesai);
        
        if($apv_direksi == '4'){
            $path_ttd_direktur = array('ttd_direktur'       => $this->id_company.'/pkwt/apv_direksi/'.$nama_file);
        }else{
            $path_ttd_direktur = array();
        }

        $this->db->trans_start();

        // 1. update pkwt
        $this->db->where('id_company', $this->id_company);
        $this->db->where('MD5(id_pkwt)', $id_pkwt);
        $this->db->update('pkwt_data', array_merge($update_pkwt,$path_ttd_direktur));

        if($apv_direksi == '4'){
            // 2. update tgl kontrak
            $this->db->where('id_company', $this->id_company);
            $this->db->where('id_karyawan', $id_karyawan);
            $this->db->update('data_karyawan', $update_data_karyawan);
        }

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $message = '<font color="#FF0000"><i class="fa fa-exclamation-triangle">&nbsp;</i>Data gagal diapprove</font>';
            return __response_update(false,["message"=>$message]);
        }else{
            $this->db->trans_commit();
            if($apv_direksi == "4"){
                $message = 'Data PKWT berhasil disetujui';
            }else{
                $message = 'Data PKWT berhasil ditolak';
            }

            $this->_send_notifikasi($apv_direksi, $id_pkwt);

            return __response_update(true,["message"=>$message]);
        }
    }

    public function verifikasi_form_all(){
        $this->load->view('pkwt/baru/form_approval_all', $data);
    }

    public function verifikasi_approve_all(){
        $this->nama_lengkap = $this->session->userdata('nama_user');
        $this->nik          = $this->session->userdata('nik');
        
        $path_ttd           = $this->input->post('path_ttd');
        $nm_direktur        = $this->input->post('nm_direktur');
        $apv_direksi        = $this->input->post('status');
        $ket_tolak          = $this->input->post('ket_tolak');
        $array_verifikasi   = json_decode($this->input->post('array_verifikasi')); // object

        $pkwt_update = array();
        $gaji_insert = array();
        $tgl_kontrak_update = array();
        $tunj_insert = array();
        foreach($array_verifikasi as $verif){
            $id_pkwt        = $verif->value;
            $get_pkwt       = $this->_get_data_pkwt($id_pkwt);
            $no_pkwt        = $get_pkwt->no_pkwt;
            $id_karyawan    = $get_pkwt->id_karyawan;

            // START DATA PKWT
            if($apv_direksi == '4'){
                $sourceFilePath = $this->config->item('base_image').$path_ttd;

                // START PINDAH TTD DIREKTUR
                $path_master_ttd_direksi = $this->config->item('base_upload').$path_ttd;

                if (file_exists($path_master_ttd_direksi)) {
                    // deteksi ekstension
                    $file_info      = pathinfo($path_master_ttd_direksi);
                    $file_extension = isset($file_info['extension']) ? $file_info['extension'] : '';

                    // nama file
                    $sub_pkwt = str_replace('/', '_', $no_pkwt);
                    $nama_file = $sub_pkwt.'_'.$id_karyawan.'_'.date("YmdHis").'.'.$file_extension;
                    $path_apv_ttd_direksi = $this->config->item('base_upload').$this->id_company.'/pkwt/apv_direksi';

                    if (!file_exists($path_apv_ttd_direksi)) {
                        mkdir($path_apv_ttd_direksi, 0755, true);
                    }
                    
                    $copy = copy($path_master_ttd_direksi, $path_apv_ttd_direksi.'/'.$nama_file);

                    if ($copy) {
                        // berhasil
                    } else {
                        echo "gagal: " . error_get_last()['message'];
                    }
                } else {
                    echo "Source file does not exist";
                }
                // END PINDAH TTD DIREKTUR

                $path_ttd_direktur = array('ttd_direktur'       => $this->id_company.'/pkwt/apv_direksi/'.$nama_file);
            }else{
                $path_ttd_direktur = array();
            }

            $data_pkwt  = array('md5(id_pkwt)'  => $id_pkwt,
                            'apv_direksi'       => $apv_direksi,
                            'status'            => $apv_direksi,
                            'nm_direktur'       => $nm_direktur,
                            'ket_tolak'         => $ket_tolak,
                            'tgl_apv_direksi'   => date("Y-m-d H:i:s"),
                            'user_apv_direksi'  => $this->nik. " - ". $this->nama_lengkap);
            // END DATA PKWT

            $data_tgl_kontrak = array('id_karyawan' => $get_pkwt->id_karyawan,
                                        'tgl_aktif_bekerja' => $get_pkwt->tgl_pkwt_mulai,
                                        'tgl_berhenti_bekerja' => $get_pkwt->tgl_pkwt_selesai);


            $pkwt_update[]          = array_merge($data_pkwt,$path_ttd_direktur);
            $tgl_kontrak_update[]   = $data_tgl_kontrak;
            $id_karyawan_arr[]      = $id_karyawan;
        }

        # Modifikasi Array Tunjangan Insert
        $flattenedArray = [];
        foreach ($tunj_insert as $nestedArray) {
            foreach ($nestedArray as $item) {
                $flattenedArray[] = $item;
            }
        }

        $this->db->trans_start();

        // 1. update pkwt
        $this->db->where('id_company', $this->id_company);
        $this->db->update_batch('pkwt_data', $pkwt_update, 'md5(id_pkwt)');

        if($apv_direksi == '4'){
            // 2. update tgl kontrak
            $this->db->where('id_company', $this->id_company);
            $this->db->update_batch('data_karyawan', $tgl_kontrak_update, 'id_karyawan');
        }

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $message = '<font color="#FF0000"><i class="fa fa-exclamation-triangle">&nbsp;</i>Data gagal diapprove</font>';
            return __response_update(false,["message"=>$message]);
        }else{
            $this->db->trans_commit();

            if($apv_direksi == "4"){
                $message = 'Data PKWT berhasil disetujui';
            }else{
                $message = 'Data PKWT berhasil ditolak';
            }

            foreach($pkwt_update as $value){
                $this->_send_notifikasi($apv_direksi, $value['id_pkwt']);
            }

            return __response_update(true,["message"=>$message]);
        }
    }

    // Untuk Update Data ketika Diapprove
    private function _get_data_pkwt($id){
        $query = $this->db->select('id_pkwt,id_karyawan,tgl_pkwt_mulai,tgl_pkwt_selesai,no_pkwt')
                            ->from('pkwt_data')
                            ->where('id_company', $this->id_company)
                            ->where('MD5(id_pkwt)', $id)
                            ->get()
                            ->row();
        return $query;
    }

    // Untuk Update Data ketika Diapprove
    private function _cek_gapok($id_karyawan){
        $query = $this->db->select('gapok')
                    ->from('pkwt_gaji_m')
                    ->where('id_company', $this->id_company)
                    ->where('id_karyawan', $id_karyawan)
                    ->get()
                    ->row()
                    ->gapok;
        return $query;
    }

    public function onchange_path_ttd(){
        $id_karyawan = $this->input->get('id_karyawan');

        $query = $this->db->select('id_karyawan, nm_karyawan, path_ttd')
                                ->from('pkwt_direktur')
                                ->where("id_company", $this->id_company)
                                ->where("id_karyawan", $id_karyawan)
                                ->get()
                                ->row();

        $result = [];
        if($query){
            $result = ["success" => true,
                        "data" => [ "nm_karyawan"=>$query->nm_karyawan,
                                    "path_ttd" => $query->path_ttd] ];
        }else{
            $result = ["success" => false,
                        "message" => "Data gagal ditampilkan"];
        }
        
        echo json_encode($result);      
        
    }
    
    private function _get_approval($kode) {
    switch ($kode) {
        case '1' : return '<span class="badge badge-light">Belum Disetujui</span>';
            break;
        case '2' : return '<span class="badge badge-danger">Dibatalkan</span>';
            break;
        case '3' : return '<span class="badge badge-danger">Ditolak</span>';
            break;
        case '4' : return '<span class="badge badge-success">Disetujui</span>';
            break;
        default : return '-';
            break;
        }
    }

    private function _send_notifikasi($act, $id_pkwt){
        $data_pkwt = $this->db->select('id_pkwt,token_fcm,no_pkwt')
                            ->from('pkwt_data')
                            ->where('md5(id_pkwt)', $id_pkwt)
                            ->join('users', 'users.id_karyawan = pkwt_data.id_karyawan')
                            ->get()
                            ->row();

        $id_pkwt = $data_pkwt->id_pkwt;
        $token_fcm = $data_pkwt->token_fcm;

        $base = $this->config->item('url_api');

        if($act == '4'){
            #setujui
            $title = "PKWT Sudah Disetujui";
            $body = "PKWT dengan Nomor ". $data->no_pkwt. ' sudah ditandangani oleh Direktur';
        }elseif($act == '3'){
            #tolak
            $title = "PKWT Ditolak";
            $body = "PKWT dengan Nomor ". $data->no_pkwt. ' ditolak Direktur';
        }else{
            echo "status tidak diketahui"; die();
        }

        $params_fcm = [
            'token_fcm' => $token_fcm,
            'route'     => '/detail_pkwt_saya',
            'title'     => $title,
            'body'      => $body,
            'id_ref'    => $id_pkwt
        ];

        $params = [
            'params_fcm'   => json_encode($params_fcm),
            'url_consumer' => $base."/notifikasi/fcm/send",
            'nm_aplikasi' => 'absenku_v3_230901_gkm'
            // 'nm_aplikasi' => 'fcm'
        ];

        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://mb-producer.absenku.com/fcm?".http_build_query($params)); 
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'authentication: absenku123**'
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, $this->config->item('user_agent'));
        $output = curl_exec($ch); 

        curl_close($ch);
    }
}