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

class Master_lembur_pengaturan_m extends CI_Model
{
    protected $table = 'payroll_lembur_p';

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

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

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

    private function _get_datatables_query()
    {
        $this->db->select('
            id_lembur_p,
            kode,
            keterangan,
            flag_pph21,
            flag_pot_absensi
        ')
            ->from($this->table)
            ->where('id_company', $this->id_company)
            ->order_by('id_lembur_p', 'DESC');

        $column_search = array('kode', 'keterangan');
        $i = 0;
        foreach ($column_search as $item) {
            if ($_GET['search']['value']) {
                if ($i === 0) {
                    $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++;
        }
    }

    public function getDataById($encrypt_id)
    {
        $pengaturan = $this->db->select('
            id_lembur_p,
            kode,
            keterangan,
            flag_rounding,
            jenis_upah_lembur,
            nominal_flat,
            divide_prorate,
            flag_pph21,
            flag_pot_absensi
        ')
            ->from($this->table)
            ->where('id_company', $this->id_company)
            ->where('md5(id_lembur_p)', $encrypt_id)
            ->get()
            ->row();

        $pembulatan = $this->db->query('SELECT menit_mulai, menit_selesai, menit_dihitung FROM payroll_lembur_p_pembulatan WHERE md5(id_lembur) = ?', [$encrypt_id])->result();
        $perkalian = $this->db->query('SELECT jam_mulai, jam_selesai, perkalian FROM payroll_lembur_p_perkalian WHERE md5(id_lembur) = ?', [$encrypt_id])->result();

        $pengaturan->pembulatan = $pembulatan;
        $pengaturan->perkalian = $perkalian;

        return $pengaturan;
    }

    public function save($data, $arr_pembulatan, $arr_kompensasi)
    {
        $this->db->trans_begin();
        // save pengaturnan lembur
        $id_lembur           = $this->getNextId($this->table, 'id_lembur_p', $this->id_company, 4);
        $data['id_lembur_p'] = $id_lembur;
        $data['id_company']  = $this->id_company;
        $data['user_input']  = $this->nik_karyawan . ' - ' . $this->nm_karyawan;
        $this->db->insert($this->table, $data);

        // save data pembulatan
        $id_lembur_pembulatan = $this->getNextId('payroll_lembur_p_pembulatan', 'id_lembur_pembulatan', $this->id_company, 4);
        $data_pembulatan = [];
        for ($i = 0; $i < count($arr_pembulatan); $i++) {
            $data_pembulatan[] = [
                'id_lembur_pembulatan' => $id_lembur_pembulatan,
                'id_lembur'            => $id_lembur,
                'menit_mulai'          => $arr_pembulatan[$i][0],
                'menit_selesai'        => $arr_pembulatan[$i][1],
                'menit_dihitung'       => $arr_pembulatan[$i][2],
                'id_company'           => $this->id_company,
            ];

            $last_id = substr($id_lembur_pembulatan, -4);
            $next_id = (int)$last_id + 1;
            $id_lembur_pembulatan  = substr($id_lembur_pembulatan, 0, -4) . sprintf("%04d", $next_id);
        }
        $this->db->insert_batch('payroll_lembur_p_pembulatan', $data_pembulatan);

        // save data perkalian
        $id_lembur_perkalian = $this->getNextId('payroll_lembur_p_perkalian', 'id_lembur_perkalian', $this->id_company, 4);
        $data_kompensasi = [];
        for ($i = 0; $i < count($arr_kompensasi); $i++) {
            $data_kompensasi[] = [
                'id_lembur_perkalian' => $id_lembur_perkalian,
                'id_lembur'           => $id_lembur,
                'jam_mulai'           => $arr_kompensasi[$i][0],
                'jam_selesai'         => $arr_kompensasi[$i][1],
                'perkalian'           => $arr_kompensasi[$i][2],
                'id_company'          => $this->id_company,
            ];

            $last_id = substr($id_lembur_perkalian, -4);
            $next_id = (int)$last_id + 1;
            $id_lembur_perkalian  = substr($id_lembur_perkalian, 0, -4) . sprintf("%04d", $next_id);
        }
        $this->db->insert_batch('payroll_lembur_p_perkalian', $data_kompensasi);

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

    public function update($data, $arr_pembulatan, $arr_kompensasi, $encrypt_id)
    {
        // decrypt id
        $id_lembur = $this->db->select('id_lembur_p')
            ->from($this->table)
            ->where('md5(id_lembur_p)', $encrypt_id)
            ->get()
            ->row()
            ->id_lembur_p;

        $this->db->trans_begin();
        // save pengaturnan lembur
        $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, ['id_company' => $this->id_company, 'id_lembur_p' => $id_lembur]);

        // hapus data pembulatan
        $this->db->delete('payroll_lembur_p_pembulatan', ['id_company' => $this->id_company, 'id_lembur' => $id_lembur]);
        // update data pembulatan
        $id_lembur_pembulatan = $this->getNextId('payroll_lembur_p_pembulatan', 'id_lembur_pembulatan', $this->id_company, 4);
        $data_pembulatan = [];
        for ($i = 0; $i < count($arr_pembulatan); $i++) {
            $data_pembulatan[] = [
                'id_lembur_pembulatan' => $id_lembur_pembulatan,
                'id_lembur'            => $id_lembur,
                'menit_mulai'          => $arr_pembulatan[$i][0],
                'menit_selesai'        => $arr_pembulatan[$i][1],
                'menit_dihitung'       => $arr_pembulatan[$i][2],
                'id_company'           => $this->id_company,
            ];

            $last_id = substr($id_lembur_pembulatan, -4);
            $next_id = (int)$last_id + 1;
            $id_lembur_pembulatan  = substr($id_lembur_pembulatan, 0, -4) . sprintf("%04d", $next_id);
        }
        $this->db->insert_batch('payroll_lembur_p_pembulatan', $data_pembulatan);

        // hapus data perkalian
        $this->db->delete('payroll_lembur_p_perkalian', ['id_company' => $this->id_company, 'id_lembur' => $id_lembur]);
        // update data perkalian
        $id_lembur_perkalian = $this->getNextId('payroll_lembur_p_perkalian', 'id_lembur_perkalian', $this->id_company, 4);
        $data_kompensasi = [];
        for ($i = 0; $i < count($arr_kompensasi); $i++) {
            $data_kompensasi[] = [
                'id_lembur_perkalian' => $id_lembur_perkalian,
                'id_lembur'           => $id_lembur,
                'jam_mulai'           => $arr_kompensasi[$i][0],
                'jam_selesai'         => $arr_kompensasi[$i][1],
                'perkalian'           => $arr_kompensasi[$i][2],
                'id_company'          => $this->id_company,
            ];

            $last_id = substr($id_lembur_perkalian, -4);
            $next_id = (int)$last_id + 1;
            $id_lembur_perkalian  = substr($id_lembur_perkalian, 0, -4) . sprintf("%04d", $next_id);
        }
        $this->db->insert_batch('payroll_lembur_p_perkalian', $data_kompensasi);

        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)
    {
        $this->db->trans_begin();
        // hapus pengaturnan lembur
        $this->db->delete($this->table, ['id_company' => $this->id_company, 'id_lembur_p' => $id]);

        // hapus data pembulatan
        $this->db->delete('payroll_lembur_p_pembulatan', ['id_company' => $this->id_company, 'id_lembur' => $id]);

        // hapus data perkalian
        $this->db->delete('payroll_lembur_p_perkalian', ['id_company' => $this->id_company, 'id_lembur' => $id]);

        // update master lembur karyawan
        $this->db->update('payroll_lembur_m', ['lembur_hari_kerja' => ''], ['id_company' => $this->id_company, 'lembur_hari_kerja' => $id]);
        $this->db->update('payroll_lembur_m', ['lembur_libur_off' => ''], ['id_company' => $this->id_company, 'lembur_libur_off' => $id]);
        $this->db->update('payroll_lembur_m', ['lembur_libur_nasional' => ''], ['id_company' => $this->id_company, 'lembur_libur_nasional' => $id]);
        $this->db->update('payroll_lembur_m', ['lembur_libur_khusus' => ''], ['id_company' => $this->id_company, 'lembur_libur_khusus' => $id]);

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

    public function getNextId(string $tableName, string $fieldName, string $id_company, int $lengthNumber): string
    {
        $current_year = date('Y');
        $len_substring = -4 - $lengthNumber;
        $gedId = $this->db->query("SELECT
                                        MAX($fieldName) as id
                                    FROM $tableName
                                    WHERE
                                        id_company = '$id_company'
                                        AND SUBSTRING($fieldName,$len_substring,4) = '$current_year'
                                    FOR UPDATE");

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

        return $nextId;
    }
}
