#include <WiFi.h>    
#include <HTTPClient.h>
#include <UrlEncode.h>

#define reedSwitch  4
#define led  2 //optional
#define porta 15

const char* ssid = "Wokwi-GUEST";
const char* password = "";

// Holds reedswitch state (1=opened, 0=close)
bool state;

// Auxiliary variables (it will only detect changes that are 1500 milliseconds apart)
unsigned long previousMillis = 0; 
const long interval = 1500;

// +international_country_code + phone number
// Portugal +351, example: +351912345678
String phoneNumber = "+5561991616325";
String apiKey = "4557403";

void sendMessage(String message){

  // Data to send with HTTP POST
  String url = "https://api.callmebot.com/whatsapp.php?phone=556191616325&text=This+is+a+test&apikey=4557403" + phoneNumber + "&apikey=" + apiKey + "&text=" + urlEncode(message);    
  HTTPClient http;
  http.begin(url);

  // Specify content-type header
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");
  
  // Send HTTP POST request
  int httpResponseCode = http.POST(url);
  if (httpResponseCode == 200){
    Serial.print("Message sent successfully");
  }
  else{
    Serial.println("Error sending the message");
    Serial.print("HTTP response code: ");
    Serial.println(httpResponseCode);
  }

  // Free resources
  http.end();
}

void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());

  pinMode(reedSwitch, INPUT_PULLUP);
  pinMode(15, INPUT_PULLUP);
  
  // Set LED state to match door state
  pinMode(led, OUTPUT);
  
  // Set the reedswitch pin as interrupt, assign interrupt function and set CHANGE mode
  attachInterrupt(digitalPinToInterrupt(reedSwitch), Sensor, FALLING);

  // Send Message to WhatsAPP
  sendMessage("QNG 43 ATIVO!");
   
}

bool i=0;
bool estado;

void loop() {

state = digitalRead(reedSwitch);
estado =digitalRead(porta);
if(i){
  if(estado){
  //sendMessage("PORTA ABERTA"+String(estado));
  sendMessage("PORTA FECHADA");}
  else{
  sendMessage("PORTA ABERTA");}
  i=0;
  state=1;
}

}

// Runs whenever the reedswitch changes state
void Sensor() {
  i=1;
}

  
  /*
  Serial.println("State changed");
  changeState = true;
  if (changeState){
    unsigned long currentMillis = millis();
    if(currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
      // If a state has occured, invert the current door state   
        state = !state;
        if(state) {
          doorState = "closed";
        }
        else{
          doorState = "open";
        }
        
        changeState = false;
        Serial.println(state);
        Serial.println(doorState);
        
       

    };
}
*/