<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
	#	Twilio SMS module for Sendroid Ultimate
	#	location: smsapi/twilio/index.php
	#	Developed by: Ynet Interactive
	#	Special thanks: Mr. White
*/
global $LANG;
global $configverssion_id;
global $configapp_version;
global $server;
require_once __DIR__ .'/Twilio.php';

$message_id = $THIS_MESSAGE_ID;
$userID = singleMessageData($THIS_MESSAGE_ID,'customer_id');
$resellerID = userData($userID,'reseller');
$gateway_id = $THIS_MESSAGE_GATEWAY;

$customer_id = singleMessageData($THIS_MESSAGE_ID,'customer_id');
$to = singleMessageData($THIS_MESSAGE_ID,'recipient');
$message = singleMessageData($THIS_MESSAGE_ID,'message');
$type = singleMessageData($THIS_MESSAGE_ID,'type');
$duration = singleMessageData($THIS_MESSAGE_ID,'duration');
$country = singleMessageData($THIS_MESSAGE_ID,'country_id');
$pageCount = countPage($message,$type,$duration);
$cost = smsCost($to,$type,$country,$pageCount,$customer_id);
$cost = smsCost($to,$type,$country,$pageCount,$customer_id,$gateway_id);
		
$AccountSid = smsGatewayData($gateway_id,'username'); 
$AuthToken = smsGatewayData($gateway_id,'password'); 
$version = "2010-04-01"; // Twilio REST API version
$client = new Services_Twilio($AccountSid, $AuthToken); //initialise the Twilio client
try{
	if($mms > 0) {
		$message = $client->account->messages->create(array( 
			'To' => '+'.singleMessageData($THIS_MESSAGE_ID,'recipient'), 
			'From' => singleMessageData($THIS_MESSAGE_ID,'sender_id'), 
			'Body' => singleMessageData($THIS_MESSAGE_ID,'message'), 
			'MediaUrl' => singleMessageData($THIS_MESSAGE_ID,'media'),  
		));
	} else {
		$message = $client->account->messages->create(array( 
			'To' => '+'.singleMessageData($THIS_MESSAGE_ID,'recipient'), 
			'From' => singleMessageData($THIS_MESSAGE_ID,'sender_id'), 
			'Body' => singleMessageData($THIS_MESSAGE_ID,'message'), 
		));	
	}
	$response = 'sent';
	//Update message status etc
	mysqli_query($server, "UPDATE  `messagedetails` SET `status` = 'sent' WHERE `id` = '$message_id'");
	mysqli_query($server, "UPDATE  `messagedetails` SET `cost` = '$cost' WHERE `id` = '$message_id'");	
	mysqli_query($server, "UPDATE  `messagedetails` SET `dlr` = 'sent' WHERE `id` = '$message_id'");	
}
catch (Services_Twilio_RestException $e) {
	$response =  $e->getMessage();
	$response = mysqli_real_escape_string($server,$response);
	mysqli_query($server, "UPDATE  `messagedetails` SET `status` = 'failed' WHERE `id` = '$message_id'");
	mysqli_query($server, "UPDATE  `messagedetails` SET `cost` = '0' WHERE `id` = '$message_id'");	
	mysqli_query($server, "UPDATE  `messagedetails` SET `dlr` = 'failed' WHERE `id` = '$message_id'");	
	mysqli_query($server, "UPDATE  `messagedetails` SET `notice` = '$response' WHERE `id` = '$message_id'");
} 

?>