#include "WiFi.h"
#include <HTTPClient.h>
#include <ArduinoJson.h>

const char* ssid = "Wokwi-GUEST";         // change SSID
const char* password = "";    // change password

const String GOOGLE_SCRIPT_ID = "AKfycbwW_L7p0NUkVfJBsx3RBoRhQo17lMnQiulh6Df9-CPgbZBiXkGmTT4yKor8eiBnwmsG";    // change Gscript ID
const int EVENT_OPEN = 1;
const int EVENT_CLOSE = 0;
const String EVENT_NAME = "door_sensor_1";

String event_string = "";
String card_number = "123456789";  // Replace with the actual card number
bool server_free = true;

int retry_counter = 0;

void setup() {
  pinMode(4, INPUT_PULLUP);
  delay(100);
  Serial.begin(115200);
  delay(100);

  // connect to WiFi
  Serial.println();
  Serial.print("Connecting to WiFi: ");
  Serial.println(ssid);
  Serial.flush();
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  
  Serial.println("Connected to WiFi");
}

void loop() {
  if (Serial.available() > 0) {
    char command = Serial.read();

    if (command == '1') {
         
         //ler rfid para abrir porta




        //acionar relês para acionar fechadura eletronica


      event_string = String(EVENT_OPEN);

      Serial.println("*** Simulando abertura da porta ***");


    } else if (command == '2') {

        //não fazer nada, recusado
      Serial.println("Cartão não autorizado");
      event_string = String(EVENT_CLOSE);
      Serial.println("*** Simulando fechamento da porta ***");


    }


    if (server_free) {
      server_free = false;
      xTaskCreate(post_data, "post_data", 7168, nullptr, 4, nullptr);
    } else {
      Serial.println("*** HTTP SERVER OCUPADO! IGNORANDO EVENTO ***");
    }
  }


  delay(50); // debounce
}

void post_data(void* params) {
  retry_counter = 3;
  
  while (retry_counter > 0) {
    String url = "https://script.google.com/macros/s/" + GOOGLE_SCRIPT_ID + "/exec";
    
    Serial.println("Enviando dados para a planilha:");
    Serial.println(url);

    // Construir o corpo do JSON
    DynamicJsonDocument jsonDoc(1024);
    jsonDoc["event"] = event_string;
    jsonDoc["card_number"] = card_number;
    jsonDoc["timestamp"] = millis();
    
    String jsonData;
    serializeJson(jsonDoc, jsonData);

    // Enviar dados usando HTTP POST
    HTTPClient http;
    http.begin(url);
    http.addHeader("Content-Type", "application/json");
    int httpCode = http.POST(jsonData);

    Serial.print("Código de status HTTP: ");
    Serial.println(httpCode);

    // Obtendo resposta da planilha do Google
    if (httpCode > 0) {
      String payload;
      payload = http.getString();
      Serial.println("Resposta: " + payload);
      http.end();
      retry_counter = 0;
    } else {
      retry_counter--;
      Serial.println("HTTP POST falhou - tentativas restantes: " + String(retry_counter));
      delay(2000);
    }
  }

  server_free = true;
  vTaskDelete(nullptr);
}