<?php

class Employee_Model extends MY_Model {

    function __construct() {
        parent::__construct();
    }

    public function getEmployees($id, $dept, $manager, $branch) {
        if ($id) {
            $this->db->where('id', (int) $id);
        }
        if ($dept) {
            $this->db->where('dept', $dept);
        }
        if ($manager) {
            $this->db->where('manager', $manager);
        }
        if ($branch) {
            $this->db->where('branch', $branch);
        }
        return $this->db->get('employee');
    }

    public function saveEmployee($data, $id = NULL) {
        $this->_table_name = 'employee';
        $this->_primary_key = 'id';
        if ($id !== NULL && $id > 0) {
            $data['updated_by'] = 1;
        } else {
            $data['created_by'] = 1;
        }
        return parent::save($data, $id);
    }

    public function checkDepartment($column, $value, $update = 'no') {
        $this->_table_name = 'employeedept';
        $this->_primary_key = 'id';
        if ($update == 'yes') {
            $old = $this->input->post('old');
            if (trim(strtolower($old)) === trim(strtolower($value))) {
                return false;
            } else {
                return $this->doesThisDepartmentExist($this->_table_name, $column, $value);
            }
        } else {
            return $this->doesThisDepartmentExist($this->_table_name, $column, $value);
        }
    }

    private function doesThisDepartmentExist($table, $column, $value) {
        return $this->db->where(array($column => $value, 'branch' => $this->session->userdata('branch')))->count_all_results($table) > 0;
    }
    public function saveDepartment($data, $id = NULL) {
        $this->_table_name = 'employeedept';
        $this->_primary_key = 'id';
        if ($id !== NULL && $id > 0) {
            $data['updated_by'] = 1;
        } else {
            $data['created_by'] = 1;
        }
        return parent::save($data, $id);
    }

    public function checkManager($column, $value, $update = 'no') {
        $this->_table_name = 'employeemanager';
        $this->_primary_key = 'id';
        if ($update == 'yes') {
            $old = $this->input->post('old');
            if (trim(strtolower($old)) === trim(strtolower($value))) {
                return false;
            } else {
                return $this->exists($this->_table_name, $column, $value);
            }
        } else {
            return $this->exists($this->_table_name, $column, $value);
        }
    }

    public function saveManager($data, $id = NULL) {
        $this->_table_name = 'employeemanager';
        $this->_primary_key = 'id';
        if ($id !== NULL && $id > 0) {
            $data['updated_by'] = 1;
        } else {
            $data['created_by'] = 1;
        }
        return parent::save($data, $id);
    }

}
