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

class Jabatan_model extends CI_Model
{
    const TABLE = 'tb_jabatan';

    public function get_all($active_only = FALSE)
    {
        $this->db->select('j.*, d.nama_divisi')
                 ->from(self::TABLE . ' j')
                 ->join('tb_divisi d', 'd.id_divisi = j.id_divisi', 'left');
        if ($active_only) {
            $this->db->where('j.is_active', 1);
        }
        return $this->db->order_by('d.nama_divisi', 'ASC')
                        ->order_by('j.level_jabatan', 'ASC')
                        ->order_by('j.nama_jabatan', 'ASC')
                        ->get()->result();
    }

    public function get_by_divisi($id_divisi, $active_only = TRUE)
    {
        if ($active_only) {
            $this->db->where('is_active', 1);
        }
        return $this->db->where('id_divisi', (int) $id_divisi)
                        ->order_by('level_jabatan', 'ASC')
                        ->order_by('nama_jabatan', 'ASC')
                        ->get(self::TABLE)->result();
    }

    public function get_by_id($id)
    {
        return $this->db->select('j.*, d.nama_divisi')
                        ->from(self::TABLE . ' j')
                        ->join('tb_divisi d', 'd.id_divisi = j.id_divisi', 'left')
                        ->where('j.id_jabatan', (int) $id)
                        ->get()->row();
    }

    public function kode_exists($kode, $exclude_id = NULL)
    {
        $this->db->where('kode_jabatan', $kode);
        if ($exclude_id) {
            $this->db->where('id_jabatan !=', (int) $exclude_id);
        }
        return $this->db->count_all_results(self::TABLE) > 0;
    }

    public function insert($data)
    {
        $this->db->insert(self::TABLE, $data);
        return $this->db->insert_id();
    }

    public function update($id, $data)
    {
        $this->db->where('id_jabatan', (int) $id)->update(self::TABLE, $data);
        return $this->db->affected_rows();
    }

    public function toggle_active($id)
    {
        $row = $this->db->where('id_jabatan', (int) $id)->get(self::TABLE)->row();
        if (!$row) return FALSE;
        $this->db->where('id_jabatan', (int) $id)
                 ->update(self::TABLE, ['is_active' => $row->is_active ? 0 : 1]);
        return TRUE;
    }

    public function count_pegawai($id_jabatan)
    {
        return $this->db->where('id_jabatan', (int) $id_jabatan)
                        ->where('status_pegawai', 'AKTIF')
                        ->count_all_results('tb_pegawai');
    }
}
