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

class Approval_atasan_m extends CI_Model
{
    var $table = 'sales_approver';

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

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

    public function count_all($id_group_m="all"){
        $this->_get_datatables_query($id_group_m);
        return $this->db->count_all_results();
    }
    private function _get_datatables_query($id_group_m="all"){
        $this->db->select("
            approver.id_karyawan,
            karyawan.nik AS nik_karyawan,
            karyawan.nama_lengkap AS nama_karyawan,
            atasan.nik AS nik_atasan,
            atasan.nama_lengkap AS nama_atasan,
            approver.approval,
            approver.id_group_m,
            sgm.kode AS kode_group,
            sgm.nama AS nama_group
        ")
        ->from($this->table. ' AS approver')
        ->join('data_karyawan as karyawan', 'karyawan.id_karyawan = approver.id_karyawan')
        ->join('data_karyawan as atasan', 'atasan.id_karyawan = approver.id_atasan', 'LEFT')
        ->join('sales_group_m as sgm', 'sgm.id_group_m = approver.id_group_m', 'LEFT')
        ->where("approver.id_company", $this->id_company)
        ->where("approver.status", '1');

        if($this->is_sales_admin == true){
            if (!in_array($this->sales_admin_group, ["all", ""])) {
                $this->db->where_in('approver.id_group_m', explode(',', $this->sales_admin_group));
            }
        }
        
        if($id_group_m != "all"){
            $this->db->where('approver.id_group_m', $id_group_m);
        }

        $column_search = array('karyawan.nama_lengkap', 'atasan.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++;
        }

        // $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("karyawan.nama_lengkap" => "ASC");
            $this->db->order_by(key($order_by), $order_by[key($order_by)]);
        }
    }

    public function getDataById($id = null){
        $query = $this->db->select("approver.id_karyawan,
                approver.id_atasan,
                karyawan.nik AS nik_karyawan,
                karyawan.nama_lengkap AS nama_karyawan,
                atasan.nik AS nik_atasan,
                atasan.nama_lengkap AS nama_atasan,
                approver.approval,
                approver.id_group_m,
                sgm.kode AS kode_group,
                sgm.nama AS nama_group
            ")
            ->from($this->table. ' AS approver')
            ->join('data_karyawan as karyawan', 'karyawan.id_karyawan = approver.id_karyawan')
            ->join('data_karyawan as atasan', 'atasan.id_karyawan = approver.id_atasan', 'LEFT')
            ->join('sales_group_m as sgm', 'sgm.id_group_m = approver.id_group_m', 'LEFT')
            ->where('approver.id_company', $this->id_company)
            ->where('MD5(approver.id_karyawan)', $id)
            ->get()
            ->row();

        return $query;
    }

    public function save($data = [], $id=""){
        $karyawan = $this->_get_data_karyawan($data['id_karyawan']);
        $group    = $this->_get_data_group($data['id_group_m']);

        // Array Data
        $user_input = array(
            'tgl_input'  => date("Y-m-d H:i:s"),
            'user_input' => $this->nik_karyawan. " - ". $this->nm_karyawan
        );

        $user_update    = array(
            'tgl_update'     => date("Y-m-d H:i:s"),
            'user_update'	=> $this->nik_karyawan. " - ". $this->nm_karyawan
        );

        $target_personil_p = array(
            'id_karyawan' => $data['id_karyawan'],
            'tahun'       => date('Y'),
            'bulan'       => date('m'),
            'nominal'     => 0,
            // 'id_group_m'  => $data['id_group_m'],
            'id_company'  => $this->id_company
        );
        
        $target_personil_r = array(
            'id_karyawan'       => $data['id_karyawan'],
            'nik'               => $karyawan->nik,
            'nama_karyawan'     => $karyawan->nama_karyawan,
            'tahun'             => date('Y'),
            'bulan'             => date('m'),
            'nominal_target'    => 0,
            'nominal_realisasi' => 0,
            'jumlah_po'         => 0,
            'id_group_m'        => $data['id_group_m'],
            'nama_group'        => $group->kode_group. " - ". $group->nama_group,
            'id_company'        => $this->id_company
        );
        
        $target_poin_p = array(
            'id_karyawan' => $data['id_karyawan'],
            'poin'     => 0,
            'id_company'  => $this->id_company
        );

        $target_poin_trx = array(
            'id_karyawan'   => $data['id_karyawan'],
            'nik'           => $karyawan->nik,
            'nama_karyawan' => $karyawan->nama_karyawan,
            'poin'          => 0,
            'id_group_m'    => $data['id_group_m'],
            'nama_group'    => $group->kode_group. " - ". $group->nama_group,
            'tgl_trx'       => date('Y-m-d'),
            'id_company'    => $this->id_company
        );

        // Check id_group apakah sama
        $check_id_group = $this->_check_id_group_karyawan($data['id_karyawan'], $data['id_group_m']); // true = id_group sama, false = id_group berubah

        // Validasi id_karyawan & id_atasan sama
        if($data['id_karyawan'] == $data['id_atasan']){
            $message = array('message' => '<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>' . $this->lang->line('error_sama_karyawan_atasan') . '</font>');
            return __response_save(false, $message);
        }

        // Validasi data sama
        $cek_id_karyawan = $this->_cek_id_karyawan($data['id_karyawan'], $id);
        if(!empty($cek_id_karyawan)){
            $message = array('message' => '<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>' . $this->lang->line('error_duplicate') . '</font>');
            return __response_save(false, $message);
        }else{
            if(!empty($id)){
            // PROSES UPDATE
                $this->db->trans_start();
                    # 1. update data sales/approval
                    $this->db->where("md5(id_karyawan)",$id);
                    $this->db->where('id_company', $this->id_company);
                    $this->db->update($this->table, array_merge($data,$user_update));

                    # 2. update my_session
                    // $this->set_my_session_sales();

                    if($check_id_group['id_group_sama'] == false){
                        if($check_id_group['data_target_exist'] == false){
                            # 3. update target_personil_p
                            $this->db->set('nominal', 0);
                            $this->db->where('tahun', date('Y'));
                            $this->db->where('bulan', date('m'));
                            $this->db->where("md5(id_karyawan)",$id);
                            $this->db->where('id_company', $this->id_company);
                            $this->db->update('sales_target_personil_p');
                            
                            # 4. insert target_personil_r
                            $this->db->insert('sales_target_personil_r', array_merge($target_personil_r, $user_input));
                        }

                        # 5. delete target_poin_trx
                        $this->db->where('tgl_trx', date('Y-m-d'));
                        $this->db->where('MD5(id_karyawan)', $id);
                        $this->db->where('id_company', $this->id_company);
                        $this->db->delete('sales_target_poin_trx');

                        # 6. insert target_poin_trx
                        $this->db->insert('sales_target_poin_trx', array_merge($target_poin_trx, $user_input));
                    }
                
                $this->db->trans_complete();
                if ($this->db->trans_status() === TRUE) {
                    $this->db->trans_commit();
                    $this->set_my_session_sales();
                    return  __response_update(true);
                } else {
                    $this->db->trans_rollback();
                    return  __response_update(false);
                }

            }else{
            // PROSES SAVE    
                $this->db->trans_start();
                    $cek_data_sales = $this->_cek_data_sales($data['id_karyawan']);
                    if(empty($cek_data_sales)){
                    // JIKA DATA SALES BELUM ADA
                        # 1A. insert data sales approver
                        $this->db->insert($this->table, array_merge($data,$user_input));

                        # 2A. update flag sales karyawan
                        $this->db->where("id_karyawan", $data['id_karyawan']);
                        $this->db->where('id_company', $this->id_company);
                        $this->db->set('flag_sales', '1');
                        $this->db->update('data_karyawan');

                        # 3A. insert target_personil_p
                        $this->db->insert('sales_target_personil_p', array_merge($target_personil_p, $user_input));
                        
                        # 4A. insert target_personil_r
                        $this->db->insert('sales_target_personil_r', array_merge($target_personil_r, $user_input));
                        
                        # 5A. insert target_poin_p
                        $this->db->insert('sales_target_poin_p', array_merge($target_poin_p, $user_input));
                        
                        # 6A. insert target_poin_trx
                        $this->db->insert('sales_target_poin_trx', array_merge($target_poin_trx, $user_input));
                    }else{
                    // JIKA DATA SUDAH ADA TAPI NONAKTIF
                        # 1B. update data sales approver
                        $status = array('status' => '1');
                        $this->db->where("id_karyawan", $data['id_karyawan']);
                        $this->db->where('id_company', $this->id_company);
                        $this->db->update($this->table, array_merge($data, $status));
                    }

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

    public function delete($id = null){
        $this->db->trans_start();

        # 1. delete data sales approver
        $this->db->where('MD5(id_karyawan)', $id);
        $this->db->where('id_company', $this->id_company);
        $this->db->delete($this->table);

        # 2. update flag sales karyawan
        $this->db->where("MD5(id_karyawan)", $id);
        $this->db->where('id_company', $this->id_company);
        $this->db->set('flag_sales', '0');
        $this->db->update('data_karyawan');

        # 3. delete target_personil_p
        $this->db->where('tahun', date('Y'));
        $this->db->where('bulan', date('m'));
        $this->db->where('MD5(id_karyawan)', $id);
        $this->db->where('id_company', $this->id_company);
        $this->db->delete('sales_target_personil_p');

        # 4. delete target_personil_r
        $this->db->where('tahun', date('Y'));
        $this->db->where('bulan', date('m'));
        $this->db->where('MD5(id_karyawan)', $id);
        $this->db->where('id_company', $this->id_company);
        $this->db->delete('sales_target_personil_r');

        # 5. delete target_poin_p
        $this->db->where('MD5(id_karyawan)', $id);
        $this->db->where('id_company', $this->id_company);
        $this->db->delete('sales_target_poin_p');

        # 6. delete target_poin_trx
        $this->db->where('tgl_trx', date('Y-m-d'));
        $this->db->where('MD5(id_karyawan)', $id);
        $this->db->where('id_company', $this->id_company);
        $this->db->delete('sales_target_poin_trx');

        $this->set_my_session_sales();

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

    // START Untuk Tampilan Home
    public function get_max_sales(){
        $max_sales =  $this->db->select('tb_paket.max_sales')
                                ->from('master_company')
                                ->join('tb_paket', 'tb_paket.id_tb_paket = master_company.id_tb_paket')
                                ->where('master_company.id_company', $this->id_company)
                                ->get()
                                ->row()
                                ->max_sales;
                                
        return intval($max_sales);
    }

    public function get_active_sales(){
        $this->db->select('id_karyawan')
                ->from('sales_approver')
                ->where('id_company', $this->id_company)
                ->where("status", '1');

        if($this->is_sales_admin == true){
            if (!in_array($this->sales_admin_group, ["all", ""])) {
                $this->db->where_in('id_group_m', explode(',', $this->sales_admin_group));
            }
        }
        
        return $this->db->get()->num_rows();
    }

    public function get_sales_other_group(){
        if (!in_array($this->sales_admin_group, ["all", ""])) {
            $this->db->select('id_karyawan')
                    ->from('sales_approver')
                    ->where('id_company', $this->id_company)
                    ->where("status", '1');
                    
            $this->db->where_not_in('id_group_m', explode(',', $this->sales_admin_group));
            return $this->db->get()->num_rows();
        }else{
            return 0;
        }
    }
    // END Untuk Tampilan Home

    // START Untuk Validasi Memilih Atasan pada Dropdown Group
    public function check_karyawan_admin($id_group = ""){
        $query = $this->db->select('id_karyawan')
                            ->from('sales_admin_m')
                            ->where('id_company', $this->id_company)
                            ->where('id_group_m !=', "all")
                            ->not_like('id_group_m', $id_group)
                            ->get()
                            ->result();
        
        $data = array();
        foreach($query AS $value){
            $data[] = $value->id_karyawan;
        }

        return $data;
    }

    public function check_karyawan_approver($id_group = ""){
        $query = $this->db->select('id_karyawan')
                            ->from($this->table)
                            ->where('id_company', $this->id_company)
                            ->where('id_group_m !=', "")
                            ->where('id_group_m !=', $id_group)
                            ->get()
                            ->result();
        
        $data = array();
        foreach($query AS $value){
            $data[] = $value->id_karyawan;
        }

        return $data;
    }
    // END Untuk Validasi Memilih Atasan pada Dropdown Group

    // START Get Data Ketika Pindah Group
    private function _get_data_karyawan($id_karyawan = ""){
        return $this->db->select("
                dk.id_karyawan,
                dk.nik,
                dk.nama_lengkap AS nama_karyawan,
            ")
            ->from("data_karyawan AS dk")
            ->where("dk.id_company", $this->id_company)
            ->where("dk.id_karyawan", $id_karyawan)
            ->get()
            ->row();
    }

    private function _get_data_group($id_group_m = ""){
        return $this->db->select("
                sgm.id_group_m,
                sgm.kode AS kode_group,
                sgm.nama AS nama_group
            ")
            ->from("sales_group_m AS sgm")
            ->where("sgm.id_company", $this->id_company)
            ->where("sgm.id_group_m", $id_group_m)
            ->get()
            ->row();
    }

    private function _check_id_group_karyawan($id_karyawan = "", $id_group_m=""){
        $data              = array();

        $id_group_sekarang = $id_group_m;
        $id_group_dulu = $this->db->select("sa.id_group_m")
                                    ->from("sales_approver AS sa")
                                    ->where("sa.id_company", $this->id_company)
                                    ->where("sa.id_karyawan", $id_karyawan)
                                    ->get()
                                    ->row()
                                    ->id_group_m;

        if($id_group_dulu == $id_group_sekarang){
            $data['id_group_sama'] = true;
        }else{
            $data['id_group_sama'] = false;
        }

        $data_target_exist = $this->db->select("id_karyawan")
                                    ->from("sales_target_personil_r")
                                    ->where("id_company", $this->id_company)
                                    ->where("id_karyawan", $id_karyawan)
                                    ->where("id_group_m", $id_group_sekarang)
                                    ->where("tahun", date('Y'))
                                    ->where("bulan", date('m'))
                                    ->get()
                                    ->row()
                                    ->id_karyawan;

        if(!empty($data_target_exist)){
            $data['data_target_exist'] = true;
        }else{
            $data['data_target_exist'] = false;
        }

        return $data;
    }
    // END Get Data Ketika Pindah Group

    private function _cek_id_karyawan($id_karyawan="", $id=""){
        if(!empty($id)){
            $this->db->where('MD5(id_karyawan) !=', $id);
        }
        
        $query = $this->db->select("id_karyawan")
                        ->from($this->table)
                        ->where('id_company', $this->id_company)
                        ->where('id_karyawan', $id_karyawan)
                        ->where("status", '1')
                        ->get()
                        ->row()
                        ->id_karyawan;

        return $query;
    }

    private function _cek_data_sales($id_karyawan=""){
        $query = $this->db->select("id_karyawan")
                        ->from($this->table)
                        ->where('id_company', $this->id_company)
                        ->where('id_karyawan', $id_karyawan)
                        ->where("status", '0')
                        ->get()
                        ->row()
                        ->id_karyawan;

        return $query;
    }

    private function set_my_session_sales(){
        $is_sales = $this->db->select('id_karyawan, approval')
            ->from('sales_approver')
            ->where('id_karyawan', $this->id_karyawan)
            ->where('id_company', $this->id_company)
            ->get();

        $is_sales_atasan = $this->db->select('COUNT(id_atasan) as ttl_bawahan')
            ->from('sales_approver')
            ->where('id_company', $this->id_company)
            ->where('id_atasan', $this->id_karyawan)
            ->get()
            ->row()
            ->ttl_bawahan;

        $data = array(
            'is_sales'                    => ($is_sales && $is_sales->num_rows() > 0) ? true : false,
            'is_sales_skip_approval'      => ($is_sales && $is_sales->row()->approval == '0') ? true : false,
            'is_sales_atasan'             => ($is_sales_atasan > 0) ? true : false,
        );

        return $this->session->set_userdata($data);
    }
}