<?php

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

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

class Sms extends MY_Controller {

    public $data = array();

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

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

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

        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('role_id', $this->lang->line('receiver'), 'trim|required');

            if ($this->form_validation->run() === TRUE) {
                $notification = $this->db->get_where('notifications', array('status' => 1, 'type' => 'general'))->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'] = ADMIN;
                $data['sender_role_id'] = $this->session->userdata('role_id');
                $data['sms_type'] = 'general';
                $data['receiver_id'] = $this->input->post('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();

                $insert_id = $this->sms->insert('text_messages', $data);
                $receivers = '';
                $users = $this->sms->get_user_list($this->input->post('role_id'), $this->input->post('receiver_id'));
                foreach ($users as $obj) {
                    $message = get_formatted_body($this->input->post('body'), $this->input->post('role_id'), $obj->user_id);
                    $receivers .= $obj->user_id . ',';
                    if ($obj->phone != '') {
                        $userData = ['role_id' => $this->input->post('role_id'), 'user_id' => $obj->user_id];
                        $this->_send_sms($obj->phone, $message);
                        create_sms_log($message, $obj->phone, 'general', $userData);
                    }
                }
                // update text_messages table 
                $updated = $this->sms->update('text_messages', array('receivers' => $receivers), array('id' => $insert_id));
                if ($updated) {
                    create_log('Has been created a general text message');
                    success($this->lang->line('sms_send_success'));
                    redirect('message/sms');
                } else {
                    error($this->lang->line('sms_send_failed'));
                    redirect('message/sms/add');
                }
            } else {
                $this->data = $_POST;
            }
        }

        $this->data['roles'] = $this->sms->get_list('roles', array('status' => 1), '', '', '', 'id', 'ASC');
        $this->data['add'] = TRUE;
        $this->layout->title($this->lang->line('send') . ' ' . $this->lang->line('sms') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('sms/add', $this->data);
    }

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

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

    public function get_single_sms() {
        $id = $this->input->post('id');
        $this->data['sms'] = $this->sms->get_single_sms($id);
        echo $this->load->view('sms/view', $this->data);
    }

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

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