<?php
########################################################
##
## whh 2019.11.22
## whh 2020.01.12 remove forced capitals for clientId
## whh 2020.01.22 fix editing and php warnings after updating to v7 on osx
## whh 2020.01,22 add jScipt reloading of form select fields so no refresh is required
##                 all fields are cleared in formSubmit.js before getting here
## whh 2020.01.24  adding encryption for json data
## whh 2020.02.20 data encryption removed directory limited to PHP access
## whh 2020.02.22 fixed DELETE created clientId from lastName and firstName to find in contact.json
## whh 2020.03.05 commented out at all the echo to screen
## whh 2022.10.17 fix annd json_encode statement to just variable and , JSON_PRETTY_PRINT (except the first one for DIDWW credentials)
##
########################################################
# make sure you are logged in to run this
########################################################
// $logged_in = false;
session_start();
$login_in = $_SESSION['logged_in'];

// 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:10px; color:grey;'> CONTACTS.PHP Build: 2020.03.05</strong>";
echo $version;
########################################################

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

########################################################
# GET data from index.html
########################################################

       $contactId = $_POST['selected'];
        $phonenum = $_POST['recipient'];
         // $message = $_POST['message'];
     // $destination = $_POST['destination'];
    $phonesNumber = $_POST['phonesNumber'];
          // $source = $_POST['source'];
        $lastName = $_POST['lastName'];
       $firstName = $_POST['firstName'];
            $email = $_POST['email'];
           $notes = $_POST['notes'];
            $type = $_POST['type'];
   $contactDelete = $_POST['contactDelete'];

           $debug = true;

$clientId = $contactId; // lastName_firstName: phone Number

// build initials for contact
$firstInitial = substr($firstName,0,1);
$lastInitial = substr($lastName,0,1);
$firstInitial = strtoupper($firstInitial);
$lastInitial = strtoupper($lastInitial);
$initials = $firstInitial . $lastInitial;
//$firstName = strtoupper($firstName);
//$lastName = strtoupper($lastName);
//$clientId = strtoupper($clientId);
// $type = strtoupper($type);
// $contactDelete = strtoupper($contactDelete);


// encrypting functions just call and pass text and key
// encrypting functions just call and pass text and key

// $scrambledNumber = cryptoJsAesEncrypt($keyStuff, $phonesNumber); // encryption




//echo "<br>Encrypted Phone Number: " . $scrambledNumber . "<BR>";

//echo "<br>clientId: " . $clientId . "<BR>";
//echo " phonenum: " . $phonenum . "<BR>";
//echo " lastName: " . $lastName . "<BR>";
//echo " firstName: " . $firstName . "<BR>";
//echo " type: " . $type . "<BR>";
//echo " mail: " . $mail . "<BR>";
//echo " notes: " . $notes. "<BR>";
//echo " contactDelete:  " . $contactDelete  . "<BR>";

$clientIdNew = $lastName . "_" . $firstName . ": " . $phonenum;

//echo "56 clientIdNew: " . $clientIdNew . "<BR>";

        if ($clientId !== $clientIdNew) {
            echo "Not the same <br>";
            $clientId = $clientIdNew;
          };

//echo "63 clientId: " . $clientId . "<BR>";



########################################################
## Convert to the JSON FILE variable names
########################################################

// contact.json variables
//$clientId = $lastName . "_" . $firstName;
//$firstname = $firstName;
//$name = $lastName;
//$initials = $initials;
//$phone =  $phonenum;
//$type = $type;
//$localdateTime = $dateTime;
//$mail = $mail;
//$notes = $notes;


    // Use variables from _POST - build Object array to add to data/contacts.json

        $newClientId = $lastName . "_" . $firstName; // used to test if it is a new contact
        //echo "newClientId: " . $newClientId . "<BR>";

        $clientObj = new stdClass();

        $clientObj->clientId = $newClientId;
        $clientObj->firstname = $firstName;
        $clientObj->lastname = $lastName;
        $clientObj->initials = $initials;
        $clientObj->phone = $phonenum;
        $clientObj->type = $type;
        $clientObj->email = $email;
        $clientObj->notes = $notes;
        $clientObj->localdateTime = $dateTime ;
        // $clientObj->scrambledNumber = $scrambledNumber;

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


// make sure the name is new else exists and bypass create
  // make sure the name is new else exists and bypass create
    // make sure the name is new else exists and bypass create



//Traverse array and get the data for clients with firstname and name from form
    $allClientsfile = "data/contacts.json"; //Get existing JSON file

    $jsondata = file_get_contents($allClientsfile); //Get data from existing JSON file
    $arr_data = json_decode($jsondata, true); // converts existing JSON data into an Array

    $size = sizeof($arr_data); //get total number of clients in the exiting client array and display
    //echo "<BR> Existing Contact Array Size: " . $size . "<BR>";

    foreach ($arr_data as $key1 => $value1) {
      // echo "111 " . $clientId . "<br>";
      // echo $arr_data[$key1]["clientId"] . "<br>";

      // use phone number of clientId ????????????

      if($arr_data[$key1]["clientId"] == $newClientId){
              // Contact Exits modify data
              echo "goto MODIFY Contact Data: " . "<BR>";
          goto modifyArray; // by pass Add a new client

        }
    };

    // Contact does not exist add it

    goto addNewContact;



// *********************************************************************
  modifyArray:
// *********************************************************************
  //echo "<br><strong>Modify: </strong></strong>contacts.json<br>";
  // find array key using clientId  and change its elemts to the new values
    // find array key using clientId  and change its elemts to the new values
      // find array key using clientId  and change its elemts to the new values

        foreach ($arr_data as $key1 => $value1) {
                // test if clientId exists then walk through data

              if($arr_data[$key1]["clientId"] == $newClientId) {

                // update phone number if are not the same
                  if($arr_data[$key1]["phone"] !== $phonenum) {
                     $arr_data[$key1]["phone"] = $phonenum;
                   };
               // update type if not the same
                  if($arr_data[$key1]["type"] !== $type) {
                    $arr_data[$key1]["type"] = $type;
                  };
              // update email if not the same
                  if($arr_data[$key1]["initials"] !== $initials) {
                    $arr_data[$key1]["initials"] = $initials;
                  };
                  if($arr_data[$key1]["lastname"] !== $lastName) {
                     $arr_data[$key1]["lastname"] = $lastName;
                   };
               // update type if not the same
                  if($arr_data[$key1]["firstname"] !== $firstName) {
                    $arr_data[$key1]["firstname"] = $firstName;
                  };
               // update email if not the same
                  if($arr_data[$key1]["email"] !== $email) {
                    $arr_data[$key1]["email"] = $email;
                  };
                // update notes if not the same
                  if($arr_data[$key1]["notes"] !== $notes) {
                    $arr_data[$key1]["notes"] = $notes;
                  };

              } // end update data for clientId from HTML form of new or empty data

                   // echo "173 Update Loop : " . $clientId . "<br>";
   } // end Contact update

 // echo "176 : " . $clientId . "<br>";

// *********************************************************************
// This will delete the submitted contacted of Delete is selected in the form
// *********************************************************************

        if ($contactDelete == "Delete") {

            //echo "In the Delete section: " . $contactDelete . "<br>";

          $clientIdDelete= $lastName . "_" . $firstName;
          foreach($arr_data as $key => $value) {

              //echo "In the Delete section: " . $clientIdDelete . "<br>";

             if($value['clientId'] == $clientIdDelete) {
              unset($arr_data[$key]);
             }
           }
         }

    $reindex = array_values($arr_data); //normalize index
    $arr_data = $reindex; //update variable
// echo "193 : <br>";

    // print_r($arr_data);

// converts updated arr_data to json and saves tp file
// echo "198 : " . $clientId . "<br>";
   //convert array back into json format
   $jsondataNew = json_encode($arr_data, JSON_PRETTY_PRINT);
   //write updated json data into data/contacts.jsonfile
   file_put_contents($allClientsfile, $jsondataNew);
   //echo "Written to JSON file (L198) <br>";

//echo "Contact " . $clientId . " Information Updated";

// *********************************************************************
goto addtoLog; // bypass add to Contacts since it is not new or deleted
// *********************************************************************

// *********************************************************************
  addNewContact:
// *********************************************************************
// ADD NEW PBJECT TO THE END OF THE JSON FILE
  // ADD NEW PBJECT TO THE END OF THE JSON FILE
    // ADD NEW PBJECT TO THE END OF THE JSON FILE
echo "<BR> Adding as new Client: " . $clientId .": " . $phonenum . "<BR>";

//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);

        $allClientsfile = "data/contacts.json"; //Get existing JSON file
        $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);

        // convert array back to JSON and save to file
        $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.jsonfile

// *********************************************************************
  addtoLog:
// *********************************************************************
//============================================================================================
// Save the SMS message to a file with filename by phonenumber as a transaction log
//          and echo results to message window on the webpage
//============================================================================================

//Builds the content of the client log
    // 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>" . "firstName: " . $firstName  . "<br>" . "lastName: " . $lastName . "<br>" . "Initials: " . $initials . " Phone Number: " . $phonenum . "<br>". $type . "<br>";
        $ip2 = $ip1 . "Created: " . date("l, d-M-y H:i:s T");
        $ip3 = $ip2 . "<br>" ."<hr>";

echo "<br>" . "-LOGGED AS-: " . $ip3;

        $datei2 = fopen("data/". $phonenum . ".txt","a") or die("Cannot open file:" . "data/" . $phonenum . ".txt"); //implicitly creates file if it doesn't exist
        fwrite($datei2, $ip3);
        fclose($datei2);



        //============================================================================================
        // Save contact unformation to MySQL database table Contacts
        //          and echo results to message window on the webpage
        //============================================================================================
        ## using POD so it works on other databases
        ## open connection to the database
        $servername = "localhost";
        $username = "tostonc_zx3";
        $password = "A1s2d3f4!@#";
        $dbname = "tostonc_zx3_test";


        try {
          $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
          // set the PDO error mode to exception
          $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

          // prepare sql and bind parameters
          $stmt = $conn->prepare("INSERT INTO SMSContacts (clientID, firstname, lastname, initials, type, email, phone, notes, localdatetime )
                    VALUES (:clientId, :firstname, :lastname, :initials, :type, :email, :phone, :notes, :localdateTime )");

          $stmt->bindParam(':clientId', $newClientId);
          $stmt->bindParam(':firstname', $firstName);
          $stmt->bindParam(':lastname', $lastName);
          $stmt->bindParam(':initials', $initials);
          $stmt->bindParam(':type', $type);
          $stmt->bindParam(':email', $email);
          $stmt->bindParam(':phone', $phonenum);
          $stmt->bindParam(':notes', $notes);
          $stmt->bindParam(':localdateTime', $dateTime);
          $stmt->execute();

          echo "New records created successfully";
        } catch(PDOException $e) {
          echo "Error: " . $e->getMessage();
        }
        $conn = null;




// *********************************************************************
  bigFail:
// *********************************************************************
//echo "-DONE- " ;
//echo "<strong>App SEND Build Date:</strong> 2019.11.21 <br><br>" ;
//SAVED
//echo $version ;

?>

<script>
// reload the select fields with the changes
// reload the select fields with the changes

        loadContactId(); // load select list from contacts.json
        loadPhoneNumbers(); // load select phone numbers from contacts.json

</script>
