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

class Saldo_cuti_m extends CI_Model
{
    protected $table = 'data_karyawan';
    protected $table_history_cuti = 'cuti_history';

    function get_datatables($cabang, $departemen)
    {
        $this->_get_datatables_query($cabang, $departemen);
        if ($_GET['length'] != -1) {
            $this->db->limit($_GET['length'], $_GET['start']);
        }
        $query = $this->db->get();
        return $query->result();
    }

    function count_filtered($cabang, $departemen)
    {
        $this->_get_datatables_query($cabang, $departemen);
        $query = $this->db->get();
        return $query->num_rows();
    }

    public function count_all($cabang, $departemen)
    {
        $this->_get_datatables_query($cabang, $departemen);
        return $this->db->count_all_results();
    }
    private function _get_datatables_query($cabang, $departemen)
    {
        if ($cabang != 'all') {
            $this->db->where('mc.id_cabang', $cabang);
        }
        if ($departemen != 'all') {
            $this->db->where('md.id_departemen', $departemen);
        }
        $this->db->select('
                dk.id_karyawan,
                dk.nik,
                dk.nama_lengkap,
                dk.jatah_cuti,
                dk.carry_forward,
                mc.kode as kode_cabang,
                mc.nama as nama_cabang,
                md.kode as kode_departemen,
                md.nama as nama_departemen,
                mj.kode_jabatan as kode_jabatan,
                mj.nama as nama_jabatan,
            ')
            ->from($this->table . ' as dk')
            ->join('master_jabatan as mj', 'mj.id_jabatan = dk.id_jabatan')
            ->join('master_cabang as mc', 'mc.id_cabang = dk.id_cabang')
            ->join('master_departemen as md', 'md.id_departemen = dk.id_departemen', 'left')
            ->where('dk.id_company', $this->id_company)
            ->where_in('dk.status', ['1', '2'])
            ->where_not_in('mj.level_user', ['1', '6']);

        $column_search = array('dk.nik', 'dk.nama_lengkap');
        $i = 0;

        foreach ($column_search as $item) {  // looping awal
            if ($_GET['search']['value']) { // jika datatable mengirimkan pencarian dengan metode POST

                if ($i === 0) { // looping awal
                    $this->db->group_start();
                    $this->db->like($item, $_GET['search']['value']);
                } else {
                    $this->db->or_like($item, $_GET['search']['value']);
                }

                if (count($column_search) - 1 == $i) {
                    $this->db->group_end();
                }
            }
            $i++;
        }

        $this->db->order_by('mc.nama ASC, md.nama ASC, mj.nama ASC, dk.nama_lengkap ASC');
    }

    public function getDataById($id = null)
    {
        $select = $this->db->select('
                id_jenis_izin,
                kode_izin,
                nama,
                jenis_izin,
                flag,
                flag_kalender,
                flag_file,
                max_izin,
                back_date
            ')
            ->from($this->table)
            ->where('id_company', $this->id_company)
            ->where('md5(id_jenis_izin)', $id)
            ->get()
            ->row();
        return $select;
    }

    public function save($data)
    {
        $this->db->trans_start();

        // semua karyawan
        if ($data['target'] == 'all') {
            // get saldo karyawan
            $data_sekarang = $this->db->select('id_karyawan, jatah_cuti')
                ->from($this->table)
                ->where_in('status', ['1', '2'])
                ->where('id_company', $this->id_company)
                ->get()
                ->result();
        }
        // cabang
        else if ($data['target'] == 'cabang') {
            // get saldo karyawan
            $data_sekarang = $this->db->select('id_karyawan, jatah_cuti')
                ->from($this->table)
                ->where_in('status', ['1', '2'])
                ->where('id_company', $this->id_company)
                ->where_in('id_cabang', $data['target_select_cabang'])
                ->get()
                ->result();
        }
        // departemen
        else if ($data['target'] == 'departemen') {
            // get saldo karyawan
            $data_sekarang = $this->db->select('id_karyawan, jatah_cuti')
                ->from($this->table)
                ->where_in('status', ['1', '2'])
                ->where('id_company', $this->id_company)
                ->where_in('id_departemen', $data['target_select_departemen'])
                ->get()
                ->result();
        }
        // spesifik karyawan
        else {
            // get saldo karyawan
            $data_sekarang = $this->db->select('id_karyawan, jatah_cuti')
                ->from($this->table)
                ->where_in('status', ['1', '2'])
                ->where('id_company', $this->id_company)
                ->where_in('id_karyawan', $data['target_select_karyawan'])
                ->get()
                ->result();
        }

        // store data in array
        $data_karyawan = [];
        $data_history_cuti = [];
        $nextId = $this->fungsi->getNextId($this->table_history_cuti, 'id_cuti_history', $this->id_company, 5);
        foreach ($data_sekarang as $key) {
            if ($data['jenis'] == 'tambah') {
                $jatah_cuti = ($key->jatah_cuti + $data['saldo']);
                $tambah     = $data['saldo'];
                $kurang     = 0;
            } elseif ($data['jenis'] == 'kurang') {
                $jatah_cuti = ($key->jatah_cuti - $data['saldo']);
                $tambah     = 0;
                $kurang     = $data['saldo'];
            } else {
                $jatah_cuti = $data['saldo'];
                $tambah     = $data['saldo'];
                $kurang     = $key->jatah_cuti;
            }

            $data_karyawan[] = [
                'concat(id_karyawan,id_company)' => $key->id_karyawan . $this->id_company,
                'jatah_cuti'                     => $jatah_cuti,
                'user_update'                    => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                'tgl_update'                     => date('Y-m-d H:i:s')
            ];

            $data_history_cuti[] = [
                'id_cuti_history' => $nextId,
                'tgl_trx'         => date('Y-m-d'),
                'tambah'          => $tambah,
                'kurang'          => $kurang,
                'saldo'           => $jatah_cuti,
                'keterangan'      => $data['keterangan'],
                'id_karyawan'     => $key->id_karyawan,
                'user_input'      => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                'id_company'      => $this->id_company
            ];

            $last_id = substr($nextId, -5);
            $next_id = (int)$last_id + 1;
            $nextId = substr($nextId, 0, -5) . sprintf("%05d", $next_id);
        }

        // update semua saldo karyawan
        $this->db->update_batch($this->table, $data_karyawan, 'concat(id_karyawan,id_company)');

        // insert history cuti per karyawan
        $this->db->insert_batch($this->table_history_cuti, $data_history_cuti);

        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return __response_update(false);
        } else {
            $this->db->trans_commit();
            return __response_update(true);
        }
    }

    public function delete($id = null)
    {
        $this->db->select("kode_izin");
        $this->db->where("id_company", $this->id_company);
        $this->db->where("md5(id_jenis_izin)", $id);
        $this->db->from("master_jenis_izin");
        $kode_izin = $this->db->get()->row()->kode_izin;

        $this->db->select("id_izin");
        $this->db->where("id_company", $this->id_company);
        $this->db->where("status", "1");
        $this->db->where("kode_izin", $kode_izin);
        $this->db->from("data_izin");
        $cek_data = $this->db->get()->num_rows();

        if ($cek_data > 0) {
            $message = '<font color="#ffffff"><i class="fa fa-exclamation-triangle">&nbsp;</i>' . $this->lang->line('error_hapus_jenis_izin') . '</font>';
            return __response_delete(false, ["message" => $message]);
        } else {
            $this->db->where('md5(id_jenis_izin)', $id);
            $this->db->where('id_company', $this->id_company);
            $delete = $this->db->delete($this->table);
            return  __response_delete($delete);
        }
    }
}
