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

class Ptkp_m extends CI_Model
{
    protected $table = 'data_karyawan';

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

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

    public function count_all()
    {
        return $this->db->select('id_karyawan')
            ->from($this->table)
            ->where('id_company', $this->id_company)
            ->count_all_results();
    }

    private function _get_datatables_query()
    {
        $this->db->select('
                id_karyawan,
                nama_lengkap,
                nik,
                tanggungan
            ')
            ->from($this->table)
            ->join('master_jabatan mj', 'mj.id_jabatan = data_karyawan.id_jabatan')
            ->where('data_karyawan.id_company', $this->id_company)
            ->where_in('status', ['1', '2', '3', '4'])
            ->where_not_in('mj.level_user', ['1', '6'])
            ->where('tanggungan', '');

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

        $this->db->order_by('nama_lengkap ASC, nik ASC');
    }

    public function get_ptkp(): array
    {
        $query = $this->db->select('kode, keterangan')
            ->from('ptkp')
            ->get()
            ->result();

        $data = [];
        foreach ($query as $value) {
            $data[$value->kode] = [
                'kode'       => $value->kode,
                'keterangan' => $value->keterangan
            ];
        }

        return $data;
    }

    // ACTION SAVE
    public function save($id, $ptkp)
    {
        $this->db->trans_begin();

        # Update tanggungan / ptkp
        $data['user_update'] = $this->nik_karyawan . ' - ' . $this->nm_karyawan;
        $data['tgl_update']  = date('Y-m-d H:i:s');
        $this->db->update($this->table, ['tanggungan' => $ptkp], ['id_karyawan' => $id]);

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