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

class Divisi_model extends CI_Model
{
    const TABLE = 'tb_divisi';

    public function get_all($active_only = FALSE)
    {
        if ($active_only) {
            $this->db->where('is_active', 1);
        }
        return $this->db->order_by('nama_divisi', 'ASC')->get(self::TABLE)->result();
    }

    public function get_by_id($id)
    {
        return $this->db->where('id_divisi', (int) $id)->get(self::TABLE)->row();
    }

    public function kode_exists($kode, $exclude_id = NULL)
    {
        $this->db->where('kode_divisi', $kode);
        if ($exclude_id) {
            $this->db->where('id_divisi !=', (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_divisi', (int) $id)->update(self::TABLE, $data);
        return $this->db->affected_rows();
    }

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

    public function count_jabatan($id_divisi)
    {
        return $this->db->where('id_divisi', (int) $id_divisi)
                        ->count_all_results('tb_jabatan');
    }
}
