<?php

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

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

class Anesthetist extends MY_Controller {

    public $data = array();

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

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

        check_permission(VIEW);

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

        $config = array();
        $config = get_pagination(ADMIN_PER_PAGE);
        if ($search) {
            $config['base_url'] = site_url('doctor/anesthetist/?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->anesthetist->get_anesthetist_list($config['per_page'], $offset, $search, $count = TRUE);
        $this->pagination->initialize($config);
        $this->data['anesthetists'] = $this->anesthetist->get_anesthetist_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_anesthetist') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('anesthetist/index', $this->data);
    }

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

        check_permission(ADD);
        if ($_POST) {
            $this->_prepare_anesthetist_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_anesthetist_data();
                $insert_id = $this->anesthetist->insert('anesthetists', $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 Anesthetist : ' . $data['name']);
                    success($this->lang->line('insert_success'));
                    redirect('doctor/anesthetist');
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('doctor/anesthetist/add');
                }
            } else {
                $this->data = $_POST;
            }
        }
        $this->data['departments'] = $this->anesthetist->get_list('departments', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['roles'] = $this->anesthetist->get_list('roles', array('status' => 1), '', '', '', 'id', 'ASC');

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

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

        check_permission(EDIT);
        if ($_POST) {
            $this->_prepare_anesthetist_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_anesthetist_data();
                $updated = $this->anesthetist->update('anesthetists', $data, array('user_id' => $this->input->post('id')));
                if ($updated) {
                    create_log('Has been updated a Anesthetist : ' . $data['name']);
                    success($this->lang->line('update_success'));
                    redirect('doctor/anesthetist');
                } else {
                    error($this->lang->line('update_failed'));
                    redirect('doctor/anesthetist/edit/' . $this->input->post('id'));
                }
            } else {
                $this->data['anesthetist'] = $this->anesthetist->get_single_anesthetist($id);
            }
        } else {
            if ($id) {
                $this->data['anesthetist'] = $this->anesthetist->get_single_anesthetist($id);
                if (!$this->data['anesthetist']) {
                    redirect('doctor/anesthetist');
                }
            }
        }
        $this->data['departments'] = $this->anesthetist->get_list('departments', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['designations'] = $this->anesthetist->get_list('designations', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['roles'] = $this->anesthetist->get_list('roles', array('status' => 1), '', '', '', 'id', 'ASC');

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

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

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

    /*****************Function _prepare_anesthetist_validation**********************************
     * @type            : Function
     * @function name   : _prepare_anesthetist_validation
     * @description     : Process "Anesthetist" user input data validation
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    private function _prepare_anesthetist_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');
        $this->form_validation->set_rules('designation_id', $this->lang->line('designation'), 'trim');
        $this->form_validation->set_rules('role_id', $this->lang->line('role'), 'trim|required');
        $this->form_validation->set_rules('charge', $this->lang->line('charge'), '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('bn_name', $this->lang->line('bn_name'), 'trim');
        $this->form_validation->set_rules('phone', $this->lang->line('phone'), 'trim|required|callback_phone');
        $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|required');
    }

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

    public function username() {
        if ($this->input->post('id') == '') {
            $username = $this->anesthetist->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->anesthetist->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 phone**********************************
     * @type            : Function
     * @function name   : phone
     * @description     : Unique check for "Vd phone" data/value
     *
     * @param           : null
     * @return          : boolean true/false
     * ********************************************************** */

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

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

        $items = array();
        $items[] = 'charge';
        $items[] = 'employee_type';
        $items[] = 'specialist';
        $items[] = 'bmdc_reg_no';
        $items[] = 'department_id';
        $items[] = 'designation_id';
        $items[] = 'name';
        $items[] = 'bn_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[] = 'is_view_on_web';
        $items[] = 'sort_by';
        $items[] = 'status';

        $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);

        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->anesthetist->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 anesthetist 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 anesthetist 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 anesthetist 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 "Anesthetist" data from database
     *                     and unlink anesthetist 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('doctor/anesthetist');
        }

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

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

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

            success($this->lang->line('delete_success'));
        } else {
            error($this->lang->line('delete_failed'));
        }
        redirect($_SERVER['HTTP_REFERER']);
    }


    /*     * ***************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);
                }
            }
        }
    }
}
