<?php
class Admin_group_model extends CI_Model {

    public function get_all() {
        return $this->db->order_by('nama_lengkap', 'ASC')->get('admin_groups')->result();
    }

    public function get_by_id($id) {
        $sql = "
            SELECT a.*, u.nama as unor_nama
            FROM admin_groups a
            LEFT JOIN unor u ON a.unor_id = u.unor_id
            WHERE a.id = ?
        ";
        return $this->db->query($sql, [$id])->row();
    }

    public function get_unor_list() {
        $this->db->select('unor_id, nama as unor_nama', FALSE);
        $this->db->from('unor');
        $this->db->where('unor_id IS NOT NULL');
        $this->db->where('nama IS NOT NULL');
        $this->db->distinct();
        $this->db->order_by('nama', 'ASC');
        return $this->db->get()->result();
    }

    public function insert($data) {
        $this->db->insert('admin_groups', $data);
        return $this->db->insert_id();
    }

    public function update($id, $data) {
        return $this->db->where('id', $id)->update('admin_groups', $data);
    }

    public function delete($id) {
        return $this->db->where('id', $id)->delete('admin_groups');
    }

    public function username_exists($username, $id = null) {
        $this->db->where('username', $username);
        if ($id) {
            $this->db->where('id !=', $id);
        }
        return $this->db->count_all_results('admin_groups') > 0;
    }
}