<?php

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

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

class Ipd extends MY_Controller {

    public $data = array();

    function __construct() {
        parent::__construct();
        $this->load->model('Ipd_Model', 'ipd', true);
        $this->load->library('mimsms');
    }

    /*****************Function index**********************************
     * @type            : Function
     * @function name   : index
     * @description     : Load "Ipd 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/ipd/?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->ipd->get_sms_list($config['per_page'], $offset, $search, $count = TRUE);
        $this->pagination->initialize($config);
        $this->data['texts'] = $this->ipd->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('ipd') . ' ' . $this->lang->line('sms') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('ipd/index', $this->data);
    }

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

        check_permission(ADD);

        if ($_GET && $this->input->get('date')) {
            $type = $this->input->get('type');
            $date = $this->input->get('date') ?? date('Y-m-d');
            $exp = explode('-', $date);
            $form_date = date('Y-m-d', strtotime($exp[0]));
            $to_date = date('Y-m-d', strtotime($exp[1]));
            $doctor_id = $this->input->get('doctor_id');
            $reference_id = $this->input->get('reference_id');

            $this->data['ipd_patients'] = $this->ipd->get_ipd_patient_list($type, $form_date, $to_date, $doctor_id, $reference_id);

            $this->data['type'] = $type;
            $this->data['date'] = $date;
            $this->data['doctor_id'] = $doctor_id;
            $this->data['reference_id'] = $reference_id;
        }

        $this->data['doctors'] = $this->ipd->get_doctor_list();
        $this->data['references'] = $this->ipd->get_list('employees', array('status' => 1));
        $this->data['add'] = TRUE;
        $this->layout->title($this->lang->line('ipd') . ' ' . $this->lang->line('sms') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('ipd/add', $this->data);
    }

    /*****************Function send**********************************
     * @type            : Function
     * @function name   : send
     * @description     : send ipd 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' => 'ipd_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'] = 'ipd_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['patients'])) {
                    $insert_id = $this->ipd->insert('text_messages', $data);
                    foreach ($_POST['patients'] 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, 'ipd_patient', $userData);
                        }
                    }
                }

                // update text_messages table 
                $updated = $this->ipd->update('text_messages', array('receivers' => $receivers), array('id' => $insert_id));
                if ($updated) {
                    create_log('Has been created a ipd patient text message');
                    success($this->lang->line('sms_send_success'));
                    redirect('message/ipd');
                } else {
                    error($this->lang->line('sms_send_failed'));
                    redirect('message/ipd/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/ipd');
        }

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