<?php
error_reporting(0);
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Fungsi
{

    private $ci;

    public function __construct()
    {
        $this->ci = &get_instance();
        // load language
        $this->ci->load->helper('language');
        $siteLang = $this->ci->session->userdata('site_lang');
        $this->ci->lang->load('content', $siteLang ?: 'indonesia');

        $this->id_company = $this->ci->session->userdata("id_company");
    }

    public function getNextId($tableName = null, $fieldName = null, $id_company = null, $lengthNumber = null)
    {
        $current_month = date('Ym');
        $len_substring = -6 - $lengthNumber;
        $gedId = $this->ci->db->query("SELECT MAX($fieldName) as id
                                            FROM $tableName
                                            WHERE id_company = '$id_company'
                                            AND SUBSTRING($fieldName,$len_substring,6) = '$current_month'");

        if ($gedId->num_rows() > 0) {
            $current_id = substr($gedId->row()->id, "-" . $lengthNumber);
            $nextId =  $id_company . $current_month . sprintf("%0" . $lengthNumber . "d", ($current_id + 1));
        } else {
            $nextId = $id_company . $current_month . sprintf("%0" . $lengthNumber . "d", 1);
        }

        return $nextId;
    }

    public function decrypt_idkaryawan($id_karyawan = null)
    {
        $query = $this->ci->db->select("id_karyawan")
            ->from("data_karyawan")
            ->where("MD5(id_karyawan)", $id_karyawan)
            ->get()
            ->row();
        return $query->id_karyawan;
    }

    public function decrypt_idtemp($id_temp = null)
    {
        $query = $this->ci->db->select("id_temp")
            ->from("data_karyawan_temp")
            ->where("MD5(id_temp)", $id_temp)
            ->get()
            ->row();
        return $query->id_temp;
    }

    public function delete_fileupload($predir = null)
    {
        $path = $this->ci->config->item('base_upload') . $predir;
        if (is_file($path)) {
            unlink($path);
        }
    }

    // Delete Directory
    public function delete_directory($dir, $id_karyawan)
    {
        $this->ci->load->helper('file'); // Load codeigniter file helper

        $dir_path  =  $this->ci->config->item('base_upload') . $this->id_company . '/' . $dir . '/' . $id_karyawan;  // For check folder exists
        $del_path  =  $this->ci->config->item('base_upload') . $this->id_company . '/' . $dir . '/' . $id_karyawan . '/'; // For Delete folder

        if (is_dir($dir_path)) {
            delete_files($del_path, true); // Delete files into the folder
            rmdir($del_path); // Delete the folder
            return true;
        } else {
            return false;
        }
    }

    public function tgl_indo($tanggal)
    {
        $bulan = array(
            1 =>   'Januari',
            'Februari',
            'Maret',
            'April',
            'Mei',
            'Juni',
            'Juli',
            'Agustus',
            'September',
            'Oktober',
            'November',
            'Desember'
        );
        $pecahkan = explode('-', $tanggal);

        if ($tanggal == "0000-00-00" or $tanggal == "") {
            $hasil = "";
        } else {
            $hasil = $pecahkan[2] . ' ' . $bulan[(int)$pecahkan[1]] . ' ' . $pecahkan[0];
        }
        return $hasil;
    }

    public function get_bulan($tanggal)
    {
        $bulan = array(
            1 =>   'Januari',
            'Februari',
            'Maret',
            'April',
            'Mei',
            'Juni',
            'Juli',
            'Agustus',
            'September',
            'Oktober',
            'November',
            'Desember'
        );
        $pecahkan = explode('-', $tanggal);
        if ($tanggal == "00-0000" or $tanggal == "") {
            $hasil = "";
        } else {
            $hasil = $bulan[(int)$pecahkan[0]];
        }
        return $hasil;
    }

    public function get_tahun($tanggal)
    {

        $pecahkan = explode('-', $tanggal);
        if ($tanggal == "00-0000" or $tanggal == "") {
            $hasil = "";
        } else {
            $hasil = $pecahkan[1];
        }
        return $hasil;
    }

    public function jkel($jkel)
    {

        if ($jkel == "L") {
            return $this->ci->lang->line('laki_laki');
        } else if ($jkel == "P") {
            return $this->ci->lang->line('perempuan');
        } elseif ($jkel == "uknown") {
            return $this->ci->lang->line('belum_diatur');
        } else {
            return '-';
        }
    }

    public function status_pekerjaan($status)
    {

        if ($status == "1") {
            $status = $this->ci->lang->line('kontrak');
        } elseif ($status == "2") {
            $status = $this->ci->lang->line('tetap');
        } else {
            $status = $this->ci->lang->line('promosi');
        }
        return $status;
    }

    public function status_karyawan($sk)
    {

        if ($sk == "1") {
            $ret = '<div class="badge badge-warning">' . $this->ci->lang->line('kontrak') . '</div>';
        } elseif ($sk == "2") {
            $ret = '<div class="badge badge-primary">' . $this->ci->lang->line('tetap') . '</div>';
        } elseif ($sk == "3") {
            $ret = '<div class="badge badge-info">' . $this->ci->lang->line('izin_belajar') . '</div>';
        } elseif ($sk == "4") {
            $ret = '<div class="badge badge-info">' . $this->ci->lang->line('tugas_belajar') . '</div>';
        } elseif ($sk == "5") {
            $ret = '<div class="badge badge-danger">' . $this->ci->lang->line('resign') . '</div>';
        } elseif ($sk == "6") {
            $ret = '<div class="badge badge-danger">' . $this->ci->lang->line('dikeluarkan') . '</div>';
        } elseif ($sk == "7") {
            $ret = '<div class="badge badge-danger">' . $this->ci->lang->line('pensiun') . '</div>';
        }

        return $ret;
    }

    public function lock_area($sk)
    {

        if ($sk == "1") {
            $ret = $this->ci->lang->line('ya');
        } else {
            $ret = $this->ci->lang->line('tidak');
        }

        return $ret;
    }

    function isHoliday2($id_karyawan, $tgl)
    {
        $CI = &get_instance();
        $CI->load->database();

        $tanggal = strtotime($tgl);
        $hari = date('w', $tanggal);

        $query = $CI->db->query("SELECT id_company FROM data_karyawan WHERE id_karyawan = '" . $id_karyawan . "'");
        $cabang = $CI->db->query("SELECT id_cabang FROM data_karyawan WHERE id_karyawan = '" . $id_karyawan . "'")->row()->cabang;

        $cek_shift = $CI->db->query("SELECT data_shift_karyawan.id_shift_karyawan, data_shift_karyawan.id_master_shift, master_shift.kode_shift FROM data_shift_karyawan INNER JOIN master_shift ON data_shift_karyawan.id_master_shift = master_shift.id_master_shift WHERE data_shift_karyawan.id_karyawan = '" . $id_karyawan . "' AND data_shift_karyawan.id_company = '" . $query->row()->id_company . "' AND data_shift_karyawan.tanggal = '" . $tgl . "'");

        if ($cek_shift->num_rows() > 0) {

            if ($cek_shift->row()->kode_shift != 'OFF') {
                $hasil = 0;
            } else {
                $hasil = 1;
            }
        } else {
            $lib = $CI->db->query("SELECT id_jam_kerja FROM jam_kerja WHERE id_company = '" . $query->row()->id_company . "' AND hari = '" . $hari . "' AND id_cabang = '" . $cabang . "'");

            $cek_libur1 = $CI->db->query("SELECT libur FROM jam_kerja WHERE id_company = '" . $query->row()->id_company . "' AND hari = '" . $hari . "' " . (($lib->num_rows() > 0) ? "AND id_cabang = '" . $cabang . "'" : "") . " ");
            if (isset($cek_libur1->row()->libur)) {
                $libur1 = $cek_libur1->row()->libur;
            } else {
                $libur1 = "-";
            }
            $libur2 = $CI->db->query("SELECT id FROM holidays WHERE id_company = '" . $query->row()->id_company . "' AND tanggal = '" . $tgl . "'")->num_rows();

            if ($libur1 != "1" and $libur2 == 0) {
                $hasil = 0;
            } else {
                $hasil = 1;
            }
        }

        return $hasil;
    }

    function isHoliday($date)
    {
        $CI = &get_instance();
        $company = $CI->session->userdata('id_company');

        $weekDay = date('w', strtotime($date));

        if (!($weekDay == 0 || $weekDay == 6)) {
            $CI = &get_instance();
            $CI->load->model('db_model');

            $query = $CI->db_model->get('holidays', 'keterangan', array(
                'tanggal' => date('Y-m-d', strtotime($date)),
                'id_company' => $company
            ));

            if ($query->num_rows() > 0) {
                $data = $query->row();
                $hasil = 1;
            } else {
                $hasil = ($weekDay == 0 || $weekDay == 6);
            }
        } else {
            $cek = $CI->db->where('hari', $weekDay)->where('id_company', $company)->get('jam_kerja')->row();
            if (!empty($cek)) {
                $hasil = $cek->libur;
            } else {
                $hasil = ($weekDay == 0 || $weekDay == 6);
            }
        }

        return $hasil;
    }

    //     function mysql_date_2_views($datetime){
    //         $timestamp = strtotime($datetime);
    //         //$day = $this->konversi_hari(date('D', $timestamp));

    //         $date = explode(' ',$datetime)[0];
    //         $time = explode(' ',$datetime)[1];
    // //      print_r($date);
    //         $tgl = explode('-',$date)[2];
    //         $bulan = $this->konversi_bulan(explode('-',$date)[1]);
    //         $tahun = explode('-',$date)[0];
    //         $tanggal_waktu = "$tgl $bulan $tahun $time";
    //         //$tanggal_waktu = "$tgl $bulan $tahun";
    //         return $tanggal_waktu;
    //     }

    function konversi_date($datetime)
    {
        $timestamp = strtotime($datetime);
        //$day = $this->konversi_hari(date('D', $timestamp));

        $date = explode(' ', $datetime)[0];
        $time = explode(' ', $datetime)[1];
        //      print_r($date);
        $tgl = explode('-', $date)[2];
        $bulan = $this->konversi_bulan(explode('-', $date)[1]);
        $tahun = explode('-', $date)[0];
        $tanggal_waktu = "$tgl $bulan $tahun";
        //$tanggal_waktu = "$tgl $bulan $tahun";
        return $tanggal_waktu;
    }

    function konversi_date_slash($datetime)
    {
        $timestamp = strtotime($datetime);
        //$day = $this->konversi_hari(date('D', $timestamp));

        $date = explode(' ', $datetime)[0];
        $time = explode(' ', $datetime)[1];
        //      print_r($date);
        $tgl = explode('-', $date)[2];
        $bulan = explode('-', $date)[1];
        $tahun = explode('-', $date)[0];
        $tanggal_waktu = "$tgl/$bulan/$tahun";

        return $tanggal_waktu;
    }

    function konversi_datetime($datetime)
    {
        $timestamp = strtotime($datetime);
        //$day = $this->konversi_hari(date('D', $timestamp));

        $date = explode(' ', $datetime)[0];
        $time = explode(' ', $datetime)[1];
        //      print_r($date);
        $tgl = explode('-', $date)[2];
        $bulan = explode('-', $date)[1];
        $tahun = explode('-', $date)[0];
        $tanggal_waktu = "$tgl-$bulan-$tahun $time";
        //$tanggal_waktu = "$tgl $bulan $tahun";
        return $tanggal_waktu;
    }

    function mysql_date_2_date($date)
    {
        $tgl = explode('-', $date)[2];
        $bulan = $this->konversi_bulan(explode('-', $date)[1]);
        $tahun = explode('-', $date)[0];
        $tanggal_waktu = "$tgl $bulan $tahun";
        //$tanggal_waktu = "$tgl $bulan $tahun";
        return $tanggal_waktu;
    }

    function mysql_date_3_date($date)
    {
        $tgl = explode('/', $date)[0];
        $bulan = $this->konversi_bulan(explode('/', $date)[1]);
        $tahun = explode('/', $date)[2];
        $tanggal_waktu = "$tgl $bulan $tahun";
        //$tanggal_waktu = "$tgl $bulan $tahun";
        return $tanggal_waktu;
    }

    function konversi_bulan($bulan)
    {
        switch ($bulan) {
            case '01':
                return 'Januari';
                break;
            case '02':
                return 'Februari';
                break;
            case '03':
                return 'Maret';
                break;
            case '04':
                return 'April';
                break;
            case '05':
                return 'Mei';
                break;
            case '06':
                return 'Juni';
                break;
            case '07':
                return 'Juli';
                break;
            case '08':
                return 'Agustus';
                break;
            case '09':
                return 'September';
                break;
            case '10':
                return 'Oktober';
                break;
            case '11':
                return 'November';
                break;
            case '12':
                return 'Desember';
                break;
            default:
                return '-';
                break;
        }
    }

    function konversi_lock_area($id_lok)
    {
        $target = explode(",", $id_lok);

        $target_name_arr = array();
        foreach ($target as $dat) {
            $target_name_arr[] = $this->get_nama_lokasi($dat);
        }
        $target_id = implode(', ', $target_name_arr);

        return $target_id;
    }

    function _gmt($gmt = '')
    {
        switch ($gmt) {
            case '+07:00':
                return 'WIB';
                break;
            case '+08:00':
                return 'WITA';
                break;
            case '+09:00':
                return 'WIT';
                break;
            default:
                return '';
                break;
        }
    }

    function get_izin_kar($tanggal, $id, $level)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query_data_izin = $CI->db_model->get('data_izin', 'data_izin.id_cabang, data_izin.id_departemen, data_izin.tgl_mulai_izin, data_izin.tgl_selesai_izin, data_izin.id_izin, ', 'md5(data_izin.id_izin) = "' . $id . '"')->row();

        $cabang      = $query_data_izin->id_cabang;
        $departemen  = $query_data_izin->id_departemen;
        $tgl_mulai   = $query_data_izin->tgl_mulai_izin;
        $tgl_selesai = $query_data_izin->tgl_selesai_izin;
        $id_izin     = $query_data_izin->id_izin;

        if ($level == '7') {
            $cek_kar = $CI->db->query("SELECT id_karyawan, approval_spv as status_approval FROM data_izin WHERE id_company = '$this->id_company' AND id_izin != '$id_izin' AND approval_spv IN('1','4','5') AND id_cabang = '$cabang' AND id_departemen = '$departemen' AND ((tgl_mulai_izin = '$tanggal' or tgl_selesai_izin = '$tanggal') or ('$tanggal' BETWEEN tgl_mulai_izin AND tgl_selesai_izin))");
        } elseif ($level == '2') {
            $cek_kar = $CI->db->query("SELECT id_karyawan, approval_kedep as status_approval FROM data_izin WHERE id_company = '$this->id_company' AND id_izin != '$id_izin' AND approval_kedep IN('1','4','5') AND id_cabang = '$cabang' AND id_departemen = '$departemen' AND ((tgl_mulai_izin = '$tanggal' or tgl_selesai_izin = '$tanggal') or ('$tanggal' BETWEEN tgl_mulai_izin AND tgl_selesai_izin))");
        } elseif ($level == '5') {
            $cek_kar = $CI->db->query("SELECT id_karyawan, approval_kacab as status_approval FROM data_izin WHERE id_company = '$this->id_company' AND id_izin != '$id_izin' AND approval_kacab IN('1','4','5') AND id_cabang = '$cabang' AND id_departemen = '$departemen' AND ((tgl_mulai_izin = '$tanggal' or tgl_selesai_izin = '$tanggal') or ('$tanggal' BETWEEN tgl_mulai_izin AND tgl_selesai_izin))");
        } elseif ($level == '1') {
            $cek_kar = $CI->db->query("SELECT id_karyawan, approval_hrd as status_approval FROM data_izin WHERE id_company = '$this->id_company' AND id_izin != '$id_izin' AND approval_hrd IN('1','4','5') AND id_cabang = '$cabang' AND id_departemen = '$departemen' AND ((tgl_mulai_izin = '$tanggal' or tgl_selesai_izin = '$tanggal') or ('$tanggal' BETWEEN tgl_mulai_izin AND tgl_selesai_izin))");
        } elseif ($level == '4') {
            $cek_kar = $CI->db->query("SELECT id_karyawan, approval_direksi as status_approval FROM data_izin WHERE id_company = '$this->id_company' AND id_izin != '$id_izin' AND approval_direksi IN('1','4','5') AND id_cabang = '$cabang' AND id_departemen = '$departemen' AND ((tgl_mulai_izin = '$tanggal' or tgl_selesai_izin = '$tanggal') or ('$tanggal' BETWEEN tgl_mulai_izin AND tgl_selesai_izin))");
        }

        $target_id = array(
            'target_id' => [],
            'target_status' => []
        );

        if ($cek_kar->num_rows() > 0) {
            foreach ($cek_kar->result() as $dat) {
                $target_id['target_id'][] = $this->get_nama_kar($dat->id_karyawan);
                $target_id['target_status'][] = $this->get_approval($dat->status_approval);
            }
        }

        return $target_id;
    }

    public function format_date($date, $separator = '/')
    {
        //dd/mm/yyyy
        return substr($date, 8, 2) . $separator . substr($date, 5, 2) . $separator . substr($date, 0, 4);
    }

    public function format_date_strip($date, $separator = '-')
    {
        //dd-mm-yyyy
        return substr($date, 8, 2) . $separator . substr($date, 5, 2) . $separator . substr($date, 0, 4);
    }

    public function reverse_date($date, $separator = '-')
    {
        //yyyy-dd-mm
        return substr($date, 6, 4) . $separator . substr($date, 0, 2) . $separator . substr($date, 3, 2);
    }

    public function reverse_date2($date, $separator = '-')
    {
        //yyyy-mm-dd
        return substr($date, 6, 4) . $separator . substr($date, 3, 2) . $separator . substr($date, 0, 2);
    }

    function kode_to_id_shift($id, $company)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get(
            'master_shift',
            'id_master_shift',
            array('kode_shift' => $id, 'id_company' => $company),
            'id_master_shift ASC'
        );
        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = $data->id_master_shift;
        } else {
            $hasil = "0";
        }

        return $hasil;
    }

    function get_email($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('data_karyawan', 'email', array('id_karyawan' => $id), 'id_karyawan ASC');

        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = $data->email;
        } else {
            $hasil = "-";
        }

        return $hasil;
    }

    function get_nama_siswa($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('data_karyawan', 'nama_lengkap', array('id_karyawan' => $id), 'id_karyawan ASC');

        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = strtoupper($data->nama_lengkap);
        } else {
            $hasil = "-";
        }

        return $hasil;
    }

    public function get_shift($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('master_shift', 'nama_shift', array('id_master_shift' => $id), 'id_master_shift ASC');
        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = $data->nama_shift;
        } else {
            $hasil = "-";
        }

        return $hasil;
    }

    public function get_kode_shift($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('master_shift', 'kode_shift', array('id_master_shift' => $id), 'id_master_shift ASC');
        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = $data->kode_shift;
        } else {
            $hasil = "-";
        }

        return $hasil;
    }

    function get_nama_kar($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('data_karyawan', 'nama_lengkap', array('id_karyawan' => $id), 'id_karyawan ASC');

        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = strtoupper($data->nama_lengkap);
        } else {
            $hasil = "-";
        }

        return $hasil;
    }

    function get_nama_kar_normal($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('data_karyawan', 'nama_lengkap', array('id_karyawan' => $id), 'id_karyawan ASC');

        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = $data->nama_lengkap;
        } else {
            $hasil = "-";
        }

        return $hasil;
    }

    function get_data_nama_dep($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('master_departemen', 'nama', array('id_departemen' => $id), 'id_departemen ASC');
        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = $data->nama;
        } else {
            $hasil = "-";
        }

        return $hasil;
    }

    function get_kode_dep($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('master_departemen', 'kode', array('id_departemen' => $id), 'id_departemen ASC');
        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = $data->kode;
        } else {
            $hasil = "-";
        }

        return $hasil;
    }

    function get_nama_cab($id)
    { // ID CABANG TIDAK DI ENKRIPSI
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('master_cabang', 'nama', array('id_cabang' => $id), 'id_cabang ASC');
        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = $data->nama;
        } else {
            $hasil = "-";
        }

        return $hasil;
    }

    function namaCabang($id)
    { // ID CABANG DI ENKRIPSI
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('master_cabang', 'kode, nama', array('md5(id_cabang)' => $id), 'id_cabang ASC');
        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = $data->kode . " - " . $data->nama;
        } else {
            $hasil = "-";
        }

        return $hasil;
    }

    function get_kode_cab($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('master_cabang', 'kode', array('id_cabang' => $id), 'id_cabang ASC');
        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = $data->kode;
        } else {
            $hasil = "-";
        }

        return $hasil;
    }

    function get_nama_cab_array($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        foreach ($id as $key) {
            $query = $CI->db_model->get('master_cabang', 'nama', array('id_cabang' => $key), 'id_cabang ASC');
        }

        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = $data->nama;
        } else {
            $hasil = "-";
        }

        return $hasil;
    }

    function get_nama_jab($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('master_jabatan', 'nama', array('id_jabatan' => $id), 'id_jabatan ASC');
        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = $data->nama;
        } else {
            $hasil = "-";
        }

        return $hasil;
    }

    function get_kode_jab($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('master_jabatan', 'kode_jabatan', array('id_jabatan' => $id), 'id_jabatan ASC');
        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = $data->kode_jabatan;
        } else {
            $hasil = "-";
        }

        return $hasil;
    }

    function get_nama_level($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $this->code_lang = $this->ci->session->userdata("code_lang");
        if($this->code_lang == 'en'){
            $CI->db->select('lang_en as level');
        }else{
            $CI->db->select('lang_id as level');
        }

        // $query = $CI->db_model->get('usergroup', 'level', array('id' => $id), 'id ASC');
        $query = $CI->db->select("id,urutan")
                            ->from('usergroup')
                            ->where('id', $id)
                            ->order_by('id')
                            ->get();
                            
        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = $data->level;
        } else {
            $hasil = "-";
        }

        return $hasil;
    }

    function get_logo($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('master_company', 'url_logo', array('id_company' => $id));
        if ($query->num_rows() > 0) {
            $data = $query->row();
            $hasil = $data->url_logo;
        } else {
            $hasil = "-";
        }

        return $hasil;
    }

    function get_level_approval_izin($level)
    {
        if ($level == '3') {
            $data = "2,1";
        } elseif ($level == '7') {
            $data = "2,1";
        } elseif ($level == '2') {
            $data = "5,1";
        } elseif ($level == '5') {
            $data = "1";
        } elseif ($level == '4') {
            $data = "1";
        }

        return $data;
    }

    function get_level_approval_lembur($level)
    {
        if ($level == '3') {
            $data = "2";
        } elseif ($level == '7') {
            $data = "2";
        } elseif ($level == '2') {
            $data = "5";
        } elseif ($level == '5') {
            $data = "4";
        } elseif ($level == '4') {
            $data = "";
        }

        return $data;
    }

    function get_level_approval_reimburse($level)
    {
        if ($level == '3') {
            $data = "2,6";
        } elseif ($level == '7') {
            $data = "2,6";
        } elseif ($level == '2') {
            $data = "5,6";
        } elseif ($level == '5') {
            $data = "6";
        } elseif ($level == '4') {
            $data = "6";
        }

        return $data;
    }

    public function get_approval_reimburse($kode)
    {
        switch ($kode) {
            case '1':
                return '<span class="badge badge-secondary">Menunggu</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-warning">Direvisi</span>';
                break;
            case '5':
                return '<span class="badge badge-primary">Disetujui</span>';
                break;
            case '6':
                return '<span class="badge badge-secondary">Menunggu</span>';
                break;
            default:
                return '';
                break;
        }
    }

    public function get_approval($kode)
    {   
        switch ($kode) {
            case '1':
                return '<span class="badge badge-warning">'.$this->ci->lang->line('proses').'</span>';
                break;
            case '2':
                return '<span class="badge badge-danger">'.$this->ci->lang->line('dibatalkan').'</span>';
                break;
            case '3':
                return '<span class="badge badge-danger">'.$this->ci->lang->line('ditolak').'</span>';
                break;
            case '4':
                return '<span class="badge badge-success">'.$this->ci->lang->line('disetujui').'</span>';
                break;
            case '5':
                return '<span class="badge badge-primary">'.$this->ci->lang->line('menunggu').'</span>';
                break;
            default:
                return '-';
                break;
        }
    }

    public function get_approval_lembur($kode)
    {
        switch ($kode) {
            case '1':
                return '<span class="badge badge-warning">Proses</span>';
                break;
            case '2':
                return '<span class="badge badge-dark">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;
            case '5':
                return '<span class="badge badge-primary">Menunggu</span>';
                break;
            default:
                return '-';
                break;
        }
    }

    public function status_approval_lembur($kode)
    {
        switch ($kode) {
            case '1':
                return 'Proses';
                break;
            case '2':
                return 'Dibatalkan';
                break;
            case '3':
                return 'Ditolak';
                break;
            case '4':
                return 'Disetujui';
                break;
            case '5':
                return 'Menunggu';
                break;
            default:
                return '-';
                break;
        }
    }

    public function approve_data($value)
    {
        //$value = "7,2,1";
        $data = [];
        $val_arr = explode(',', $value);
        foreach ($val_arr as $key) {
            if ($key == "7") {
                $data['approval_spv'] = '1';
            } elseif ($key == "2") {
                $data['approval_kedep'] = '1';
            } elseif ($key == "5") {
                $data['approval_kacab'] = '1';
            } elseif ($key == "1") {
                $data['approval_hrd'] = '1';
            } elseif ($key == "4") {
                $data['approval_direksi'] = '1';
            }
        }
        //return array_merge($result,$data);
        //print_r($data);
        return $data;
    }

    public function approved_data($value)
    {
        $data = [];
        $val_arr = explode(',', $value);
        foreach ($val_arr as $key) {
            if ($key == "7") {
                $data['approval_spv'] = '4';
            } elseif ($key == "2") {
                $data['approval_kedep'] = '4';
            } elseif ($key == "5") {
                $data['approval_kacab'] = '4';
            } elseif ($key == "1") {
                $data['approval_hrd'] = '4';
            } elseif ($key == "4") {
                $data['approval_direksi'] = '4';
            }
        }
        //return array_merge($result,$data);
        //print_r($data);
        return $data;
    }

    //query
    //dropdown
    function dropdown_cabang($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('master_cabang', 'id_cabang, nama, kode', array('id_cabang' => $id));

        return $query;
    }

    function dropdown_cabang_pusat($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('master_cabang', 'id_cabang, nama, kode', array('flag' => "1", "id_company" => $id));

        return $query;
    }

    function dropdown_departemen($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('master_departemen', 'id_departemen, nama, kode', array('id_departemen' => $id));

        return $query;
    }

    function dropdown_jabatan($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('master_jabatan', 'id_jabatan, nama, kode_jabatan', array('id_jabatan' => $id));

        return $query;
    }

    function dropdown_jenis_izin($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('master_jenis_izin', 'kode_izin, nama', array('kode_izin' => $id));

        return $query;
    }

    function dropdown_karyawan($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('data_karyawan', 'id_karyawan, nama_lengkap', array('id_karyawan' => $id));

        return $query;
    }

    function dropdown_jamkerja($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db_model->get('master_shift', 'id_master_shift, nama_shift, kode_shift', array('id_master_shift' => $id));

        return $query;
    }
    //dropdown

    function data_reimburse($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db->select("reimbursement_data.*, reimbursement_jenis.jenis_plafon as jenis_plafon, reimbursement_jenis.max_nominal_plafon as max_plafon")
            ->from('reimbursement_data')
            ->join("reimbursement_jenis", "reimbursement_jenis.id_jenis_reimbursement = reimbursement_data.id_jenis_reimbursement", "left")
            ->where("reimbursement_data.id_pengajuan_reimbursement", $id)->get();

        return $query;
    }

    function jumlah_nominal($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db->select("SUM(reimbursement_data.nominal) as total_nominal")->from("reimbursement_data")
            ->where("id_pengajuan_reimbursement", $id)->get()->row()->total_nominal;

        return $query;
    }

    function jumlah_disetujui($id)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db->select("SUM(reimbursement_data.nominal_disetujui) as total_disetujui")->from("reimbursement_data")
            ->where("id_pengajuan_reimbursement", $id)->get()->row()->total_disetujui;

        return $query;
    }

    function total_nominal($departemen, $pawal, $pakhir)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db->select("reimbursement_data.nominal as nominal")->from("reimbursement_data")
            ->join("reimbursement_pengajuan", "reimbursement_pengajuan.id = reimbursement_data.id_pengajuan_reimbursement")
            ->where("reimbursement_pengajuan.id_departemen", $departemen)
            ->where("reimbursement_pengajuan.tgl_pengajuan >=", $pawal)
            ->where("reimbursement_pengajuan.tgl_pengajuan <=", $pakhir)
            ->where("reimbursement_pengajuan.apv_finance", "5")->get();

        return $query;
    }

    function total_disetujui($departemen, $pawal, $pakhir)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db->select("reimbursement_data.nominal_disetujui as nominal_setuju")->from("reimbursement_data")
            ->join("reimbursement_pengajuan", "reimbursement_pengajuan.id = reimbursement_data.id_pengajuan_reimbursement")
            ->where("reimbursement_pengajuan.id_departemen", $departemen)
            ->where("reimbursement_pengajuan.tgl_pengajuan >=", $pawal)
            ->where("reimbursement_pengajuan.tgl_pengajuan <=", $pakhir)
            ->where("reimbursement_pengajuan.apv_finance", '5')->get();

        return $query;
    }

    function total_nominal_karyawan($karyawan, $pawal, $pakhir, $where_co)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db->select("reimbursement_data.nominal as nominal")->from("reimbursement_data")
            ->join("reimbursement_pengajuan", "reimbursement_pengajuan.id = reimbursement_data.id_pengajuan_reimbursement")
            ->where("reimbursement_pengajuan.id_karyawan", $karyawan)
            ->where("reimbursement_pengajuan.tgl_pengajuan >=", $pawal)
            ->where("reimbursement_pengajuan.tgl_pengajuan <=", $pakhir)
            ->where($where_co, "5")->get();

        return $query;
    }

    function total_disetujui_karyawan($karyawan, $pawal, $pakhir, $where_co)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $query = $CI->db->select("reimbursement_data.nominal_disetujui as nominal_setuju")->from("reimbursement_data")
            ->join("reimbursement_pengajuan", "reimbursement_pengajuan.id = reimbursement_data.id_pengajuan_reimbursement")
            ->where("reimbursement_pengajuan.id_karyawan", $karyawan)
            ->where("reimbursement_pengajuan.tgl_pengajuan >=", $pawal)
            ->where("reimbursement_pengajuan.tgl_pengajuan <=", $pakhir)
            ->where($where_co, '5')->get();

        return $query;
    }

    function last_approval($karyawan)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $data_karyawan = $CI->db->select("data_karyawan.*, master_jabatan.level_user as usergroup")->from("data_karyawan")->join("master_jabatan", "master_jabatan.id_jabatan = data_karyawan.id_jabatan")->where("data_karyawan.id_karyawan", $karyawan)->get()->row();

        $level_approval = $CI->db_model->get('p_approval_reimbursement', 'level_approval',  array('level_user' => $data_karyawan->usergroup, 'id_cabang' => $data_karyawan->id_cabang, 'id_company' => $data_karyawan->id_company))->row()->level_approval;
        $get_lev = explode(',', $level_approval);
        $last = end($get_lev);

        return $last;
    }

    function last_approval_izin($karyawan)
    {
        $CI = &get_instance();
        $CI->load->model('db_model');

        $data_karyawan = $CI->db->select("data_karyawan.*, master_jabatan.level_user as usergroup")->from("data_karyawan")->join("master_jabatan", "master_jabatan.id_jabatan = data_karyawan.id_jabatan")->where("data_karyawan.id_karyawan", $karyawan)->get()->row();

        $level_approval = $CI->db_model->get('p_approval_izin', 'level_approval',  array('level_user' => $data_karyawan->usergroup, 'id_cabang' => $data_karyawan->id_cabang, 'id_company' => $data_karyawan->id_company))->row()->level_approval;
        $get_lev = explode(',', $level_approval);
        $last = end($get_lev);
        $first = $get_lev[0];

        return $get_lev;
    }
    //query

    function getInitials($string = null)
    {
        return array_reduce(
            explode(' ', $string),
            function ($initials, $word) {
                $result = sprintf('%s%s', $initials, substr($word, 0, 1));
                $result = strtoupper(strtolower($result));
                return $result;
            }
        );
    }

    // START FUNGSI SALES ACTIVITY
    function check_atasan_get_bawahan_sa(){
        $this->is_sales_atasan = $this->ci->session->userdata("is_sales_atasan");  // jika sales adalah atasan
        $this->is_sales_admin  = $this->ci->session->userdata("is_sales_admin");   // jika sales adalah admin sales
        $this->id_karyawan     = $this->ci->session->userdata("id_karyawan");      // id_karyawan sales

        $data              = array();
        $data['is_atasan'] = false;
    
        if($this->is_sales_atasan == true){
            if($this->is_sales_admin == false){
                $data['is_atasan'] = true;

                $query = $this->ci->db->select('id_karyawan')
                                ->from('sales_approver')
                                ->where('id_company', $this->id_company)
                                ->where('id_atasan', $this->id_karyawan)
                                ->get()
                                ->result();

                $data['list_bawahan'][] = $this->id_karyawan;
                foreach($query as $value) {
                    $data['list_bawahan'][] = $value->id_karyawan;
                }
            }
        }
        
        // $return = array();
        // $return['check_atasan_sa'] = $data;
        // $this->session->set_userdata($return);
        return $data;
    }

    public function approve_izin_sales($mulai = "", $selesai = "", $id_karyawan = ""){
        $CI = &get_instance();
        $CI->load->model('db_model');

        $karyawan = $CI->db->select('id_karyawan, poin, id_company')
                        ->where('MD5(id_karyawan)', $id_karyawan)
                        ->get('sales_target_poin_p')
                        ->row();

        if(!empty($karyawan)){
            // Initial Foreach Tanggal
            $awal     = date_create($mulai);
            $akhir    = date_create(date('Y-m-d', strtotime('+1 days ' . $selesai)));
            $interval = DateInterval::createFromDateString('1 day');
            $period   = new DatePeriod($awal, $interval, $akhir);
    
            $data = array();
            foreach ($period as $dt) {
                $data[] = array(
                    "tgl_trx"     => $dt->format('Y-m-d'),
                    "id_karyawan" => $karyawan->id_karyawan,
                    "poin"        => "0",
                    "id_company"  => $karyawan->id_company,
                    "user_input"  => "Fungsi Approve",
                );
            }
    
            $CI->db->trans_start();
            // 1. delete data
            $CI->db->where("id_company", $karyawan->id_company);
            $CI->db->where("id_karyawan", $karyawan->id_karyawan);
            $CI->db->group_start();
            $CI->db->where("tgl_trx >=", $mulai);
            $CI->db->where("tgl_trx <=", $selesai);
            $CI->db->group_end();
            $CI->db->delete("sales_target_poin_trx");
    
            // 2. insert data
            $CI->db->insert_batch("sales_target_poin_trx" ,$data);
    
            $CI->db->trans_complete();
            if ($CI->db->trans_status() === FALSE) {
                $CI->db->trans_rollback();
                
                $response = array(
                    'status' => false,
                    'keterangan' => 'Data gagal diperbarui',
                );
            } else {
                $CI->db->trans_commit();
                
                $response = array(
                    'status' => true,
                    'keterangan' => 'Data berhasil diperbarui',
                );
            }
        }else{
            $response = array(
                'status' => false,
                'keterangan' => 'Id karyawan tidak ditemukan',
            );
        }
        
        echo json_encode($response);
    }

    function get_data_group(){
        $CI = &get_instance();
        $CI->load->model('db_model');

        $CI->db->select("
                kode AS kode_group,
                nama AS nama_group,
                id_group_m
            ")
            ->from('sales_group_m')
            ->where('id_company', $this->id_company)
            ->order_by('no_urut ASC');

        $this->is_sales_admin    = $this->ci->session->userdata('is_sales_admin');
        $this->sales_admin_group = $this->ci->session->userdata('sales_admin_group');

        if($this->is_sales_admin == true){
            if (!in_array($this->sales_admin_group, ["all", ""])) {
                $CI->db->where_in('id_group_m', explode(',', $this->sales_admin_group));
            }
        }

        return $CI->db->get()->result();
    }

    function cek_adm_satu_grup(){
        $this->level_user        = $this->ci->session->userdata('level_user');
        $this->is_sales_admin    = $this->ci->session->userdata('is_sales_admin');
        $this->sales_admin_group = $this->ci->session->userdata('sales_admin_group');
        // true : admin sales hanya satu grup
        // false : superadmin, admin sales multigrup atau all grup

        if($this->level_user != "1"){
            if($this->sales_admin_group != "all"){
                if(strpos($this->sales_admin_group, ',') !== false){ // jika mengandung koma
                    return false;
                }else{
                    return true;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    function hex2rgb($hex) {
        $hex = str_replace("#", "", $hex);
    
         if(strlen($hex) == 3) {
          $r = hexdec(substr($hex,0,1).substr($hex,0,1));
          $g = hexdec(substr($hex,1,1).substr($hex,1,1));
          $b = hexdec(substr($hex,2,1).substr($hex,2,1));
        } else {
          $r = hexdec(substr($hex,0,2));
          $g = hexdec(substr($hex,2,2));
          $b = hexdec(substr($hex,4,2));
        }
        
        return array($r, $g, $b);
    }
    // END FUNGSI SALES ACTIVITY

    // START FUNGSI PENGATURAN ADMIN
    function get_id_superadmin(){
        $CI = &get_instance();
        $CI->load->model('db_model');

        return $CI->db->select("
                u.id_karyawan,
            ")
            ->from('users AS u')
            ->join('data_karyawan AS dk', 'dk.id_karyawan = u.id_karyawan')
            ->join('master_jabatan AS mj', 'mj.id_jabatan = dk.id_jabatan')
            ->where('u.id_company', $this->id_company)
            ->where('mj.level_user', "1")
            ->get()
            ->row()
            ->id_karyawan;
    }
}
