<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Comms extends CI_Controller {

	public function __construct()
	{
		parent::__construct(); 
		$this->load->model('msgmodel');
		$this->load->library('email');
        $config['charset'] = 'iso-8859-1';
        $config['wordwrap'] = TRUE;
		$config['mailtype'] = 'html'; 
		$config['newline'] ='\r\n';
		$config['clrf'] ='\r\n';
		$config['protocol'] = 'smtp';
		
		$config['smtp_host'] = 'mail.mzawadi.com';
		$config['smtp_port'] = 587;
		$config['smtp_user'] ='kblloyalty@mzawadi.com';
		$config['smtp_pass'] ='Kbl_2018';

        $this->email->initialize($config);
	}

    public function index(){
        show_404();
	}

	function comm($user,$code){
		set_time_limit(0);
		$user = base64_decode(urldecode($user));
		$code = base64_decode(urldecode($code));
		$msgs = $this->msgmodel->get(array('code'=>$code));
		foreach($msgs->result_array() as $msg){
			if(strtolower($msg['type']) == strtolower("email")){
				$this->msgmodel->update(array('deliverydescription'=> 'Sent'),array('code'=>$code));
				$this->email->to($msg['destination']);
				$this->email->subject($msg['subject']);
				$this->email->from(MAIL_FROM);
				$this->email->message(  $msg['message'] );
				// $this->email->send();
			} else {
				$comms['message']  = trim($msg['message']);
				if(SMS_LIVE){
					//38610706;Success;254726770792;1
					$smsResponse = $this->sendSMS($msg['destination'],$msg['message']);
					if(!empty($smsResponse)){
						$resp = explode(";",$smsResponse);
						$comms = array('MessageId'=> $resp[0], 'RequestStatus'=> $resp[1]);
						$this->msgmodel->update($comms,array('code'=>$code));
					}
				}
			}
		}
	}

	function sendSMS($mobile, $message){
		$smsdata = array(
			"username" => "mzawadi",
			"password" => base64_encode(md5("naftal1984")),
			"pass_type" => "bm5",
			"shortcode" => "INFOTEXT",
			"mobile" => $mobile,
			"message" => $message,
		);
		$smsdata_string = json_encode($smsdata);
		$smsURL = "https://api.africastalking.com/version1/messaging"; 
		//$smsURL = "https://api.tililsms.com/sms/v3/sendsms";
		//POST 

		//-H 'Content-Type: application/x-www-form-urlencoded' \
		//-H 'apiKey: MyAppApiKey' \

		$ch = curl_init($smsURL);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, "username=daguindd&to=".$mobile."&message=".urlencode($message)."&from=ARI");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/x-www-form-urlencoded',
			'apiKey: 13a9b79e150ba39e28483b9ea8331179902a516125e39267b077188ff7c7f097')
		);

		$apiresult = curl_exec($ch);
		/*if (!$apiresult) {
			die("ERROR on  | error[" . curl_error($ch) . "] | error code[" . curl_errno($ch) . "]\n");
		}*/
		curl_close($ch);
		return $apiresult;
	}

}
