<?php
header('Content-Type: text/html'); 
include('connection.php');
require "twilio/Services/Twilio.php";
require 'vendors/autoload.php';

// Load our `.env` variables
$dotenv = Dotenv\Dotenv::create(__DIR__);
$dotenv->load();
date_default_timezone_set('America/Los_Angeles');

date_default_timezone_set('US/Eastern');
$new222 = date('Y-m-d H:i:s');
//echo $_SERVER['QUERY_STRING'];
//$ness=gettype($_SERVER['QUERY_STRING']);

//$ness=strlen($_SERVER['QUERY_STRING']);


$json = json_decode(file_get_contents("php://input"), true);
$ccccc=print_r($json);
$record_type = count($json);
$record_type=implode(" ",$json[0]);
$record_type = $json['data']['payload'];
$record_type222 = $json['data']['event_type'];


if($record_type222=='message.received')
{
    



$date_time = date('Y-m-d H:i:s');
//$from= $_REQUEST['from'];
///$body= $_REQUEST['body'];
//$to= $_REQUEST['to'];
//$decoded_jsonto = json_decode($to, true);
//$to=$decoded_jsonto[0][phone_number];



//echo $from;
//echo $body;
//echo $to;
//$decoded_json = json_decode($body, true);
//$body = $decoded_json;
//$jsonData = json_encode($body);

$fromp=$record_type['from'];
//print_r($fromp[phone_number]);
$from=$fromp['phone_number'];
$from1=$from;


$top=$record_type['to'];
//print_r($top[phone_number]);

$to=$top[0]['phone_number'];
$to1=$to;

$bodyp=$record_type['text'];



//$top=$body[to];

//$text=$body[text];
//$newj=$_SERVER['QUERY_STRING'];
//print_r($text);
//$body1= $_REQUEST['meta'];
//$body12= strtolower($_REQUEST['Body']);

$from=substr($from,1);
$to=substr($to,1);
$mediaUrl ='';
$mediaUrl = $_REQUEST['MediaUrl0'];
$body1 = mysqli_real_escape_string($con,$body1);
if($body12 == 'stop' || $body12 == 'Stop')
{
	$query = mysqli_query($con,"insert into tapp_blacklist(number,keyword,datetime) values('".$from."','stop','".$new222."' )");
}
if($body12 == 'start' || $body12 == 'Start')
{
	$query = mysqli_query($con,"delete from tapp_blacklist where number ='".$from."'");
}



  
			    
			    
$sqlrec4 = mysqli_query($con,"insert into tapp_msg_receive (sender,body,date_time,read_status,msg_read,twilio_num,mediaUrl,string) values('".$from."','".$bodyp."','".$new222."','N','0','".$to."','".$mediaUrl."','".$string."'  )");
$sqlrec5 = mysqli_query($con,"insert into table_data (sender,body,date_time,sending_status) values('".$from."','".$bodyp."','".$new222."' ,'R')");
	$query = mysqli_query($con,"select * from tapp_twilio_number  where number like '%".$to."'") ;

  





$get_keyword = mysqli_query($con,"select * from tapp_unsub_keywords")or die(mysqli_error($con));
while($row = mysqli_fetch_array($query) )
	{
	 $sid=$row['twilio_sid'];
	$token=$row['twilio_token'];
	 $service_type=$row['service_type'];

	}
		 	
	$check_blacklist = mysqli_query($con,"select * from tapp_blacklist where number like '%".$from."%'");
	if(mysqli_num_rows($check_blacklist)<1)

	{
while($rowdata = mysqli_fetch_array($get_keyword))
{

if (strpos($body12, strtolower($rowdata['keyword'])) !== false) {
    $message = $rowdata['message'];
	$AccountSid = $sid;

 $AuthToken = $token;
$num=$from;

$twilio_number=$to;

 $mes=$body1;



$message= mysqli_real_escape_string($con, stripslashes($message));
$msg=$message;
 $num1='+'.$num;
$client = new Services_Twilio(getenv('sid'), getenv('token'));

// $mediaUrl ='';

	try
	{
		$sms = $client->account->messages->sendMessage($twilio_number,$num1,$msg);

		 $sms->sid;
		$sql1 = mysqli_query($con,"INSERT INTO tapp_sent_msg_log(sms_number,twilio_num,message,images,bulk_name,date_time) VALUES ('".$num."','".$twilio_number."','".$message."','".$mediaUrl."','".$unique_id."',now())");
		$sqlrec5 = mysqli_query($con,"insert into table_data (sender,body,date_time,sending_status) values('".$num."','".$msg."',now(),'S')");
		$_SESSION['flash_message'] = 'Message has been sent to '.$num1;
	}
	catch (Exception $e)
	{
	 $e->getMessage();
		$sql1 = mysqli_query($con,"INSERT INTO tapp_sent_msg_failed(sms_number,twilio_num,message,images,'bulk_name',date_time) VALUES ('".$num."','".$twilio_number."','".$message."','".$mediaUrl."','".$unique_id."',now())");
$_SESSION['failure_message'] = "Sorry! SMS couldn't sent to ".$num1;
	}
}	
}

	}
	
	}
	
	if(isset($_REQUEST['MediaUrl0']))

{
    
    ?>
    <Response>
    <Message to="+18042779410"><Body> <?=htmlspecialchars(substr($_REQUEST['From'] . ": " . $_REQUEST['Body'], 0, 1600))?></Body><Media><?=$_REQUEST['MediaUrl0']?> </Media></Message>
</Response>
    <?php 
    
}
else
{?>
 <Response>
    <Message to="+18042779410"> <?=htmlspecialchars(substr($_REQUEST['From'] . ": " . $_REQUEST['Body'], 0, 1600))?> </Message>
</Response>

    <?php 
}?>



