<?php

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

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

class Opd extends MY_Controller {

    public $data = array();

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

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

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

        check_permission(ADD);

        if ($_GET && $this->input->get('date') && $this->input->get('doctor_id')) {
            $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['opd_patients'] = $this->opd->get_opd_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['doctor'] = $this->opd->get_single('employees', array('user_id' => $doctor_id));
        }

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

    /*****************Function send**********************************
     * @type            : Function
     * @function name   : send
     * @description     : send opd 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' => 'opd_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'] = 'opd_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->opd->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, 'opd_patient', $userData);
                        }
                    }
                }

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

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