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

class Home_m extends CI_Model {
    var $table = 'master_jabatan';

    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->_get_datatables_query();
        return $this->db->count_all_results();
    }

    private function _get_datatables_query(){
        $this->db->select("
                    mj.id_jabatan,
                    mj.kode_jabatan,
                    group.level AS nama_usergroup,
                    mj.nama AS nama_jabatan,
                    kebp.bobot_aspek_kepribadian AS bobot_pengaturan,
                    SUM(COALESCE(kapm.`bobot`, 0)) AS bobot_data
                ")
            ->from($this->table. ' AS mj')
            ->join('kpi_aspek_bobot_p AS kebp', 'mj.id_jabatan = kebp.id_jabatan', 'LEFT')
            ->join('kpi_aspek_kepribadian_m AS kapm', 'mj.id_jabatan = kapm.id_jabatan', 'LEFT')
            ->join('usergroup AS group', 'group.id = mj.level_user')
            ->where("mj.id_company", $this->id_company)
            ->where_not_in("mj.level_user", ['1', '6'])
            ->group_by('mj.id_jabatan');
    
         $column_search = array('mj.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++;
        }
    
        if (isset($_GET['order'])) {
            // $this->db->order_by($column_order[$_GET['order']['0']['column']], $_GET['order']['0']['dir']);
        } else {
            $this->db->order_by('group.urutan ASC, mj.nama ASC');
        }
    }
}