<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Department_Model extends MY_Model {

    function __construct() {
        parent::__construct();
    }
    public function get_department_list($limit, $offset, $keyword, $count) {
        $this->db->select('D.*');
        $this->db->from('departments AS D');
        if ($keyword) {
            $this->db->like('D.name', $keyword, 'both');
            $this->db->or_like('D.bn_name', $keyword, 'both');
            $this->db->or_like('D.remark', $keyword, 'both');
        }
        $this->db->order_by('D.id', 'DESC');
        if ($count) {
            return $this->db->count_all_results();
        } else {
            $this->db->limit($limit, $offset);
            $query = $this->db->get();

            if ($query->num_rows() > 0) {
                return $query->result();
            }
        }
        return array();
    }

    public function get_single_department($id) {
        $this->db->select('D.*, C.name as created_by, M.name as modified_by');
        $this->db->from('departments AS D');
        $this->db->join('employees AS C', 'C.user_id = D.created_by', 'left');
        $this->db->join('employees AS M', 'M.user_id = D.modified_by', 'left');
        $this->db->where('D.id', $id);
        return $this->db->get()->row();
    }

    function duplicate_check($name, $id = null) {
        if ($id) {
            $this->db->where_not_in('id', $id);
        }
        $this->db->where('name', $name);
        return $this->db->get('departments')->num_rows();
    }
}
