<?php

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

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

class Employee extends MY_Controller {

    public $data = array();

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

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

        check_permission(VIEW);

        $config = array();
        $search = $this->input->get('search');

        $config = array();
        $config = get_pagination(ADMIN_PER_PAGE);
        if ($search) {
            $config['base_url'] = site_url('hrm/employee/?search=') . $search;
        } 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->employee->get_employee_list($config['per_page'], $offset, $search, $count = TRUE);
        $this->pagination->initialize($config);
        $this->data['employees'] = $this->employee->get_employee_list($config['per_page'], $offset, $search, $count = FALSE);

        $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));
        $this->data['search'] = $search;
        $this->data['list'] = TRUE;
        $this->layout->title($this->lang->line('manage_employee') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('index', $this->data);
    }

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

        check_permission(ADD);
        if ($_POST) {
            $this->_prepare_employee_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_employee_data();
                $insert_id = $this->employee->insert('employees', $data);
                if ($insert_id) {
                    // $sms['role_id'] = $this->input->post('role_id');
                    // $sms['user_id'] = $data['user_id'];
                    // $this->_send_sms($sms);

                    create_log('Has been created a Employee : ' . $data['name']);
                    success($this->lang->line('insert_success'));
                    redirect('hrm/employee');
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('hrm/employee/add');
                }
            } else {
                $this->data = $_POST;
            }
        }
        $this->data['departments'] = $this->employee->get_list('departments', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['roles'] = $this->employee->get_list('roles', array('status' => 1), '', '', '', 'id', 'ASC');

        $this->data['add'] = TRUE;
        $this->layout->title($this->lang->line('add') . ' ' . $this->lang->line('employee') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('add', $this->data);
    }

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

        check_permission(EDIT);
        if ($_POST) {
            $this->_prepare_employee_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_employee_data();
                $updated = $this->employee->update('employees', $data, array('user_id' => $this->input->post('id')));
                if ($updated) {
                    create_log('Has been updated a Employee : ' . $data['name']);
                    success($this->lang->line('update_success'));
                    redirect('hrm/employee');
                } else {
                    error($this->lang->line('update_failed'));
                    redirect('hrm/employee/edit/' . $this->input->post('id'));
                }
            } else {
                $this->data['employee'] = $this->employee->get_single_employee($id);
            }
        } else {
            if ($id) {
                $this->data['employee'] = $this->employee->get_single_employee($id);
                if (!$this->data['employee']) {
                    redirect('hrm/employee');
                }
            }
        }
        $this->data['departments'] = $this->employee->get_list('departments', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['designations'] = $this->employee->get_list('designations', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['roles'] = $this->employee->get_list('roles', array('status' => 1), '', '', '', 'id', 'ASC');

        $this->data['edit'] = TRUE;
        $this->layout->title($this->lang->line('edit') . ' ' . $this->lang->line('employee') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('edit', $this->data);
    }

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

    public function get_single_employee() {
        $user_id = $this->input->post('user_id');
        $this->data['employee'] = $this->employee->get_single_employee($user_id);
        echo $this->load->view('view', $this->data);
    }

    /*****************Function _prepare_employee_validation**********************************
     * @type            : Function
     * @function name   : _prepare_employee_validation
     * @description     : Process "Employee" user input data validation
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    private function _prepare_employee_validation() {
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="error-message" style="color: red;">', '</div>');

        if (!$this->input->post('id')) {

            $this->form_validation->set_rules('username', $this->lang->line('username'), 'trim|required|callback_username');
            $this->form_validation->set_rules('password', $this->lang->line('password'), 'trim|required');
        }
        $this->form_validation->set_rules('department_id', $this->lang->line('department'), 'trim|required');
        $this->form_validation->set_rules('designation_id', $this->lang->line('designation'), 'trim|required');
        $this->form_validation->set_rules('role_id', $this->lang->line('role'), 'trim|required');
        $this->form_validation->set_rules('email', $this->lang->line('email'), 'trim|valid_email');
        $this->form_validation->set_rules('name', $this->lang->line('name'), 'trim|required');
        $this->form_validation->set_rules('phone', $this->lang->line('phone'), 'trim|required');
        $this->form_validation->set_rules('gender', $this->lang->line('gender'), 'trim');
        $this->form_validation->set_rules('religion', $this->lang->line('religion'), 'trim');
        $this->form_validation->set_rules('dob', $this->lang->line('birth_date'), 'trim');
        $this->form_validation->set_rules('joining_date', $this->lang->line('join_date'), 'trim|required');
    }

    /*     * ***************Function username**********************************
     * @type            : Function
     * @function name   : username
     * @description     : Unique check for "Employee username" data/value
     *
     * @param           : null
     * @return          : boolean true/false
     * ********************************************************** */

    public function username() {
        if ($this->input->post('id') == '') {
            $username = $this->employee->duplicate_check($this->input->post('username'));
            if ($username) {
                $this->form_validation->set_message('username', $this->lang->line('already_exist'));
                return FALSE;
            } else {
                return TRUE;
            }
        } else if ($this->input->post('id') != '') {
            $username = $this->employee->duplicate_check($this->input->post('username'), $this->input->post('id'));
            if ($username) {
                $this->form_validation->set_message('username', $this->lang->line('already_exist'));
                return FALSE;
            } else {
                return TRUE;
            }
        } else {
            return TRUE;
        }
    }

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

        $items = array();
        $items[] = 'commission_type';
        $items[] = 'department_id';
        $items[] = 'designation_id';
        $items[] = 'name';
        $items[] = 'phone';
        $items[] = 'national_id';
        $items[] = 'gender';
        $items[] = 'religion';
        $items[] = 'blood_group';
        $items[] = 'marital_status';
        $items[] = 'present_address';
        $items[] = 'permanent_address';
        $items[] = 'email';
        $items[] = 'sort_by';

        $data = elements($items, $_POST);

        $data['dob'] = date('Y-m-d', strtotime($this->input->post('dob')));
        $data['joining_date'] = date('Y-m-d', strtotime($this->input->post('joining_date')));
        $data['age'] = floor((time() - strtotime($data['dob'])) / 31556926);
        $data['status'] = $this->input->post('status') ?? 0;
        $data['is_view_on_web'] = $this->input->post('is_view_on_web') ?? 0;

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

            $user_data = array(
                'role_id' => $this->input->post('role_id'),
                'username' => $this->input->post('username'),
                'device_id' => $this->input->post('device_id'),
            );
            $this->db->update('users', $user_data, array('id' => $this->input->post('id')));
        } else {
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['created_by'] = logged_in_user_id();
            // create user
            $data['user_id'] = $this->employee->create_user();
        }

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

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

        if ($_FILES['resume']['name']) {
            $data['resume'] = $this->_upload_resume();
        }
        return $data;
    }

    /*     * ***************Function _upload_photo**********************************
     * @type            : Function
     * @function name   : _upload_photo
     * @description     : Process to upload employee photo into server
     *                     and return photo name
     * @param           : null
     * @return          : $return_photo string value
     * ********************************************************** */

    private function _upload_photo() {

        $prev_photo = $this->input->post('prev_photo');
        $photo = $_FILES['photo']['name'];
        $photo_type = $_FILES['photo']['type'];
        $return_photo = '';
        if ($photo != "") {
            if (
                $photo_type == 'image/jpeg' || $photo_type == 'image/pjpeg' ||
                $photo_type == 'image/jpg' || $photo_type == 'image/png' ||
                $photo_type == 'image/x-png' || $photo_type == 'image/gif'
            ) {

                $destination = 'assets/uploads/employee-photo/';

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

                move_uploaded_file($_FILES['photo']['tmp_name'], $destination . $photo_path);

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

                $return_photo = $photo_path;
            }
        } else {
            $return_photo = $prev_photo;
        }

        return $return_photo;
    }

    /*     * ***************Function _upload_signature**********************************
     * @type            : Function
     * @function name   : _upload_signature
     * @description     : process to upload employee signature in the server
     *                     and return signature file name
     * @param           : null
     * @return          : $return_signature string value
     * ********************************************************** */

    private function _upload_signature() {

        $prev_signature = $this->input->post('prev_signature');
        $signature = $_FILES['signature']['name'];
        $signature_type = $_FILES['signature']['type'];
        $return_signature = '';
        if ($signature != "") {
            if (
                $signature_type == 'image/jpeg' || $signature_type == 'image/pjpeg' ||
                $signature_type == 'image/jpg' || $signature_type == 'image/png' ||
                $signature_type == 'image/x-png' || $signature_type == 'image/gif'
            ) {

                $destination = 'assets/uploads/employee-signature/';

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

                move_uploaded_file($_FILES['signature']['tmp_name'], $destination . $signature_path);

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

                $return_signature = $signature_path;
            }
        } else {
            $return_signature = $prev_signature;
        }

        return $return_signature;
    }

    /*     * ***************Function _upload_resume**********************************
     * @type            : Function
     * @function name   : _upload_resume
     * @description     : Process to upload employee resume into server
     *                     and return resume file name
     * @param           : null
     * @return          : $return_resume string value
     * ********************************************************** */

    private function _upload_resume() {

        $prev_resume = $this->input->post('prev_resume');
        $resume = $_FILES['resume']['name'];
        $resume_type = $_FILES['resume']['type'];
        $return_resume = '';

        if ($resume != "") {
            if (
                $resume_type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
                $resume_type == 'application/msword' || $resume_type == 'text/plain' ||
                $resume_type == 'application/vnd.ms-office' || $resume_type == 'application/pdf'
            ) {

                $destination = 'assets/uploads/employee-resume/';

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

                move_uploaded_file($_FILES['resume']['tmp_name'], $destination . $resume_path);

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

                $return_resume = $resume_path;
            }
        } else {
            $return_resume = $prev_resume;
        }

        return $return_resume;
    }

    /*     * ***************Function delete**********************************
     * @type            : Function
     * @function name   : delete
     * @description     : delete "Employee" data from database
     *                     and unlink employee photo and Resume from server
     * @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/employee');
        }

        $employee = $this->employee->get_single('employees', array('id' => $id));
        if (!empty($employee)) {

            // delete employee data
            $this->employee->delete('employees', array('id' => $id));
            // delete employee login data
            $this->employee->delete('users', array('id' => $employee->user_id));

            // delete employee resume and photo
            $destination = 'assets/uploads/';
            if (file_exists($destination . '/employee-photo/' . $employee->photo)) {
                @unlink($destination . '/employee-photo/' . $employee->photo);
            }
            if (file_exists($destination . '/employee-signature/' . $employee->signature)) {
                @unlink($destination . '/employee-signature/' . $employee->signature);
            }
            if (file_exists($destination . '/employee-resume/' . $employee->resume)) {
                @unlink($destination . '/employee-resume/' . $employee->resume);
            }
            create_log('Has been deleted a Employee : ' . $employee->name);

            success($this->lang->line('delete_success'));
        } else {
            error($this->lang->line('delete_failed'));
        }
        redirect('hrm/employee');
    }


    /*     * ***************Function _send_sms**********************************
     * @type            : Function
     * @function name   : _send_sms
     * @description     : this function used to send reset username and passwrd by user mobile         
     * @param           : null; 
     * @return          : null 
     * ********************************************************** */

    private function _send_sms($data = null) {
        $profile = get_user_by_role($data['role_id'], $data['user_id']);
        if ($profile->phone) {
            $notification = $this->db->get_where('notifications', array('status' => 1, 'type' => 'registration_sms'))->row();
            $body = $this->db->get_where('sms_templates', array('type' => $notification->id))->row();
            if ($notification->is_sms && $body->role_id == $profile->role_id) {
                $this->load->library('mimsms');
                $phone   = $profile->phone;
                $message = get_formatted_body($body->template, $profile->role_id, $profile->user_id);
                if ($phone) {
                    return $this->mimsms->sendMimSms($phone, $message);
                }
            }
        }
    }
}
