<?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);
        //$this->load->library('ciqrcode');
    }
    
    public function set_qrcode($patient_unique_id)
    {
        $this->load->library('ciqrcode');
        // header("Content-Type: image/png");
        // $params['data'] = 'This is a text to encode become QR Code';
        // $this->ciqrcode->generate($params);
        
        
        $params['data'] = $patient_unique_id;
        $params['level'] = 'H';
        $params['size'] = 10;
        $params['savename'] = FCPATH.'assets/uploads/qr/'.$patient_unique_id.'.png';
        $this->ciqrcode->generate($params);
    }

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

        check_permission(VIEW);

        $search = $this->input->get('search');
        $card_issue = $this->input->get('card_issue');
        $config = array();
        $config = get_pagination(ADMIN_PER_PAGE);
        if ($search || $card_issue) {
            $config['base_url'] = site_url('patient/?search=' . $search . '&card_issue=' . $card_issue);
        } 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, $card_issue, $count = TRUE);
        $this->pagination->initialize($config);
        $this->data['patients'] = $this->patient->get_patient_list($config['per_page'], $offset, $search, $card_issue, $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['card_issue'] = $card_issue;

        $this->data['list'] = TRUE;
        $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->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->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[] = 'name';
        $items[] = 'bn_name';
        $items[] = 'phone';
        $items[] = 'email';
        $items[] = 'gender';
        $items[] = 'religion';
        $items[] = 'blood_group';
        $items[] = 'marital_status';
        $items[] = 'national_id';
        $items[] = 'profession';
        $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);
                }
            }
        }
    }

    public function generate_card()
    {
        check_permission(ADD);
        $patient_id = $this->input->post('user_id');
        if ($patient_id) {
            $patient = $this->patient->get_single('patients', array('user_id' => $patient_id));
            $data['card_issue_date'] = date('Y-m-d');
            $data['issue_by'] = logged_in_user_id();
            $data['card_remark'] = null;
            $this->patient->update('patients', $data, array('user_id' => $patient_id));
            create_log('Has been generate a patient card : ' . $data['card_issue_date'] . 'patient name: ' . $patient->name);
        }
    }

    public function download($user_id)
    {
        check_permission(VIEW);
        $patient = $this->patient->get_single('patients', array('user_id' => $user_id));
        if ($patient && $patient->card_issue_date) {
            $this->data['patient'] = $patient;
            $this->data['qrcode'] = $this->set_qrcode($patient->patient_unique_id);
            $this->load->view('patient/card', $this->data);
        } else {
            redirect('patient');
        }
    }
}
