<?php

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

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

class Patient extends MY_Controller
{

    public $data = array();

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

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

        check_permission(VIEW);

        $date = $this->input->get('date');
        $patient_category = $this->input->get('patient_category');
        $reference_emp = $this->input->get('reference_emp');
        $search = $this->input->get('search');
        $config = array();
        $config = get_pagination(ADMIN_PER_PAGE);
        if ($_GET && $date) {
            $exp = explode('-', $date);
            $form_date = date('Y-m-d', strtotime($exp[0]));
            $to_date = date('Y-m-d', strtotime($exp[1]));
            $config['base_url'] = site_url('patient/?search=' . $search . '&patient_category=' . $patient_category . '&date=' . $date. '&reference_emp=' . $reference_emp);
            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->patient->get_patient_list($config['per_page'], $offset, $search, $form_date, $to_date, $patient_category, $reference_emp, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['patients'] = $this->patient->get_patient_list($config['per_page'], $offset, $search, $form_date, $to_date, $patient_category, $reference_emp, $count = FALSE);
    
            $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));
            
            
            
        } 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->patient->get_patient_list($config['per_page'], $offset, $search, date('Y-m-d'), date('Y-m-d'), $patient_category, $reference_emp, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['patients'] = $this->patient->get_patient_list($config['per_page'], $offset, $search, date('Y-m-d'), date('Y-m-d'), $patient_category, $reference_emp, $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['date'] = $date;
        $this->data['patient_category'] = $patient_category;
        $this->data['reference_emp'] = $reference_emp;

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

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

        check_permission(ADD);
        if ($_POST) {
            $this->_prepare_patient_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_patient_data();
                $insert_id = $this->patient->insert('patients', $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 Patient : ' . $data['name']);
                    success($this->lang->line('insert_success'));
                    redirect('patient');
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('patient/add');
                }
            } else {
                $this->data = $_POST;
            }
        }
        $this->data['add'] = TRUE;
        $this->data['reference_employees'] = $this->patient->get_employee_list();
        $this->layout->title($this->lang->line('add') . ' ' . $this->lang->line('patient') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('patient/add', $this->data);
    }

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

        check_permission(EDIT);
        if ($_POST) {
            $this->_prepare_patient_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_patient_data();
                $updated = $this->patient->update('patients', $data, array('user_id' => $this->input->post('id')));
                if ($updated) {
                    create_log('Has been updated a Patient : ' . $data['name']);
                    success($this->lang->line('update_success'));
                    redirect('patient');
                } else {
                    error($this->lang->line('update_failed'));
                    redirect('patient/edit/' . $this->input->post('id'));
                }
            } else {
                $this->data['patient'] = $this->patient->get_single_patient($id);
            }
        } else {
            if ($id) {
                $this->data['patient'] = $this->patient->get_single_patient($id);
                if (!$this->data['patient']) {
                    redirect('patient');
                }
            }
        }
        $this->data['edit'] = TRUE;
        $this->data['reference_employees'] = $this->patient->get_employee_list();
        $this->layout->title($this->lang->line('edit') . ' ' . $this->lang->line('patient') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('patient/edit', $this->data);
    }

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

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

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

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

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

        $items = array();
        $items[] = 'reference_emp';
        $items[] = 'name';
        $items[] = 'bn_name';
        $items[] = 'phone';
        $items[] = 'email';
        $items[] = 'patient_category';
        $items[] = 'gender';
        $items[] = 'religion';
        $items[] = 'blood_group';
        $items[] = 'marital_status';
        $items[] = 'national_id';
        $items[] = 'address';
        $items[] = 'guardian_name';
        $items[] = 'note';
        $data = elements($items, $_POST);


        $data['dob'] = date('Y-m-d', strtotime($this->input->post('dob')));
        $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();
        } else {
            $data['status'] = 1;
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['created_by'] = logged_in_user_id();
            // create patient_unique_id
            $data['patient_unique_id'] = $this->patient->get_custom_id('patients', '1');
            // create user
            $data['user_id'] = $this->patient->create_user();
        }

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

        return $data;
    }

    /*     * ***************Function _upload_photo**********************************
     * @type            : Function
     * @function name   : _upload_photo
     * @description     : Process to upload patient 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/patient-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 delete**********************************
     * @type            : Function
     * @function name   : delete
     * @description     : delete "Patient" 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('patient');
        }

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

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

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

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

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

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