<?php
########################################################
##
## whh 2019.11.19 added select phonenum or manual entry phonenum
## whh 2019.11.19 add save a message under filename phonenum.txt
## whh 2019.11.20 credentials hidden
## whh 2019.11.21 added json data file for clients
## whh 2019.12.11 cleaned up echo to HTML message window and comments
## whh 2019.12.15 add source phone number as slelected from webpage and formSubmit.js
## whh 2019.12.24 update from variables transfer from non contact from and conact messages
## whh 2019.12.27
## whh 2019.12.31 added change read in SMSmessages.json to yes whenever sending a new message for that contact
## whh 2020.01.05 cleaned up the message sent window text and format
## whh 2020.01.28 clean up variable no longer used and add checks for posting
## whh 2020.03.05 commented out all the echo to screen
## whh 2020.10.22 initialize array $clientObj
## whh 2020.10.22 move filenaming assigning to top of code
## whh 2021.08.14 added rtrim phoneNumber cleanup to solve issue with number pad phoning adding 6 spaces to the end of source phone number
##
########################################################
# make sure you are logged in to run this
########################################################
session_start();
$login_in = $_SESSION['logged_in'];

// echo $_SERVER["REMOTE_ADDR"];

// echo "session_start: " . $login_in . "<br>";

if (!$login_in) {
    die ('You do not have permission to access this page. Please login');
}
########################################################

$version = "<strong style='font-size:8px; color:grey;'> Build: 2020.03.05</strong>" . "<br>";
echo $version;
########################################################
// echo "<center><strong style='font-size:16px; color:black;'>JUST SENT</strong></center>" ;

########################################################
# DIDWW SMS send a message code
########################################################
# echo "<strong>Sending Information:</strong><br>" ;
########################################################
require_once 'junk/test.foo';
date_default_timezone_set("America/Toronto");
$dateTime = date("l, d-M-y H:i:s T");


########################################################
# Set filenames for messahes
########################################################

$allClientsfile = "data/SMSmessagesSent.json"; //Sent Messages JSON file
$allinSMS = "data/SMSmessages.json"; //Received Messages JSON file

########################################################
# GET data from index.php
########################################################

// if the clientId from the selected picj field is empty set it to unknown
if(isset($_POST['selected'])) {
    // echo $_POST['selected'] . "<br>";
    $selectedContact = $_POST['selected'];
              } else { $selectedContact= "unknown"; }

// if the phone number was selected from the selected picj field is empty set it to unknown
if(isset($_POST['selectedPhone'])) {
    //echo $_POST['selectedPhone'] . " - A phone number was selected" . "<br>";
    $selectedPhone = $_POST['selectedPhone'];
              } else { $selectedPhone = "unknown"; }


// this is if the number pad was used to enter a phone numer to send to
if(!empty($_POST['recipient'])) {
    //echo $_POST['recipient'] . " - A phone number was entered" . "<br>";
    $phonenumentered = $_POST['recipient'];
              } else { $phonenumentered = "unknown"; }


         $message = $_POST['message'];

    // these are built by scrapping from the top of the page phonenumber in formSubmit.js
    $destination = $_POST['destination']; // contact it is being send to
    $phonesNumber = $_POST['phonesNumber']; // Phone Number being sent from


          // $source = $_POST['source']; // not used
       $firstName = $_POST['firstName'];
        $lastName = $_POST['lastName'];
           $debug = false;



//echo "selectedContact: " . $selectedContact . "<br>";
//echo "selectedPhone: " . $selectedPhone. "<br>";
echo "phonenumentered source: " . $phonenumentered . "<br>"; // one off message value entered
//echo "message: " . $message . "<br>";
echo "destination source: " . $destination . "<br>"; // answering an SMS thread
echo "phonesNumber source: " . $phonesNumber . "<br>"; // answering an SMS thread, one off message
//echo "firstName: " . $firstName . "<br>";
//echo "lastName: " . $lastName . "<br>";
// echo "source " . $source . "<br>";
//echo "dateTime: " . $dateTime . "<br>";


########################################################
# we have all the data from the sned page now do stuff
########################################################




$firstName = strtoupper($firstName);
$lastName = strtoupper($lastName);


$clientId = $lastName . "_" . $firstName;
//echo "<strong>Contact: </strong>" . $clientId . "<br>";


//No longer needed to send to a new contact
# Decide which to use, from list or entered phone number
if ($phonenumentered !== "unknown") {
  // Add Number is being used for a one off
        $destination = $phonenumentered;

    } else {
      // responding to an exiting message
      $destination = $destination;
  };


$phonesNumber = slug($phonesNumber);
$destination = slug($destination);
echo "destination cleansed: " . $destination . "<br>";

// function removes all none asci charateris from a phoneNumber and destinnation string
  function slug($number){
      $number = strtolower($number);
      $number = preg_replace('/[^a-z0-9 -]+/', '', $number);
      $number = str_replace('-', '', $number);
      $number = ltrim($number, " "); // remove leading blank space
      $number = rtrim($number, " "); // remove trailing blank space
      return trim($number, '-');
  }



// echo "<strong>Phones Number: </strong> " . $phonesNumber . "<br><strong>To: </strong>" . $destination . "<br>";


// echo "<strong>Debug set to:</strong> " . $debug . "<br><br>";


// *****************************************************************************
// *****************************************************************************
########################################################
#  x - DID
########################################################

// echo "URI: " . $sms_trunk_uri . "<br>";
// echo "NAME: " . $sms_trunk_login . "<br>";
// echo "PASS: " . $sms_trunk_pass . "<br>";

$sms_message = [
"destination" => $destination,
"source" => $phonesNumber,
"content" => $message
];


$postdata = json_encode(
[
"data" => [
"type" => "outbound_messages",
"attributes" => $sms_message
]
]
);

//echo "postdata: " . $postdata . "<br>" ;
//echo "<br>";
//var_dump($postdata);

$credentials = sprintf('Authorization: Basic %s',
base64_encode("$sms_trunk_login:$sms_trunk_pass") );

$opts = array('http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/vnd.api+json\r\n".
"Accept: 'application/vnd.api+json\r\n".
$credentials,
'content' => $postdata
)
);
//echo "<br><br> opts: " ;
//print_r($opts);
//echo "<br><br>";
//var_dump($opts);

// send SMS !!!!!!!!! send SMS !!!!!!!!!send SMS !!!!!!!!!send SMS !!!!!!!!!send SMS !!!!!!!!!send SMS !!!!!!!!!
// send SMS !!!!!!!!! send SMS !!!!!!!!!send SMS !!!!!!!!!send SMS !!!!!!!!!send SMS !!!!!!!!!send SMS !!!!!!!!!
// send SMS !!!!!!!!! send SMS !!!!!!!!!send SMS !!!!!!!!!send SMS !!!!!!!!!send SMS !!!!!!!!!send SMS !!!!!!!!!

$context = stream_context_create($opts); // TURN SENDING BACK ON UNCOMMENT !!!!!!!

// TURN SENDING BACK ON UNCOMMENT !!!!!!! TURN SENDING BACK ON UNCOMMENT !!!!!!! TURN SENDING BACK ON UNCOMMENT
// TURN SENDING BACK ON UNCOMMENT !!!!!!! TURN SENDING BACK ON UNCOMMENT !!!!!!! TURN SENDING BACK ON UNCOMMENT // TURN SENDING BACK ON UNCOMMENT !!!!!!! TURN SENDING BACK ON UNCOMMENT !!!!!!! TURN SENDING BACK ON UNCOMMENT
// TURN SENDING BACK ON UNCOMMENT !!!!!!! TURN SENDING BACK ON UNCOMMENT !!!!!!! TURN SENDING BACK ON UNCOMMENT


//echo "<br> <br> Content: " ;
//print_r($context);
//echo "<br>";
//var_dump($context);

// receive fail or success displayed in message on HTNL page
$result = file_get_contents($sms_trunk_uri, false, $context);
// echo "<strong>Result: </strong>" ;
// var_dump($result);

$resultText = $result ? 'Sent' : 'Failed'; // set variable to value based on the boolean content true : False

echo "<strong>DIDWW Response: </strong>" . $resultText . "<br>";

//echo "<br> -SENT- " ;
// *****************************************************************************
// *****************************************************************************


########################################################
## Add Messages to the JSON FILE
########################################################
//echo "selectedContact: " . $selectedContact . "<br>";
//echo "selectedPhone: " . $selectedPhone. "<br>";
//echo "phonenumentered: " . $phonenumentered . "<br>"; // one off message value entered
echo "Message: " . $message . "<br>";
echo "Destination: " . $destination . "<br>"; // answering an SMS thread
echo "PhonesNumber: " . $phonesNumber . "<br>"; // answering an SMS thread, one off message
//echo "firstName: " . $firstName . "<br>";
//echo "lastName: " . $lastName . "<br>";
//echo "source " . $source . "<br>";
echo "DateTime: " . $dateTime . "<br>";
echo "ClientId:  " . $clientId;


    // Use variables from _GET - build Object array to add to data/SMSmessage.json
    //initialize the array
  $clientObj = new stdClass;

        $clientObj->clientId = $clientId;
        $clientObj->number = $phonesNumber;
        $clientObj->messagein = $message;
        $clientObj->dateTime = $dateTime;
        $clientObj->recipient = $destination;
        $clientObj->localdateTime = $dateTime;
        $clientObj->result = $resultText;

        $clientJSON = json_encode($clientObj); // Convert object array data from Array Form to JSON data

//echo "<br><strong>Message: </strong>" . $message . "<br> <br>";

########################################################
## get the all the existing client data from JSON file and convert to an array
########################################################


        $jsondata = file_get_contents($allClientsfile); //Get data from existing JSON file
//echo "jsondata " . $jsondata ."<br> <br>";
        $arr_data = json_decode($jsondata, true); // converts existing JSON data into an Array
//print_r($arr_data); //Print array data to screen for debugging
        array_push($arr_data,$clientObj); // Push new client data to array
//echo "<br> <br>arr_data plus new client: <br> <br>";
//print_r($arr_data);
        $jsondataNew = json_encode($arr_data, JSON_PRETTY_PRINT); //Convert updated array to JSON
//echo "<br> <br> jsondataNew: " . $jsondataNew ."<br> <br>";
        file_put_contents($allClientsfile, $jsondataNew); //write updated json data into data/contacts.json file

//============================================================================================
// Save the SMS message to a file with filename by phonenumber
//============================================================================================

//Builds the content of the client log for the Client View Window
    // data/phonenumber.txt - Creates file for client log if it does not exist
      // Builds the log file contents and adds to exiting data or creates it for the first time
        $ip1 = "<br>" . "Sent To: " . $destination . "<br>" . "SMS Message: " . $message . "<br><br>" . "DIDWW Response: " . $resultText . "<br><br>";
        $ip2 = $ip1 . "Date-Time Sent: " . date("l, d-M-y H:i:s T");
        $ip3 = $ip2 ."<br> From: " . $phonesNumber ."<hr>";
//echo "<br>". "-LOGGED AS-: " . $ip3;
        $datei2 = fopen("data/". $phonesNumber . ".txt","a") or die("Cannot open file:" . "data/" . $phonesNumber. ".txt"); //implicitly creates file if it doesn't exist
        fwrite($datei2, $ip3);
        fclose($datei2);



// *****************************************************************************
// mark all messages with sending/replying $clientId as read in SMSmessage.json file
// *****************************************************************************

    ########################################################
    ## get the all the existing client data from JSON file and convert to an array
    ########################################################
        $read = "yes"; // If you are sending a reply you have read messages for that person

        $jsondata = file_get_contents($allinSMS ); //Get data from existing JSON file
// echo "jsondata " . $jsondata ."<br> <br>";
        $arr_data = json_decode($jsondata, true); // converts existing JSON data into an Array
// print_r($arr_data); //Print array data to screen for debugging

            foreach ($arr_data as $key1 => $value1) {
                    // test if clientId exists then walk through data
                    $recipient = $arr_data[$key1]["number"];
                  if($arr_data[$key1]["number"] == $destination) {
            //echo "Read before: " . $arr_data[$key1]["read"]  . "<br>";
                    // change read to yes if no
                      if($arr_data[$key1]["read"] !== $read) {
                         $arr_data[$key1]["read"] = $read;
                       };
            //echo "Read after: " . $arr_data[$key1]["read"] . "<br>";
                  } // If client change read to yes
                } // foreach Value

// print_r($arr_data);
        $jsondataNew = json_encode($arr_data, JSON_PRETTY_PRINT); //Convert updated array to JSON
// echo "<br> <br> jsondataNew: " . $jsondataNew ."<br> <br>";
        file_put_contents($allinSMS , $jsondataNew); //write updated json data into data/SMSmessages.json file
// echo "dist & recip: " . $destination . $recipient . "<br>";
//echo $clientId . " - All Recieved Message set to read: yes <br>";

//echo $version ;
?>
