<?php

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

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

class Doctor extends MY_Controller {

    public $data = array();

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

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

        check_permission(VIEW);

        $config = array();
        $keyword = $this->input->get('keyword');
        $department_id = $this->input->get('department_id');
        $designation_id = $this->input->get('designation_id');

        $config = array();
        $config = get_pagination(ADMIN_PER_PAGE);
        if ($keyword || $department_id || $designation_id) {
            $config['base_url'] = site_url('doctor/?keyword=' . $keyword . '&department_id=' . $department_id . '&designation_id=' . $designation_id);
        } 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->doctor->get_doctor_list($config['per_page'], $offset, $keyword, $department_id, $designation_id, $count = TRUE);
        $this->pagination->initialize($config);
        $this->data['doctors'] = $this->doctor->get_doctor_list($config['per_page'], $offset, $keyword, $department_id, $designation_id, $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['department_id'] = $department_id;
        $this->data['designation_id'] = $designation_id;

        $this->data['departments'] = $this->doctor->get_list('departments', array('status' => 1, 'type' => 'doctor'), '', '', '', 'sort_by', 'ASC');
        $this->data['designations'] = $this->doctor->get_list('designations', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['list'] = TRUE;
        $this->layout->title($this->lang->line('manage_doctor') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('index', $this->data);
    }

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

        check_permission(ADD);

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

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

    /*****************Function edit**********************************
     * @type            : Function
     * @function name   : edit
     * @description     : Load Update "Doctor" user interface
     *                    with populate "Doctor" 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_doctor_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_doctor_data();
                $updated = $this->doctor->update('employees', $data, array('id' => $this->input->post('id')));
                if ($updated) {
                    create_log('Has been updated a doctor : ' . $data['name']);
                    success($this->lang->line('update_success'));
                    redirect('doctor');
                } else {
                    error($this->lang->line('update_failed'));
                    redirect('doctor/edit/' . $this->input->post('id'));
                }
            } else {
                $this->data['doctor'] = $this->doctor->get_single_doctor($id);
            }
        } else {
            if ($id) {
                $this->data['doctor'] = $this->doctor->get_single_doctor($id);
                if (!$this->data['doctor']) {
                    redirect('doctor');
                }
            }
        }
        $this->data['departments'] = $this->doctor->get_list('departments', array('status' => 1, 'type' => 'doctor'), '', '', '', 'sort_by', 'ASC');
        $this->data['designations'] = $this->doctor->get_list('designations', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['roles'] = $this->doctor->get_list('roles', array('status' => 1), '', '', '', 'id', 'ASC');

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

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

    public function view($id = null) {

        check_permission(VIEW);

        $this->data['profile'] = $this->doctor->get_single_doctor($id);
        $this->data['social'] = $this->doctor->get_single('employee_socials', array('status' => 1, 'user_id' => $this->data['profile']->user_id), '', '', '', 'id', 'ASC');

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

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

    public function get_single_doctor() {
        $id = $this->input->post('id');
        $this->data['doctor'] = $this->doctor->get_single_doctor($id);
        echo $this->load->view('view', $this->data);
    }

    /*****************Function _prepare_doctor_validation**********************************
     * @type            : Function
     * @function name   : _prepare_doctor_validation
     * @description     : Process "Doctor" user input data validation
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    private function _prepare_doctor_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('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|callback_phone');
        $this->form_validation->set_rules('gender', $this->lang->line('gender'), 'trim|required');
        $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');
    }

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

    public function username() {
        if ($this->input->post('id') == '') {
            $username = $this->doctor->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->doctor->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->doctor->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->doctor->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_doctor_data**********************************
     * @type            : Function
     * @function name   : _get_posted_doctor_data
     * @description     : Prepare "Doctor" user input data to save into database
     *
     * @param           : null
     * @return          : $data array(); value
     * ********************************************************** */
    private function _get_posted_doctor_data() {

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

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

        $data['employee_type'] = 'doctor';
        $data['commission_type'] = 'mbbs';
        $data['is_view_on_home'] = $this->input->post('is_view_on_home') ?? 0;
        $data['is_view_on_web'] = $this->input->post('is_view_on_web') ?? 0;
        $data['status'] = $this->input->post('status') ?? 0;
        $data['dob'] = $this->input->post('dob') ? date('Y-m-d', strtotime($this->input->post('dob'))) : null;
        $data['joining_date'] = $this->input->post('joining_date') ? date('Y-m-d', strtotime($this->input->post('joining_date'))) : null;

        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'),
                'device_id' => $this->input->post('device_id'),
            );
            $doctor = $this->doctor->get_single('employees', array('id' => $this->input->post('id')));
            $this->db->update('users', $user_data, array('id' => $doctor->user_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->doctor->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 doctor 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 doctor 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 doctor 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 "Doctor" data from database
     *                     and unlink doctor 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');
        }

        $rows = [];
        $doctor = $this->doctor->get_single('employees', array('id' => $id));
        if (isset($doctor) && $id > 0) {

            $this->db->trans_start();
            // $emp = $this->db->get_where('doctors', array('id' => $id))->row_array();
            // $user = $this->db->get_where('users', array('id' => $doctor->user_id))->row_array();
            // array_push($rows, $emp, $user);
            // $properties = json_encode($rows);

            create_log('Has been deleted a doctor : ' . $doctor->name);

            // delete doctor resume and photo
            $destination = 'assets/uploads/';
            if (file_exists($destination . '/employee-photo/' . $doctor->photo)) {
                @unlink($destination . '/employee-photo/' . $doctor->photo);
            }
            if (file_exists($destination . '/employee-signature/' . $doctor->signature)) {
                @unlink($destination . '/employee-signature/' . $doctor->signature);
            }
            if (file_exists($destination . '/employee-resume/' . $doctor->resume)) {
                @unlink($destination . '/employee-resume/' . $doctor->resume);
            }

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

            $this->db->trans_complete();
            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 (isset($profile->phone) && !empty($profile->phone)) {
            $notification = $this->db->get_where('notifications', array('status' => 1, 'type' => 'registration'))->row();
            $body = $this->db->get_where('sms_templates', array('notification_id' => $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);
                }
            }
        }
    }
}
