#include "WiFi.h"
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <MFRC522.h> // Include the RFID library

#define RST_PIN         22           // Configurable, set to -1 if unused
#define SS_PIN          21          // Configurable

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

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

const String GOOGLE_SCRIPT_ID = "AKfycbyk3ZyvO5oIM1tvtUvSMnUxFXUCVSk0Yoz0YPCK-qiWGMjluPXrpWjfvqynuosIube_";    // 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 = "";  // Placeholder for storing the RFID tag
bool server_free = true;

int retry_counter = 0;

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

  SPI.begin();        // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522

  // 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() {
  // Look for new cards
  if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
    String tag = "";
    for (byte i = 0; i < mfrc522.uid.size; i++) {
      tag.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
      tag.concat(String(mfrc522.uid.uidByte[i], HEX));
    }
    tag.toUpperCase();
    card_number = tag.substring(1);
    Serial.println("Tag: " + card_number);
    
    // Example: Check if the card number is authorized
    if (card_number == "123ABC") {
      event_string = String(EVENT_OPEN);
      Serial.println("*** Simulando abertura da porta ***");
    } else {
      event_string = String(EVENT_CLOSE);
      Serial.println("Cartão não autorizado");
      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 ***");
    }
  }

  mfrc522.PICC_HaltA(); // Stop reading
  mfrc522.PCD_StopCrypto1();  // Stop encryption
}

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