#include <Arduino.h>
#include <Keypad.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#define USE_SERIAL Serial

WiFiMulti wifiMulti;
HTTPClient http;

// Sets the output variable which will be used throughout the entire script
String output = "";

// Sets up the numpad inputs
#define ROW_NUM     4 // four rows
#define COLUMN_NUM  4 // four columns

char keys[ROW_NUM][COLUMN_NUM] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

byte pin_rows[ROW_NUM]      = {19, 18, 5, 17}; // GIOP19, GIOP18, GIOP5, GIOP17 connect to the row pins
byte pin_column[COLUMN_NUM] = {16, 4, 0, 2};   // GIOP16, GIOP4, GIOP0, GIOP2 connect to the column pins

Keypad keypad = Keypad( makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM );

void setup() {
  Serial.begin(115200);

  USE_SERIAL.begin(115200);
  USE_SERIAL.println();
  USE_SERIAL.println();

// Prints a countdown to the console
  for(uint8_t t=4; t > 0; t--) {
    USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
    USE_SERIAL.flush();
    delay(1000);
  }

// Connects the ESP32 to the appropriate WiFi network
  wifiMulti.addAP("OSU_Access", "");  

// If the connection has failed, continues to try and reconnect until it succeeds
  while ((wifiMulti.run() != WL_CONNECTED)) {
    USE_SERIAL.println("Reconnecting");
    wifiMulti.addAP("OSU_Access", "");
    delay (2000);    
  }

  USE_SERIAL.println("Connected!");
}

void loop() {
  char key = keypad.getKey();

// If the pressed key is a number, it is logged in the output variable
  if (isDigit(key)) {
    output += key;
  }

// If the pressed key is a hashtag, it sends it to the webpage
  if (key ==  '#') {
    Serial.println(output);

    if ((wifiMulti.run() == WL_CONNECTED)) {
      http.begin("https://web.engr.oregonstate.edu/~mcdavida/storageSite.php");
      http.addHeader("Content-Type","application/x-www-form-urlencoded");
      // For some reason, the webpage cuts off the first number of the output variable. This adds another number in front of variable so it can be cut off later
      String output2 = 1 + output;
      String httpRequestData = "code=" + output2;
      Serial.print("POST Data sent: ");
      Serial.println(output);
      int httpCode = http.POST(httpRequestData);
      
      http.end();
    }

    // Resets the output variable for additional entries
    output = "";
    delay(5000);
  }
}

 
