<?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 Sms.
 * @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('mimsms');
    }

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

        check_permission(VIEW);

        $search = $this->input->get('search');
        $config = array();
        $config = get_pagination(ADMIN_PER_PAGE);
        if ($search) {
            $config['base_url'] = site_url('message/patient/?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->patient->get_sms_list($config['per_page'], $offset, $search, $count = TRUE);
        $this->pagination->initialize($config);
        $this->data['texts'] = $this->patient->get_sms_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('patient') . ' ' . $this->lang->line('sms') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('patient/index', $this->data);
    }

    /*****************Function add**********************************
     * @type            : Function
     * @function name   : add
     * @description     : send patient sms for user
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function add() {

        check_permission(ADD);

        if ($_GET) {
            $keyword = $this->input->get('keyword');
            $gender = $this->input->get('gender');
            $religion = $this->input->get('religion');

            $this->data['patients'] = $this->patient->get_patient_list($keyword, $gender, $religion);

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

    /*****************Function send**********************************
     * @type            : Function
     * @function name   : send
     * @description     : send patient sms for user
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function send() {

        check_permission(ADD);

        if ($_POST) {
            $this->load->library('form_validation');
            $this->form_validation->set_error_delimiters('<div class="error-message" style="color: red;">', '</div>');
            $this->form_validation->set_rules('body', $this->lang->line('message'), 'trim|required');

            if ($this->form_validation->run() === TRUE) {
                $notification = $this->db->get_where('notifications', array('status' => 1, 'type' => 'patient'))->row();
                if (empty($notification->is_sms)) {
                    error('This message notification is not active. Please contact an administrator.');
                    redirect($_SERVER['HTTP_REFERER']);
                    return false;
                }

                $data['role_id'] = PATIENT;
                $data['sender_role_id'] = $this->session->userdata('role_id');
                $data['sms_type'] = 'patient';
                $data['receiver_id'] = null;
                $data['body'] = $this->input->post('body');
                $data['status'] = 1;
                $data['created_at'] = date('Y-m-d H:i:s');
                $data['created_by'] = logged_in_user_id();

                $receivers = '';
                if (!empty($_POST['sends'])) {
                    $insert_id = $this->patient->insert('text_messages', $data);
                    foreach ($_POST['sends'] as $value) {
                        $phone = $_POST['phone'][$value];

                        $message = get_formatted_body($this->input->post('body'), PATIENT, $value);
                        $receivers .= $value . ',';
                        if ($phone != '') {
                            $this->_send_sms($phone, $message);
                            $userData = ['role_id' => PATIENT, 'user_id' => $value];
                            create_sms_log($message, $phone, 'patient', $userData);
                        }
                    }
                }

                // update text_messages table 
                $updated = $this->patient->update('text_messages', array('receivers' => $receivers), array('id' => $insert_id));
                if ($updated) {
                    create_log('Has been created a patient text message');
                    success($this->lang->line('sms_send_success'));
                    redirect('message/patient');
                } else {
                    error($this->lang->line('sms_send_failed'));
                    redirect('message/patient/add');
                }
            } else {
                error($this->lang->line('sms_send_failed'));
                redirect($_SERVER['HTTP_REFERER'], $this->data);
            }
        }
    }

    public function _send_sms($phone, $message) {
        return $this->mimsms->sendMimSms($phone, $message);
    }

    /*****************Function delete**********************************
     * @type            : Function
     * @function name   : delete
     * @description     : delete "SMS" 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('message/patient');
        }

        $sms = $this->patient->get_single('text_messages', array('id' => $id));
        if (!empty($sms)) {
            // delete sms data
            $this->patient->delete('text_messages', array('id' => $id));
            create_log('Has been deleted a patient text message : ' . $sms->body);
            success($this->lang->line('delete_success'));
        } else {
            error($this->lang->line('delete_failed'));
        }
        redirect('message/patient');
    }
}
