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

#define DHTPIN 13   
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

const char* ssid = "ayrus";
const char* password =  "tplink@123";
// Supabase
String url = "https://gpmnskqwegzwhggemqqu.supabase.co/rest/v1/ESP32";
String apikey = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImdwbW5za3F3ZWd6d2hnZ2VtcXF1Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2ODAxNTQ4ODIsImV4cCI6MTk5NTczMDg4Mn0.bWXJ3dee_v_Q7mA9KMJwWki_MYEcCzm-Qe3MAVM4S78";
char objetoJson[128];

void setup() {
 
  Serial.begin(115200);
  
  dht.begin();
  
  WiFi.begin(ssid, password);
  Serial.print("Conectando...");
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.print("Conexión Wifi establecida, mi dirección IP es: ");
  Serial.println(WiFi.localIP());

}

void loop(){
  if ((WiFi.status()== WL_CONNECTED)) {

  float h = dht.readHumidity();
  float t = dht.readTemperature();

    if (isnan(h) || isnan(t)) {
    Serial.println(F("¡Error en la lectura del sensor DHT!"));
    return;
  }

  Serial.println();
  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("°C "));
  Serial.println();
    
    HTTPClient client;
    
    client.begin( url );
    client.addHeader("apikey", apikey);
    client.addHeader("Content-Type", "application/json");

    const size_t CAPACITY = JSON_OBJECT_SIZE(3);
    StaticJsonDocument<CAPACITY> doc;

    JsonObject obj= doc.to<JsonObject>();
    obj ["id"] = "1";
    obj ["temperatura"] = t;
    obj ["humedad"] = h;

    serializeJson (doc, objetoJson);
    Serial.println("Objeto json: ");
    Serial.print(objetoJson);
    
    int httpCode = client.PATCH(String(objetoJson));

      if (httpCode > 0) {
          Serial.println();
          Serial.printf("Código de respuesta: %d\t", httpCode);
      
          if (httpCode == HTTP_CODE_OK) {
            String payload = client.getString();
            Serial.println(payload);
          }
        }
        else {
          Serial.printf("Error de la solicitud, error: %s\n", client.errorToString(httpCode).c_str());
        }
    client.end();
    }
    else {
     Serial.println("Conexión perdida");
     }  
  delay (3000);
}