<?php

/* 
 * Author       : Jai K
 * Purpose      : Model for Sending SMS
 * Created On   : 2016-10-18 10:54
 */

class SMS_Model extends CI_Model {
    
    function __construct() {
        parent::__construct();
    }
    
    function get($tbl_name, $args = array()) {
        $is_where = TRUE;
        if( !empty($args['order_by']) ) :
            $this->db->order_by($args['order_by']);
            $is_where = FALSE;
        endif;
        
        $where = !empty($args['where']) ? $args['where'] : ( $is_where ? $args : array() );
        
        if( empty($where['self.status']) ) :
            $where['self.status'] = 1;
        endif;
        
        $q = $this->db->get_where($tbl_name.' AS self', $where);
        return $q->result_array();
        
    }
    
    function get_contacts() {
        $post = $this->input->post();
        
        //echo "<pre>Data: "; print_r($post); die;
        
        //$ids = explode(',', $post['value']);
        $ids = str_replace(',', '|', $post['value']);
        
        if( !empty( $ids ) ) :
            $w = 'CONCAT(",",`bd_sms_types`,",") REGEXP ",('.$ids.'),"';
            $this->db->where($w);
        endif;
        
        // Limit
        if( !empty( $post['from'] ) ) :
            
            
        endif; 
        
        
        $this->db->select('id, bd_contact_no, bd_name');
        $this->db->order_by('bd_contact_no ASC');
        $q= $this->db->get_where( TBL_BD, array('status' => 1) );
        //echo "Query:".$this->db->last_query(); die;
        return $q->result_array();
    }
    
    function send_sms() {
        $return = array();
        $post = $this->input->post();
        $status = $message = '';

        if( empty( $post['nos'] ) )  :
                $status = 'error';
                $msg = 'None of the contact no\'s are given to sent!';
        elseif( empty( $post['msg'] ) )  :
                $status = 'error';
                $msg = 'Message can not be empty!';
        else :
                // Send SMS
                $sms_to = '';
                //$sms_to = implode(',', $post['nos']); 
                foreach( $post['nos'] as $k => $no ) :
                        $sms_to  .= MOB_PREFIX . $no . ',';
                endforeach;

                $sms_to = substr( $sms_to, 0, -1);

                //$sms_msg = $post['msg'];//"For SSBEC IB Login : Use ".$mem_otp." (IB OTP) to login into your SSBEC Online account. Sent on ".date('d M H:i');

                $return = send_sms($sms_to, $post['msg']);

                $return['status'] = $status;
                $return['msg'] = $msg;

        endif;

        return $return;
    }
    
}
