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

class Master_komponen_m extends CI_Model
{
    protected $table = 'payroll_komponen_m';

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

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

    public function count_all($master)
    {
        $this->_get_datatables_query($master);
        return $this->db->count_all_results();
    }

    private function _get_datatables_query($master)
    {
        $this->db->select("
            id_item,
            jenis_komponen,
            jenis_master,
            nm_komponen,
            flag_persentase_gapok,
            gapok_persen,
            flag_cuti,
            flag_izin,
            flag_sakit,
            flag_bpjs,
            flag_pph21,
            flag_pot_absensi,
            flag_upah_lembur,
            no_urut
        ")
            ->from($this->table)
            ->where('jenis_master', $master)
            ->where("id_company", $this->id_company);

        $column_search = array('');
        $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('no_urut', 'ASC');
    }

    public function getDataById($id = null, $master)
    {
        $this->db->select('
            id_item,
            jenis_komponen,
            jenis_master,
            nm_komponen,
            flag_persentase_gapok,
            gapok_persen,
            flag_cuti,
            flag_izin,
            flag_sakit,
            flag_bpjs,
            flag_pph21,
            flag_pot_absensi,
            flag_upah_lembur,
            no_urut
        ');
        $this->db->from($this->table);
        $this->db->where("md5(id_item)", $id);
        $this->db->where("jenis_master", $master);
        $this->db->where("id_company", $this->id_company);
        $query = $this->db->get();
        return $query->row();
    }

    public function save($data, $master, $return = true)
    {
        if ($return) $this->db->trans_begin();

        $id_item            = $this->fungsi->getNextId($this->table, 'id_item', $this->id_company, 5);
        $data["id_item"]    = $id_item;
        $data["id_company"] = $this->id_company;
        $data["user_input"] = $this->nik_karyawan . ' - ' . $this->nm_karyawan;
        $this->db->insert($this->table, $data);

        // update urutan master komponen
        $reorder = $this->input->post('reorder');
        if (!empty($reorder)) {
            $data_order = array();
            foreach ($reorder as $key) {
                $data_order[] = [
                    'concat(id_item,id_company)' => $key['id_item'] . $this->id_company,
                    'no_urut'                    => $key['no_urut']
                ];
            }
            $this->db->update_batch($this->table, $data_order, 'concat(id_item,id_company)');
        }
        $this->logger->create_log('payroll_master_komponen_save', 'save', $this->db->last_query());

        // get data karyawan aktif
        $karyawan_aktif = $this->db->select('dk.id_karyawan, pg.nominal')
            ->from('data_karyawan as dk')
            ->join('payroll_gapok_m as pg', 'pg.id_karyawan = dk.id_karyawan', 'left')
            ->join('master_jabatan', 'master_jabatan.id_jabatan = dk.id_jabatan')
            ->where('dk.id_company', $this->id_company)
            ->where_in('dk.status', ['1', '2', '3', '4'])
            ->where_not_in("master_jabatan.level_user", ["1", "6"])
            ->get()
            ->result();

        if ($master == 'pendapatan') {
            if ($data['jenis_komponen'] == 'tetap') {
                foreach ($karyawan_aktif as $karyawan) {
                    $gapok             = ($karyawan->nominal) ? $karyawan->nominal : 0;
                    $data_pendapatan[] = [
                        'id_karyawan'           => $karyawan->id_karyawan,
                        'id_item'               => $data['id_item'],
                        'jenis_komponen'        => $data['jenis_komponen'],
                        'jenis_master'          => $data['jenis_master'],
                        'nm_tunjangan'          => $data['nm_komponen'],
                        'flag_persentase_gapok' => $data['flag_persentase_gapok'],
                        'gapok_persen'          => $data['gapok_persen'],
                        'gapok_rp'              => $gapok,
                        'nominal_tunjangan'     => ($data['flag_persentase_gapok'] == '1') ? (($data['gapok_persen'] / 100) * $gapok) : 0,
                        'flag_bpjs'             => $data['flag_bpjs'],
                        'flag_pph21'            => $data['flag_pph21'],
                        'flag_pot_absensi'      => $data['flag_pot_absensi'],
                        'flag_upah_lembur'      => $data['flag_upah_lembur'],
                        'id_company'            => $this->id_company,
                        'user_input'            => $this->nik_karyawan . ' - ' . $this->nm_karyawan
                    ];
                }

                $this->db->insert_batch('payroll_tunj_tetap_m', $data_pendapatan);
            }
        } else if ($master == 'potongan') {
            if ($data['jenis_komponen'] == 'tetap') {
                foreach ($karyawan_aktif as $karyawan) {
                    $gapok           = ($karyawan->nominal) ? $karyawan->nominal : 0;
                    $data_potongan[] = [
                        'id_karyawan'           => $karyawan->id_karyawan,
                        'id_item'               => $data['id_item'],
                        'jenis_komponen'        => $data['jenis_komponen'],
                        'jenis_master'          => $data['jenis_master'],
                        'nm_potongan'           => $data['nm_komponen'],
                        'flag_persentase_gapok' => $data['flag_persentase_gapok'],
                        'gapok_persen'          => $data['gapok_persen'],
                        'gapok_rp'              => $gapok,
                        'nominal_potongan'      => ($data['flag_persentase_gapok'] == '1') ? (($data['gapok_persen'] / 100) * $gapok) : 0,
                        'flag_bpjs'             => $data['flag_bpjs'],
                        'flag_pph21'            => $data['flag_pph21'],
                        'flag_pot_absensi'      => $data['flag_pot_absensi'],
                        'id_company'            => $this->id_company,
                        'user_input'            => $this->nik_karyawan . ' - ' . $this->nm_karyawan
                    ];
                }

                $this->db->insert_batch('payroll_pot_tetap_m', $data_potongan);
            }
        } else {
            // jenis komponen kehadiran
            foreach ($karyawan_aktif as $karyawan) {
                $gapok             = ($karyawan->nominal) ? $karyawan->nominal : 0;
                $data_pendapatan[] = [
                    'id_karyawan'           => $karyawan->id_karyawan,
                    'id_item'               => $data['id_item'],
                    'nm_tunjangan'          => $data['nm_komponen'],
                    'flag_persentase_gapok' => $data['flag_persentase_gapok'],
                    'gapok_persen'          => $data['gapok_persen'],
                    'gapok_rp'              => $gapok,
                    'nominal_tunjangan'     => ($data['flag_persentase_gapok'] == '1') ? (($data['gapok_persen'] / 100) * $gapok) : 0,
                    'flag_bpjs'             => $data['flag_bpjs'],
                    'flag_pph21'            => $data['flag_pph21'],
                    'flag_pot_absensi'      => $data['flag_pot_absensi'],
                    'flag_upah_lembur'      => $data['flag_upah_lembur'],
                    'flag_cuti'             => $data['flag_cuti'],
                    'flag_izin'             => $data['flag_izin'],
                    'flag_sakit'            => $data['flag_sakit'],
                    'id_company'            => $this->id_company,
                    'user_input'            => $this->nik_karyawan . ' - ' . $this->nm_karyawan
                ];
            }

            $this->db->insert_batch('payroll_tunj_kehadiran_m', $data_pendapatan);
        }

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

    public function update($data, $master, $id_item, $jenis)
    {
        $this->db->trans_begin();

        // $this->db->where(array(
        //     'md5(id_item)' => $id_item,
        //     'id_company'   => $this->id_company
        // ));

        $data["user_update"] = $this->nik_karyawan . ' - ' . $this->nm_karyawan;
        $data["tgl_update"]  = date('Y-m-d H:i:s');
        // $this->db->update($this->table, $data);
        $this->logger->create_log('payroll_master_komponen_update', 'edit', $this->db->last_query());

        if ($master == 'pendapatan') {
            $data_pendapatan = [];
            $table_pend      = 'payroll_tunj_tetap_m';
            $keyItem         = 'concat(id_karyawan,id_item,id_company)';
            $valueItem       = $this->id_company;
            $bulan           = '';

            if ($data['jenis_komponen'] != 'tetap') {
                $table_pend = 'payroll_tunj_tdk_tetap_m';
                $keyItem    = 'concat(id_karyawan,id_item,periode,id_company)';
                $valueItem  = date('Y-m') . $this->id_company;
                $bulan      = date('Y-m');
            }

            if ($jenis != $data['jenis_komponen']) {
                if (!empty($bulan)) {
                    // kondisi tetap ke tidak tetap
                    // hapus data komponen tunjangan tetap
                    $this->db->where('md5(id_item)', $id_item);
                    $this->db->where('id_company', $this->id_company);
                    $this->db->delete('payroll_tunj_tetap_m');

                    // update master komponen
                    $this->db->update($this->table, $data, ['md5(id_item)' => $id_item, 'id_company' => $this->id_company]);
                } else {
                    // kondisi tidak tetap ke tetap
                    // hapus data komponen tunjangan tidak tetap pada bulan berjalan
                    // dan data master komponen tidak tetap
                    $this->delete($id_item, $master, date('Y-m'), false);

                    // panggil fungsi save
                    $this->save($data, $master, false);
                }
            } else {
                // update master komponen
                $this->db->update($this->table, $data, ['md5(id_item)' => $id_item, 'id_company' => $this->id_company]);

                // get data karyawan
                $this->db->select('pend.id_karyawan, pend.id_item, pend.flag_persentase_gapok, pend.nominal_tunjangan, pg.nominal')
                    ->from($table_pend . ' AS pend')
                    ->join('payroll_gapok_m AS pg', 'pg.id_karyawan = pend.id_karyawan', 'left')
                    ->where('md5(pend.id_item)', $id_item)
                    ->where('pend.id_company', $this->id_company);
                if (!empty($bulan)) {
                    $this->db->where('pend.periode', $bulan);
                }
                $select = $this->db->get()->result();

                foreach ($select as $karyawan) {
                    $gapok             = ($karyawan->nominal) ? $karyawan->nominal : 0;
                    $nominal_tunjangan = 0;
                    if ($data['flag_persentase_gapok'] == 1) {
                        // jika tidak ada perubahan dengan flag sebelumnya
                        if ($data['flag_persentase_gapok'] == $karyawan->flag_persentase_gapok) {
                            // jika data nominal sebelumnya ada nilainya
                            if ($karyawan->nominal_tunjangan > 0) {
                                // update yang terbaru
                                $nominal_tunjangan = (($data['gapok_persen'] / 100) * $gapok);
                            }
                        } else {
                            $nominal_tunjangan = (($data['gapok_persen'] / 100) * $gapok);
                        }
                    } else {
                        // jika data nominal sebelumnya ada nilainya
                        if ($karyawan->nominal_tunjangan > 0) {
                            // update yang terbaru
                            $nominal_tunjangan = $karyawan->nominal_tunjangan;
                        }
                    }
                    $data_pendapatan[] = [
                        $keyItem                => $karyawan->id_karyawan . $karyawan->id_item . $valueItem,
                        'nm_tunjangan'          => $data['nm_komponen'],
                        'flag_persentase_gapok' => $data['flag_persentase_gapok'],
                        'gapok_persen'          => $data['gapok_persen'],
                        'gapok_rp'              => $gapok,
                        'nominal_tunjangan'     => $nominal_tunjangan,
                        'flag_bpjs'             => $data['flag_bpjs'],
                        'flag_pph21'            => $data['flag_pph21'],
                        'flag_pot_absensi'      => $data['flag_pot_absensi'],
                        'flag_upah_lembur'      => $data['flag_upah_lembur'],
                        'user_update'           => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                        'tgl_update'            => date('Y-m-d H:i:s')
                    ];
                }
                if (!empty($data_pendapatan)) {
                    $this->db->update_batch($table_pend, $data_pendapatan, $keyItem);
                    $this->logger->create_log('payroll_master_komponen_data_pendapatan', 'edit', $this->db->last_query());
                }
            }
        } else if ($master == 'potongan') {
            $table_pot = 'payroll_pot_tetap_m';
            $keyItem   = 'concat(id_karyawan,id_item,id_company)';
            $valueItem = $this->id_company;
            $bulan     = '';

            if ($data['jenis_komponen'] != 'tetap') {
                $table_pot = 'payroll_pot_tdk_tetap_m';
                $keyItem   = 'concat(id_karyawan,id_item,periode,id_company)';
                $valueItem = date('Y-m') . $this->id_company;
                $bulan     = date('Y-m');
            }

            if ($jenis != $data['jenis_komponen']) {
                if (!empty($bulan)) {
                    // kondisi tetap ke tidak tetap
                    // hapus data komponen potongan tetap
                    $this->db->where('md5(id_item)', $id_item);
                    $this->db->where('id_company', $this->id_company);
                    $this->db->delete('payroll_pot_tetap_m');

                    // update master komponen
                    $this->db->update($this->table, $data, ['md5(id_item)' => $id_item, 'id_company' => $this->id_company]);
                } else {
                    // kondisi tidak tetap ke tetap
                    // hapus data komponen potongan tidak tetap pada bulan berjalan
                    // dan data master komponen tidak tetap
                    $this->delete($id_item, $master, date('Y-m'), false);

                    // panggil fungsi save
                    $this->save($data, $master, false);
                }
            } else {
                // update master komponen
                $this->db->update($this->table, $data, ['md5(id_item)' => $id_item, 'id_company' => $this->id_company]);

                // get data karyawan
                $this->db->select('pot.id_karyawan, pot.id_item, pot.flag_persentase_gapok, pot.nominal_potongan, pg.nominal')
                    ->from($table_pot . ' AS pot')
                    ->join('payroll_gapok_m AS pg', 'pg.id_karyawan = pot.id_karyawan', 'left')
                    ->where('md5(pot.id_item)', $id_item)
                    ->where('pot.id_company', $this->id_company);
                if (!empty($bulan)) {
                    $this->db->where('pot.periode', $bulan);
                }
                $select = $this->db->get()->result();

                foreach ($select as $karyawan) {
                    $gapok            = ($karyawan->nominal) ? $karyawan->nominal : 0;
                    $nominal_potongan = 0;
                    if ($data['flag_persentase_gapok'] == 1) {
                        // jika tidak ada perubahan dengan flag sebelumnya
                        if ($data['flag_persentase_gapok'] == $karyawan->flag_persentase_gapok) {
                            // jika data nominal sebelumnya ada nilainya
                            if ($karyawan->nominal_potongan > 0) {
                                // update yang terbaru
                                $nominal_potongan = (($data['gapok_persen'] / 100) * $gapok);
                            }
                        } else {
                            $nominal_potongan = (($data['gapok_persen'] / 100) * $gapok);
                        }
                    } else {
                        // jika data nominal sebelumnya ada nilainya
                        if ($karyawan->nominal_potongan > 0) {
                            // update yang terbaru
                            $nominal_potongan = $karyawan->nominal_potongan;
                        }
                    }
                    $data_potongan[] = [
                        $keyItem                => $karyawan->id_karyawan . $karyawan->id_item . $valueItem,
                        'nm_potongan'           => $data['nm_komponen'],
                        'flag_persentase_gapok' => $data['flag_persentase_gapok'],
                        'gapok_persen'          => $data['gapok_persen'],
                        'gapok_rp'              => $gapok,
                        'nominal_potongan'      => $nominal_potongan,
                        'flag_bpjs'             => $data['flag_bpjs'],
                        'flag_pph21'            => $data['flag_pph21'],
                        'flag_pot_absensi'      => $data['flag_pot_absensi'],
                        'user_update'           => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                        'tgl_update'            => date('Y-m-d H:i:s')
                    ];
                }
                if (!empty($data_potongan)) {
                    $this->db->update_batch($table_pot, $data_potongan, $keyItem);
                    $this->logger->create_log('payroll_data_potongan', 'edit', $this->db->last_query());
                }
            }
        } else {
            $table_pend = 'payroll_tunj_kehadiran_m';
            $keyItem    = 'concat(id_karyawan,id_item,id_company)';
            $valueItem  = $this->id_company;
            $bulan      = '';

            // update master komponen
            $this->db->update($this->table, $data, ['md5(id_item)' => $id_item, 'id_company' => $this->id_company]);

            // get data karyawan
            $select = $this->db->select('pend.id_karyawan, pend.id_item, pend.flag_persentase_gapok, pend.nominal_tunjangan, pg.nominal')
                ->from($table_pend . ' AS pend')
                ->join('payroll_gapok_m AS pg', 'pg.id_karyawan = pend.id_karyawan', 'left')
                ->where('md5(pend.id_item)', $id_item)
                ->where('pend.id_company', $this->id_company)
                ->get()
                ->result();

            foreach ($select as $karyawan) {
                $gapok             = ($karyawan->nominal) ? $karyawan->nominal : 0;
                $nominal_tunjangan = 0;
                if ($data['flag_persentase_gapok'] == 1) {
                    // jika tidak ada perubahan dengan flag sebelumnya
                    if ($data['flag_persentase_gapok'] == $karyawan->flag_persentase_gapok) {
                        // jika data nominal sebelumnya ada nilainya
                        if ($karyawan->nominal_tunjangan > 0) {
                            // update yang terbaru
                            $nominal_tunjangan = (($data['gapok_persen'] / 100) * $gapok);
                        }
                    } else {
                        $nominal_tunjangan = (($data['gapok_persen'] / 100) * $gapok);
                    }
                } else {
                    // jika data nominal sebelumnya ada nilainya
                    if ($karyawan->nominal_tunjangan > 0) {
                        // update yang terbaru
                        $nominal_tunjangan = $karyawan->nominal_tunjangan;
                    }
                }
                $data_pendapatan[] = [
                    $keyItem                => $karyawan->id_karyawan . $karyawan->id_item . $valueItem,
                    'nm_tunjangan'          => $data['nm_komponen'],
                    'flag_persentase_gapok' => $data['flag_persentase_gapok'],
                    'gapok_persen'          => $data['gapok_persen'],
                    'gapok_rp'              => $gapok,
                    'nominal_tunjangan'     => $nominal_tunjangan,
                    'flag_bpjs'             => $data['flag_bpjs'],
                    'flag_pph21'            => $data['flag_pph21'],
                    'flag_pot_absensi'      => $data['flag_pot_absensi'],
                    'flag_upah_lembur'      => $data['flag_upah_lembur'],
                    'flag_cuti'             => $data['flag_cuti'],
                    'flag_izin'             => $data['flag_izin'],
                    'flag_sakit'            => $data['flag_sakit'],
                    'user_update'           => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                    'tgl_update'            => date('Y-m-d H:i:s')
                ];
            }
            if (!empty($data_pendapatan)) {
                $this->db->update_batch($table_pend, $data_pendapatan, $keyItem);
                $this->logger->create_log('payroll_master_komponen_data_kehadiran', 'edit', $this->db->last_query());
            }
        }

        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, $master, $bulan, $return = true)
    {
        if ($return) $this->db->trans_begin();

        $komponen = $this->db->get_where($this->table, [
            'md5(id_item)' => $id,
            'jenis_master' => $master,
            'id_company'   => $this->id_company
        ])->row();

        if ($master == 'pendapatan') {
            $table_pend      = 'payroll_tunj_tetap_m';
            $table_pend_temp = 'payroll_tunj_tetap_temp';

            if ($komponen->jenis_komponen != 'tetap') {
                $table_pend      = 'payroll_tunj_tdk_tetap_m';
                $table_pend_temp = 'payroll_tunj_tdk_tetap_temp';
            }

            // hapus data komponen
            $this->db->where('id_company', $this->id_company);
            if (!empty($bulan)) $this->db->where('periode', $bulan);
            $this->db->where('id_item', $komponen->id_item);
            $this->db->delete($table_pend);

            // hapus data komponen temp
            $this->db->where('id_company', $this->id_company);
            if (!empty($bulan)) $this->db->where('bulan', $bulan);
            $this->db->where('nm_tunjangan', $komponen->nm_komponen);
            $this->db->delete($table_pend_temp);
        } else if ($master == 'potongan') {
            $table_pot      = 'payroll_pot_tetap_m';
            $table_pot_temp = 'payroll_pot_tetap_temp';

            if ($komponen->jenis_komponen != 'tetap') {
                $table_pot      = 'payroll_pot_tdk_tetap_m';
                $table_pot_temp = 'payroll_pot_tdk_tetap_temp';
            }
            // hapus data komponen
            $this->db->where('md5(id_item)', $id);
            if (!empty($bulan)) $this->db->where('periode', $bulan);
            $this->db->where('id_company', $this->id_company);
            $this->db->delete($table_pot);
            // hapus data komponen temp
            $this->db->where('id_company', $this->id_company);
            if (!empty($bulan)) $this->db->where('bulan', $bulan);
            $this->db->where('nm_potongan', $komponen->nm_komponen);
            $this->db->delete($table_pot_temp);
        } else {
            $table_pend = 'payroll_tunj_kehadiran_m';
            // $table_pend_temp = 'payroll_tunj_kehadiran_temp';
            // hapus data komponen
            $this->db->where('md5(id_item)', $id);
            $this->db->where('id_company', $this->id_company);
            $this->db->delete($table_pend);
            // hapus data komponen temp
            // $this->db->where('nm_tunjangan', $select->nm_komponen);
            // $this->db->where('id_company', $this->id_company);
            // $this->db->delete($table_pend_temp);
        }

        $this->db->where('id_item', $komponen->id_item);
        $this->db->where('id_company', $this->id_company);
        $this->db->delete($this->table);

        $this->logger->create_log('payroll_master_komponen', 'delete', $this->db->last_query());

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

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

        $this->db->update_batch($this->table, $data, 'concat(id_item,id_company)');
        $this->logger->create_log('payroll_master_komponen_update_order', 'edit', $this->db->last_query());

        $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);
        }
    }
}
