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

class Master_komponen_m extends CI_Model
{
    private $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_bpjs,
            flag_pph21,
            flag_pot_absensi,
            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_bpjs,
            flag_pph21,
            flag_pot_absensi,
            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)
    {
        $this->db->trans_start();

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

        $data_pendapatan = [];
        // 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'],
                        '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 ($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);
            }
        }

        $this->db->trans_complete();

        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_start();

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

        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');
                } else {
                    // kondisi tidak tetap ke tetap
                    // hapus data komponen tunjangan tidak tetap pada bulan berjalan
                    $this->db->where('periode', $bulan);
                    $this->db->where('md5(id_item)', $id_item);
                    $this->db->where('id_company', $this->id_company);
                    $this->db->delete('payroll_tunj_tdk_tetap_m');

                    // hapus data master komponen tidak tetap
                    $this->delete($id_item, $master, $bulan, false);

                    // panggil fungsi save
                    $this->save($data, $master, false);
                }
            } else {
                // 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'],
                        '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);
                }
            }
        } else {
            $data_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');
                } else {
                    // kondisi tidak tetap ke tetap
                    // hapus data komponen potongan tidak tetap pada bulan berjalan
                    $this->db->where('periode', $bulan);
                    $this->db->where('md5(id_item)', $id_item);
                    $this->db->where('id_company', $this->id_company);
                    $this->db->delete('payroll_pot_tdk_tetap_m');

                    // hapus data master komponen tidak tetap
                    $this->delete($id_item, $master, $bulan, false);

                    // panggil fungsi save
                    $this->save($data, $master, false);
                }
            } else {
                // get data karyawan
                $select = $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)
                    ->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->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, $master, $bulan, $return = true)
    {
        $this->db->trans_start();

        $this->db->where('md5(id_item)', $id);
        $this->db->where('jenis_master', $master);
        $this->db->where('id_company', $this->id_company);
        $select = $this->db->get($this->table)->row();

        if ($master == 'pendapatan') {
            $table_pend = 'payroll_tunj_tetap_m';
            $table_pend_temp = 'payroll_tunj_tetap_temp';
            if ($select->jenis_komponen != 'tetap') {
                $table_pend = 'payroll_tunj_tdk_tetap_m';
                $table_pend_temp = 'payroll_tunj_tdk_tetap_temp';
                if (!empty($bulan)) {
                    $this->db->where('periode', $bulan);
                }
            }
            // 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);
        } else {
            $table_pot = 'payroll_pot_tetap_m';
            $table_pot_temp = 'payroll_pot_tetap_temp';
            if ($select->jenis_komponen != 'tetap') {
                $table_pot = 'payroll_pot_tdk_tetap_m';
                $table_pot_temp = 'payroll_pot_tdk_tetap_temp';
                if (!empty($bulan)) {
                    $this->db->where('periode', $bulan);
                }
            }
            // hapus data komponen
            $this->db->where('md5(id_item)', $id);
            $this->db->where('id_company', $this->id_company);
            $this->db->delete($table_pot);
            // hapus data komponen temp
            $this->db->where('nm_potongan', $select->nm_komponen);
            $this->db->where('id_company', $this->id_company);
            $this->db->delete($table_pot_temp);
        }

        $this->db->where('md5(id_item)', $id);
        $this->db->where('jenis_master', $master);
        $this->db->where('id_company', $this->id_company);
        $this->db->delete($this->table);

        $this->db->trans_complete();

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