<?php

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
	exit;
}

require 'vendor/autoload.php';

use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumber;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberUtil;

use Aws\Sns\SnsClient; 
use Aws\Exception\AwsException;
use Aws\Credentials\Credentials;


$credentials = new Credentials('AKIAZM7JX5FWJCK2HMNI', 'loeDIJqhn7WeYMR6hanqnaUEpR8KOg52C7lDv/08');

$SnSclient = new SnsClient([
    'region' => 'us-east-1',
    'version' => '2010-03-31',
    'credentials' => $credentials
]);

$phoneUtil = PhoneNumberUtil::getInstance();

if(isset($_POST["msg"])){
	$message = $_POST["msg"];
}

if(isset($_POST["contacts"])){
	$contacts = json_decode($_POST["contacts"]);
}
 

for ($i = 0; $i < count($contacts); $i++) {
	try {
		$numberString = $contacts[$i];
	    $numberPrototype = $phoneUtil->parse($numberString, "US");
	    $phone_e164 = $phoneUtil->format($numberPrototype, PhoneNumberFormat::E164);
	    try {
    		$result = $SnSclient->publish([
	        	'Message' => $message,
	        	'PhoneNumber' => $phone_e164,
    		]);
		    // var_dump($result);
		} catch (AwsException $e) {
		    // output error message if fails
		    error_log($e->getMessage());
		}
	} catch (NumberParseException $e) {
    	// number is not US
    	error_log($e,3,"debug/postdata.txt");
	}
}

ob_start();
var_dump($_POST);
$output = ob_get_clean();
error_log(date('c')." PHP: ".$_SERVER["PHP_SELF"].": ".$output."\n", 3, "debug/postdata.txt");
?>