<?php

defined('BASEPATH') or exit('No direct script access allowed');

/* * *****************Department.php**********************************
 * @product name    : Hospital Management System
 * @type            : Class
 * @class name      : Department
 * @description     : Manage department.
 * @author          : South Bangla IT Zone Team
 * @url             : http://hms.sbitzone.com
 * @support         : rabibd.it@gmail.com
 * @copyright       : South Bangla IT Zone Team
 * ********************************************************** */

class Department extends MY_Controller {

    public $data = array();

    function __construct() {
        parent::__construct();
        $this->load->model('Department_Model', 'department', true);
    }

    /*****************Function index**********************************
     * @type            : Function
     * @function name   : index
     * @description     : Load "Department List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function index() {

        check_permission(VIEW);

        $keyword = $this->input->get('keyword');
        $config = array();
        $config = get_pagination(ADMIN_PER_PAGE);
        if ($keyword) {
            $config['base_url'] = site_url('hrm/department/?keyword=' . $keyword);
        } else {
            $config['base_url'] = current_url();
        }
        if ($this->input->get('page')) {
            $sgm = (int) trim($this->input->get('page'));
            $offset = $config['per_page'] * ($sgm - 1);
        } else {
            $offset = 0;
        }

        $config['total_rows'] = $this->department->get_department_list($config['per_page'], $offset, $keyword, $count = TRUE);
        $this->pagination->initialize($config);
        $this->data['departments'] = $this->department->get_department_list($config['per_page'], $offset, $keyword, $count = FALSE);
        $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));
        $this->data['keyword'] = $keyword;


        $this->data['list'] = TRUE;
        $this->layout->title($this->lang->line('manage_department') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('department/index', $this->data);
    }

    /*****************Function add**********************************
     * @type            : Function
     * @function name   : add
     * @description     : Load "Add new Department" user interface
     *                    and process to store "departments" into database
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function add() {

        check_permission(ADD);
        if ($_POST) {
            $this->_prepare_department_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_department_data();
                $insert_id = $this->department->insert('departments', $data);
                if ($insert_id) {
                    create_log('Has been created a department : ' . $data['name']);
                    success($this->lang->line('insert_success'));
                    redirect('hrm/department');
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('hrm/department/add');
                }
            } else {
                $this->data = $_POST;
            }
        }
        $this->data['add'] = TRUE;
        $this->layout->title($this->lang->line('add') . ' ' . $this->global_setting->brand_title);
        $this->layout->view('department/add', $this->data);
    }

    /*****************Function edit**********************************
     * @type            : Function
     * @function name   : edit
     * @description     : Load Update "Department" user interface
     *                    with populate "Department" value
     *                    and process to update "departments" into database
     * @param           : $id integer value
     * @return          : null
     * ********************************************************** */
    public function edit($id = null) {

        check_permission(EDIT);
        if ($_POST) {
            $this->_prepare_department_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_department_data();
                $updated = $this->department->update('departments', $data, array('id' => $this->input->post('id')));
                if ($updated) {
                    create_log('Has been updated a department : ' . $data['name']);
                    success($this->lang->line('update_success'));
                    redirect('hrm/department');
                } else {
                    error($this->lang->line('update_failed'));
                    redirect('hrm/department/edit/' . $this->input->post('id'));
                }
            } else {
                $this->data['department'] = $this->department->get_single('departments', array('id' => $this->input->post('id')));
            }
        } else {
            if ($id) {
                $this->data['department'] = $this->department->get_single('departments', array('id' => $id));
                if (!$this->data['department']) {
                    redirect('hrm/department');
                }
            }
        }
        $this->data['edit'] = TRUE;
        $this->layout->title($this->lang->line('edit') . ' ' . $this->global_setting->brand_title);
        $this->layout->view('department/edit', $this->data);
    }

    /*     * ***************Function get_single_department**********************************
     * @type            : Function
     * @function name   : get_single_department
     * @description     : "Load single department information" from database                  
     *                    to the user interface   
     * @param           : null
     * @return          : null 
     * ********************************************************** */

    public function get_single_department() {
        $id = $this->input->post('id');
        $this->data['department'] = $this->department->get_single_department($id);
        echo $this->load->view('hrm/department/view', $this->data);
    }

    /*****************Function _prepare_department_validation**********************************
     * @type            : Function
     * @function name   : _prepare_department_validation
     * @description     : Process "Department" user input data validation
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    private function _prepare_department_validation() {
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="error-message" style="color: red;">', '</div>');
        $this->form_validation->set_rules('type', $this->lang->line('department') . ' ' . $this->lang->line('type'), 'trim|required');
        $this->form_validation->set_rules('name', $this->lang->line('department') . ' ' . $this->lang->line('name'), 'trim|required|callback_name');
    }

    /*****************Function name**********************************
     * @type            : Function
     * @function name   : name
     * @description     : Unique check for "Department Name" data/value
     *
     * @param           : null
     * @return          : boolean true/false
     * ********************************************************** */
    public function name() {
        if ($this->input->post('id') == '') {
            $department = $this->department->duplicate_check($this->input->post('name'));
            if ($department) {
                $this->form_validation->set_message('name', $this->lang->line('already_exist'));
                return FALSE;
            } else {
                return TRUE;
            }
        } else if ($this->input->post('id') != '') {
            $department = $this->department->duplicate_check($this->input->post('name'), $this->input->post('id'));
            if ($department) {
                $this->form_validation->set_message('name', $this->lang->line('already_exist'));
                return FALSE;
            } else {
                return TRUE;
            }
        } else {
            return TRUE;
        }
    }

    /*****************Function _get_posted_department_data**********************************
     * @type            : Function
     * @function name   : _get_posted_department_data
     * @description     : Prepare "Department" user input data to save into database
     *
     * @param           : null
     * @return          : $data array(); value
     * ********************************************************** */
    private function _get_posted_department_data() {

        $items = array();
        $items[] = 'type';
        $items[] = 'name';
        $items[] = 'bn_name';
        $items[] = 'description';
        $items[] = 'bn_description';
        $items[] = 'remark';
        $items[] = 'sort_by';
        $data = elements($items, $_POST);

        $data['is_view_on_web'] = $this->input->post('is_view_on_web') ?? 0;
        $data['status'] = $this->input->post('status') ?? 0;

        if ($this->input->post('id')) {
            $data['modified_at'] = date('Y-m-d H:i:s');
            $data['modified_by'] = logged_in_user_id();
        } else {
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['created_by'] = logged_in_user_id();
        }

        if ($_FILES['image']['name']) {
            $data['image'] = $this->_upload_image();
        }

        return $data;
    }

    /*     * ***************Function _upload_image**********************************
     * @type            : Function
     * @function name   : _upload_image
     * @description     : Process to upload department image into server
     *                     and return image file name
     * @param           : null
     * @return          : $return_image string value
     * ********************************************************** */

    private function _upload_image() {

        $prev_image = $this->input->post('prev_image');
        $image = $_FILES['image']['name'];
        $image_type = $_FILES['image']['type'];
        $return_image = '';

        if ($image != "") {
            if (
                $image_type == 'image/jpeg' || $image_type == 'image/pjpeg' ||
                $image_type == 'image/jpg' || $image_type == 'image/png' ||
                $image_type == 'image/x-png' || $image_type == 'image/gif'
            ) {

                $destination = 'assets/uploads/department-image/';

                $file_type = explode(".", $image);
                $extension = strtolower($file_type[count($file_type) - 1]);
                $image_path = 'department-image-' . time() . '-sbiz.' . $extension;

                move_uploaded_file($_FILES['image']['tmp_name'], $destination . $image_path);

                // need to unlink previous image
                if ($prev_image != "") {
                    if (file_exists($destination . $prev_image)) {
                        @unlink($destination . $prev_image);
                    }
                }

                $return_image = $image_path;
            }
        } else {
            $return_image = $prev_image;
        }

        return $return_image;
    }

    /*****************Function delete**********************************
     * @type            : Function
     * @function name   : delete
     * @description     : delete "Department" data from database
     *
     * @param           : $id integer value
     * @return          : null
     * ********************************************************** */
    public function delete($id = null) {

        check_permission(DELETE);

        if (!is_numeric($id)) {
            error($this->lang->line('unexpected_error'));
            redirect('hrm/department');
        }

        $rows = [];
        $department = $this->department->get_single('departments', array('id' => $id));
        if (isset($department) && $id > 0) {
            $this->db->trans_start();
            // $dept = $this->db->get_where('departments', array('id' => $id))->row_array();
            // $des = $this->db->get_where('designations', array('department_id' => $id))->result_array();
            // array_push($rows, $dept, $des);
            // $properties = json_encode($rows);
            create_log('Has been deleted a department : ' . $department->name);

            // delete image
            $destination = 'assets/uploads/';
            if (file_exists($destination . '/department-image/' . $department->image)) {
                @unlink($destination . '/department-image/' . $department->image);
            }

            $this->department->delete('departments', array('id' => $id));
            $this->department->delete('designations', array('department_id' => $id));
            $this->db->trans_complete();
            success($this->lang->line('delete_success'));
        } else {
            error($this->lang->line('delete_failed'));
        }
        redirect($_SERVER['HTTP_REFERER']);
    }
}
