#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h> 
#define DOOR_SENSOR_PIN 19 // ESP32 pin 19 connected to door sensor's pin

int currentDoorState; // current state of door
int lastDoorState; // previous state of door

WiFiMulti wifiMulti;
void setup() {
  Serial.begin(115200);
  for(uint8_t t = 4; t> 0; t--) {
    Serial.printf("[SETUP] WAIT %d...\n", t);
    Serial.flush();
    delay(1000);
  }
  wifiMulti.addAP("OSU_Access","");

  pinMode(DOOR_SENSOR_PIN,INPUT_PULLUP);
  currentDoorState = digitalRead(DOOR_SENSOR_PIN);

  
}


void loop() {
  String myString;
  String myResult;
  lastDoorState = currentDoorState; // save last state
  currentDoorState = digitalRead(DOOR_SENSOR_PIN); // read the new state
  if(currentDoorState == LOW && lastDoorState == HIGH) { // state change: low
    Serial.println("The door has been closed");
    myResult = "a";
  }
  else 
  if (currentDoorState == HIGH && lastDoorState == LOW) { //state change: high
    Serial.println("The door has been opened");
    myResult = "b";
  }
  else{
    Serial.println("no change");
    myResult = "c";
  }
  
  
  if((wifiMulti.run() == WL_CONNECTED)) { // wait for WiFi connection
      HTTPClient http; // Creates an HTTPClient object to be used
      //Begins a reques we will eventuall POST
      http.begin("https://web.engr.oregonstate.edu/~shawjax/final.php");
      http.addHeader("Content-Type", "application/x-www-form-urlencoded");
      //Data to send with HTTP POST
      String myString;
      myString = "value=";
      myString = myString + myResult;
      Serial.print("POST data to send: ");
      Serial.println(myString);
      int httpCode = http.POST(myString);
      if(httpCode > 0) { //Did we get a valid response?
          if(httpCode == HTTP_CODE_OK) { //The POST happened correctly 
              String payload = http.getString();
              Serial.println(payload);
          }else {
            Serial.printf("[HTTP] GET... code: d\n", httpCode);
          }
      }
      http.end(); //END this request. 

      
  }
  else{
    Serial.println("not connected :(");
    }
  
  
   delay(1000);
  }
  
  
