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

class Cabang_m extends CI_Model
{
    var $table = 'master_cabang';
    public function __construct()
    {
        parent::__construct();
    }

    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->db->select("id_cabang")->from($this->table);
        $this->db->where("id_company", $this->id_company);
        return $this->db->count_all_results();
    }
    private function _get_datatables_query()
    {
        $this->db->select("id_cabang,kode,nama,flag")->from($this->table);
        $this->db->where("id_company", $this->id_company);

        $column_search = array('kode', 'nama');
        $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++;
        }

        $column_order = array('', 'kode', 'nama', 'flag');

        if (isset($_GET['order'])) {
            $this->db->order_by($column_order[$_GET['order']['0']['column']], $_GET['order']['0']['dir']);
        } else {
            $order_by = array("tgl_input" => "DESC");
            $this->db->order_by(key($order_by), $order_by[key($order_by)]);
        }
    }

    public function getDataById($id = null)
    {
        $select = $this->db->query("SELECT id_cabang,
                                            kode,
                                            nama,
                                            flag
                                    FROM $this->table
                                    WHERE MD5(id_cabang) = '$id'
                                    AND id_company = '" . $this->id_company . "'")->row();
        return $select;
    }

    public function save($data, $id = null, $id_company = null)
    {

        if ($id != null) {
            $cek_data = $this->db->select("id_cabang")
                ->where("kode", $data['kode'])
                ->where("MD5(id_cabang) != '$id'")
                ->where("id_company", $id_company)
                ->from($this->table)
                ->get()
                ->num_rows();
            if ($cek_data > 0) {
                return  __response_duplicate();
            } else {
                $this->db->where(array('md5(id_cabang)' => $id, 'id_company' => $id_company));
                $data['user_update'] = $this->nik_karyawan." - ".$this->nm_karyawan;
                $data['tgl_update'] = date('Y-m-d h:i:s');
                $update = $this->db->update($this->table, $data);
                $this->logger->create_log('master_cabang', 'edit', $this->db->last_query());
                return  __response_update($update);
            }
        } else {

            $data['user_input'] = $this->nik_karyawan." - ".$this->nm_karyawan;

            $id_cabang = $this->fungsi->getNextId($this->table, 'id_cabang', $id_company, 3);

            $masuk = "08:00:00";
            $pulang = "17:00:00";
            $start_absen_masuk = "07:00:00";
            $batas_absen_pulang = "23:59:59";

            $id_jam_kerja = $this->fungsi->getNextId('jam_kerja', 'id_jam_kerja', $id_company, 3);
            $no_urut = substr($id_jam_kerja, -3);

            $data_jam_kerja = [];
            for ($i = 0; $i < 7; $i++) {
                $nextid = substr($id_jam_kerja, 0, -3) . sprintf("%03d", $no_urut);

                if ($i == 5 or $i == 6) {
                    $data_jam_kerja[] = array(
                        'id_jam_kerja'       => $nextid,
                        'masuk'              => '',
                        'hari'               => $i + 1,
                        'pulang'             => '',
                        'start_absen_masuk'  => '',
                        'batas_absen_pulang' => '',
                        'libur'              => '1',
                        'jml_jamkerja'       => '',
                        'id_cabang'          => $id_cabang,
                        'id_company'         => $id_company,
                        'user_input'         => $this->nik_karyawan." - ".$this->nm_karyawan
                    );
                } else {
                    $data_jam_kerja[] = array(
                        'id_jam_kerja'       => $nextid,
                        'masuk'              => $masuk,
                        'hari'               => $i + 1,
                        'pulang'             => $pulang,
                        'start_absen_masuk'  => $start_absen_masuk,
                        'batas_absen_pulang' => $batas_absen_pulang,
                        'libur'              => '0',
                        'jml_jamkerja'       => '8',
                        'id_cabang'          => $id_cabang,
                        'id_company'         => $id_company,
                        'user_input'         => $this->nik_karyawan." - ".$this->nm_karyawan
                    );
                }

                $no_urut++;
            }

            $level_user = array('3', '7', '2', '5');

            # GET ID TERAKHIR APPROVAL IZIN
            $id_approval_izin = $this->fungsi->getNextId('p_approval_izin', 'id', $id_company, 3);
            $no_urut_id_approval_izin = substr($id_approval_izin, -3);

            # GET ID TERAKHIR APPROVAL LEMBUR
            $id_approval_lembur = $this->fungsi->getNextId('p_approval_lembur', 'id', $id_company, 3);
            $no_urut_id_approval_lembur = substr($id_approval_lembur, -3);

            # GET ID TERAKHIR APPROVAL REIMBURSE
            $id_approval_reimburse = $this->fungsi->getNextId('p_approval_reimbursement', 'id', $id_company, 3);
            $no_urut_id_approval_reimburse = substr($id_approval_reimburse, -3);

            $data_approval_izin = [];
            $data_approval_lembur = [];
            $data_approval_reimbursement = [];

            foreach ($level_user as $key) {

                # DATA INSERT APPROVAL IZIN
                $nextid_approval_izin = substr($id_approval_izin, 0, -3) . sprintf("%03d", $no_urut_id_approval_izin);

                $data_approval_izin[] = array(
                    'id'             => $nextid_approval_izin,
                    'id_cabang'      => $id_cabang,
                    'level_user'     => $key,
                    'level_approval' => $this->fungsi->get_level_approval_izin($key),
                    'id_company'     => $id_company,
                    'user_input'     => $this->nik_karyawan." - ".$this->nm_karyawan
                );

                # DATA INSERT APPROVAL LEMBUR
                $nextid_approval_lembur = substr($id_approval_lembur, 0, -3) . sprintf("%03d", $no_urut_id_approval_lembur);

                $data_approval_lembur[] = array(
                    'id'             => $nextid_approval_lembur,
                    'id_cabang'      => $id_cabang,
                    'level_user'     => $key,
                    'level_approval' => $this->fungsi->get_level_approval_lembur($key),
                    'id_company'     => $id_company,
                    'user_input'     => $this->nik_karyawan." - ".$this->nm_karyawan
                );

                # DATA INSERT APPROVAL REIMBURSE
                $nextid_approval_reimburse = substr($id_approval_lembur, 0, -3) . sprintf("%03d", $no_urut_id_approval_reimburse);

                $data_approval_reimbursement[] = array(
                    'id'             => $nextid_approval_reimburse,
                    'id_cabang'      => $id_cabang,
                    'level_user'     => $key,
                    'level_approval' => $this->fungsi->get_level_approval_reimburse($key),
                    'id_company'     => $id_company,
                    'user_input'     => $this->nik_karyawan." - ".$this->nm_karyawan
                );

                $no_urut_id_approval_izin++;
                $no_urut_id_approval_lembur++;
                $no_urut_id_approval_reimburse++;
            }

            $this->db->trans_start();

            $this->db->insert($this->table, array_merge($data, array('id_cabang' => $id_cabang)));
            $this->db->insert_batch('jam_kerja', $data_jam_kerja);
            $this->db->insert_batch('p_approval_izin', $data_approval_izin);
            $this->db->insert_batch('p_approval_lembur', $data_approval_lembur);
            $this->db->insert_batch('p_approval_reimbursement', $data_approval_reimbursement);

            $this->db->trans_complete();

            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 delete($id = null)
    {

        $this->db->select("id_karyawan");
        $this->db->from("data_karyawan");
        $this->db->where("md5(id_cabang)", $id);
        $this->db->where("id_company", $this->id_company);
        $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_cabang') . '</font>';
            return __response_delete(false, ["message" => $message]);
        } else {
            $this->db->trans_start();

            $this->db->where(array('md5(id_cabang)' => $id, 'id_company' => $this->id_company));
            $this->db->delete('master_shift');

            $this->db->where(array('md5(id_cabang)' => $id, 'id_company' => $this->id_company));
            $this->db->delete('jam_kerja');

            $this->db->where(array('md5(id_cabang)' => $id, 'id_company' => $this->id_company));
            $this->db->delete('p_approval_izin');

            $this->db->where(array('md5(id_cabang)' => $id, 'id_company' => $this->id_company));
            $this->db->delete('p_approval_lembur');

            $this->db->where(array('md5(id_cabang)' => $id, 'id_company' => $this->id_company));
            $this->db->delete('p_approval_reimbursement');

            $this->db->where(array('md5(id_cabang)' => $id));
            $delete = $this->db->delete($this->table);

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

            $this->db->trans_complete();

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

    function max_karyawan()
    {
        $this->db->select('mp.nama')
            ->from('master_company mc')
            ->join('tb_paket mp', 'mc.id_tb_paket = mp.id_tb_paket')
            ->where('id_company', $this->id_company);
        return $this->db->get()->row();
    }
}
