<?php


########################################################
## whh 2019.12.07 make variables match DIDWW
## whh 2019.12.11 clean up the code and comment out not needed echo statements
## whh 2020.02.21 added email notification
## whh 2020.02.28 switch to decode message for email
## whh 2020.03.02 add email notification recipient to data file
## whh 2020.10.16 test to make sure array is bigger then read before rewriting it to JSON file
## whh 2020.10.16 incoming log by sender
## whh 2020.10.22 initialize array $clientObj
## whh 2020.12.10 clean up error log for failed message and test empty message does not create null mesage file
## whh 2022.04.23 add error checking to resolve corrutped SMSmesage.json file and gotos to death for errors
## whh 2022.04.23 clean up system date Format test function validateJSON test json.php
## wgg 2022.04.23 house cleaning an comments statements
## whh 2022.05.04 set system date back older date Format
## whh 2022.10.17 fix annd json_encode statement to just variable and , JSON_PRETTY_PRINT (except the first one for DIDWW credentials)
## whh 2022.10.17 add require once 'testjso.php' statement to make funstion  validateJSON available

##
########################################################
##
## After the message is received and forwarded to get.php, the message will appear in data/SMSmessage.json.
## Then and email will be sent to advise a new SMS has arrived
## switch to decode message for email
##
echo "Start Get <br>";


########################################################
# GET local data
########################################################

date_default_timezone_set("America/Toronto");
## $localdateTime = date("D, d-M-Y H:i:s T");
$localdateTime = date("l, d-M-y H:i:s T");


$version = " - <strong>get.php Build Date: </strong> 2022.04.23 <br><br>";
##########################################################
## generate entries of time that this PHP is run
## error_reporting(0);
## opens data/SMSmessageRUNlog.txt to add date time of access last access of get.php

        $logentry = "Local Time: " . $localdateTime . " - Version: " . $version;
        $datej = fopen("data/SMSmessageRUN.log","a");
        fwrite($datej, "\n" . $logentry);
        fclose($datej);
##########################################################

echo "<center><strong style='font-size:24px; color:grey;'>View Messages Incoming Run: </strong>" . $localdateTime . "</center><br>" ;

########################################################
## This retieves the data from the DIDWW URL to run get.php
########################################################

// blocks viewing data except by the php GET data command
if ($_SERVER['REQUEST_METHOD']!='GET')
{
 echo 'This script is not supposed to be viewed in a browser!';
   Goto death;
}


########################################################
## NOTES NOTES NOTES NOTES NOTES NOTES NOTES NOTES NOTES
## NOTES NOTES NOTES NOTES NOTES NOTES NOTES NOTES NOTES
########################################################
/*
Default HTTP Port 80 and HTTPS Port 443

1xx informational response – the request was received, continuing process
2xx successful – the request was successfully received, understood and accepted
3xx redirection – further action needs to be taken in order to complete the request
4xx client error – the request contains bad syntax or cannot be fulfilled
5xx server error – the server failed to fulfill an apparently valid request

Actual Message from DIDWW
  46.19.209.213 - - [07/Dec/2019:21:42:45 -0600] "GET 'URL'/get.php?text=dGVzdCA%3D&source=16132875415&destination=16132875415&time=Sun%2C%2008%20Dec%202019%2003%3A42%3A45%20GMT HTTP/1.0" 200 11856 "-" "sms sender"
*/

## Read in the data from DIDWW's URL striing
$time = $_GET['time'];
$recipient = $_GET['destination'];
$message = $_GET['text'];
$sender = $_GET['source'];

## write to log file data/Get_RUN.log what was recieved from DIDWW
$logentry2 = " Local Time:" . $localdateTime . " SMSTime:" . $time . " Recipient:" . $recipient . " Message:" . $message . " Sender:" . $sender;
$datej = fopen("data/Get_RUN.log","a");
fwrite($datej, "\n" .$logentry2);
fclose($datej);

## functions and info externnal to this file
require_once 'junk/what.foo';
require_once 'testjson.php';

## test data
//$time = $localdateTime;
//$recipient = "1111231231234";
//$message = base64_encode("This is a test of decodeing php encoded text");
//$sender = "16666661234";


// Decode the text message
$text = base64_decode($message);

//Write new message to log file data/log/incoming$sender.log
$incoming = "Time received: " . $time . " -From: " . $sender . " -To: " . $recipient . " -Message: " . $text . "<br>" . "\n";
$filename = fopen("data/log/". "incoming_" . $sender . ".log","a") or die("Cannot open file:" . "data/log/" . "incoming" . $sender. ".log"); //implicitly creates file if it doesn't exist
fwrite($filename, $incoming);
fclose($filename);

########################################################
## Add Messages to the JSON FILE
########################################################

$read = "no"; // since all messages arriving are new so set read to no

$clientId = "incoming";
    // Use variables from _GET - build Object array to add to data/SMSmessage.json

    //initialize the array
  $clientObj = new stdClass;

        $clientObj->clientId = $clientId;
        $clientObj->number = $sender;
        $clientObj->encoded_message = $message;
        $clientObj->message = $text;
        $clientObj->dateTime = $time;
        $clientObj->recipient = $recipient;
        $clientObj->localdateTime = $localdateTime;
        $clientObj->read = $read;


########################################################
## Testing for new message to see if it has valid database
########################################################
        // convert new message array to a json format and test to see if it is valid
        $clientJSON = json_encode($clientObj, JSON_PRETTY_PRINT); // Convert object array data from Array Form to JSON data

        // call function validateJSON passing newly created message to see if it is valid json string
        if (validateJSON($clientJSON)) {
          $newMessageTest = "true";
        } else {
          $newMessageTest = "false";
        }

        if ($newMessageTest === "false") {
          echo "New message did not convert to a valid json object";
          goto death;
        }




########################################################
## get the all the existing incoming messages from SMSmessages.json and convert to an array
## add the latest message to the array and convert back to JSON and save in SMSmessages.json
## create or append to a text file in data/log/incoming$sender.log
########################################################

        $allClientsfile = "data/SMSmessages.json"; //Get existing JSON file
// read file
        $SMSmessages = fopen($allClientsfile,"r") or die("Cannot open file:"); //implicitly creates file if it doesn't exist
        $jsondata = fread($SMSmessages, filesize($allClientsfile));
        fclose($SMSmessages);

// call function validateJSON passing all messages to see if they are valid json strings
        if (validateJSON($jsondata)) {
          $allMessageTest = "true";
        } else {
          $allMessageTest = "false";
        }


echo  "allMessageTest: " . $allMessageTest ."<br> <br>";

// If the messages read from the file are not valid to to end and die
        if ($allMessageTest === "false") {
          echo "All message did not convert to a valid json object";
          Goto death;
        }


 // converts read JSON file data into an Array to add new message
        $arr_data = json_decode($jsondata, true);

// print_r($arr_data); //Print array data to screen for debugging

##################################################################
## Test the size of the array before and after adding new messages
## If  the size is not equal to or greater show error and die before writing to file
##################################################################
    $testsize1 = sizeof($arr_data);

echo  "Size of Array read from file:" . $testsize1 ."<br> <br>";

// Adds new messages to the array
        array_push($arr_data, $clientObj); // Push new client data to array

    $testsize2 = sizeof($arr_data);

echo  "Size of Array new message add :" . $testsize2 ."<br> <br>";

            ##################################################################
            ## test to make sure new array is bigger than the old array
            ## before converting to json and overwritting file
            ## if there new is smaller then die
            ##################################################################

                  If ($testsize2 < $testsize1 || $testsize1 < 1 || $testsize2 < 1) {
                  //Write to log file data/log/incoming$sender.log
                      $incoming_error = "Read Arraysize: " . $testsize1 . " - Write Arraysize: " . $testsize2 . "<br>" . "\n";
                      $filename = fopen("data/log/error_". "incoming_" . $sender . ".log","a") or die("Cannot open file:"); //implicitly creates file if it doesn't exist
                      fwrite($filename, $incoming_error);
                      fclose($filename);
                      echo " Data Error Failed ";
                    Goto death;
                  }


##################################################################
## Fianlly write the new json file to SMSmessages
## overwriting the entire file with the al and new message
##################################################################

// label for 5 attempts to write the file successfully
redoWrite:

//print_r($arr_data);

//Convert updated array to JSON
    $jsondataNew = json_encode($arr_data, JSON_PRETTY_PRINT);

        $NEWmessages = fopen($allClientsfile,"w") or die("Cannot open file line 68:" );
        fwrite($NEWmessages, $jsondataNew); //write updated json data into data/SMSmessages.json file
        fclose($NEWmessages);

            ##################################################################
            ## test to see if write & close failed and file is empty
            ##################################################################
                  if (filesize($allClientsfile) == 0){
                    echo "The file is empty <br>";
                    $t = $t + 1;
                  goto redoWrite;

                    // set counter so it only triwa 5 timwa then fails
                        if ($t = 5){
                            echo " 5 tries and file is DEFINITELY empty <br>";
                            goto death;
                          }
                }

echo " Data File Written <br>";


####################################################################################
## Build an email from the received SMS message and notify email Recipients
####################################################################################
// Set the recipient email address.
// FIXME: Update this to your desired email address.

// Sent notification of new SMS to this address
// Sent notification of new SMS to this address
$email_recipient = "com@polarbeast.ca";

// Set the email subject.
$subject = "SMS: $sender";

// Build the email content.
$email_content = '
<html>
<head>
  <title>SMS from '. $sender .'</title>
</head>
<body>
  <table class="table">
        <tr>
          <th align="right">SMS from: </th>
          <td align="left">'. $sender.'</td>
        </tr>
        <tr>
          <th align="right">SMS to: </th>
          <td align="left">'. $recipient.'</td>
        </tr>
        <tr>
          <th align="right">Message: </th>
          <td align="left">'. $text.'</td>
        </tr>
        <tr>
          <th align="right">Local Time:</th>
          <td align="left">'. $localdateTime .'</td>
        </tr>
    </table>
</body>
</html>
';

  // Build the email headers.
$email_headers  = 'MIME-Version: 1.0' . "\r\n";
$email_headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$email_headers .= "From: $sender ";

// Send the email.
if (mail($email_recipient, $subject, $email_content, $email_headers)) {
    // Set a 200 (okay) response code.
    http_response_code(200);
    echo "Successful Delivery Captain!";
} else {
    // Set a 500 (internal server error) response code.
    http_response_code(500);
    echo "Oh Shit! Something's horribly wrong.";
};

##############
## End of notification email email section
##############

/*
if ($insert_sms_success)
{
  // if we have succeeded to insert sms into the database
  echo "-DONE " ;
  echo $version ;
}
else
{
  // if we have failed to write to JSON file
  // Here you can do something.
  // For example, let DIDWW know an error has occured send
  http_response_code(500);
}
*/

exit ("<br><br> All done Get");

death:
echo "Oops! Something went wrong.";

end:
?>
