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

// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";

// Firebase project credentials
const char* firebaseHost = "led-onoff-ccfe4-default-rtdb.firebaseio.com";
const char* firebaseAuth = "28THE2yBCxXGNbpgusrjXSsNEBvFcUq9x92eg52G";


// DHT22 sensor settings
#define DHTPIN 4          // DHT22 data pin connected to GPIO 2
#define DHTTYPE DHT22     // DHT 22 (AM2302)

// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);

// LED pin
const int ledPin = 2;

void setup() {
  Serial.begin(115200);
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW); // Ensure LED is off initially

  dht.begin(); // Initialize DHT sensor

  // Connect to WiFi
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected to WiFi");
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    // Read temperature and humidity values from DHT22
    float temperature = dht.readTemperature();
    float humidity = dht.readHumidity();

    if (isnan(temperature) || isnan(humidity)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }

    Serial.print("Temperature: ");
    Serial.print(temperature);
    Serial.print(" °C, Humidity: ");
    Serial.print(humidity);
    Serial.println(" %");

    // Create JSON object to send to Firebase
    StaticJsonDocument<200> jsonDoc;
    jsonDoc["temperature"] = temperature;
    jsonDoc["humidity"] = humidity;

    // Convert JSON object to string
    String jsonString;
    serializeJson(jsonDoc, jsonString);

    // Send temperature and humidity data to Firebase
    HTTPClient http;
    String url = String("https://") + firebaseHost + "/IOT.json?auth=" + firebaseAuth;
    http.begin(url);
    http.addHeader("Content-Type", "application/json");
    int httpResponseCode = http.PATCH(jsonString); // Use PATCH to update part of the node

    if (httpResponseCode > 0) {
      String response = http.getString();
      Serial.print("Firebase response: ");
      Serial.println(response);
    } else {
      Serial.print("Error sending data to Firebase: ");
      Serial.println(httpResponseCode);
    }
    http.end();

    // Retrieve LED state from Firebase
    http.begin(url);
    int httpCode = http.GET();
    if (httpCode > 0) {
      String payload = http.getString();
      Serial.print("Received payload: ");
      Serial.println(payload);

      // Parse JSON
      StaticJsonDocument<200> doc;
      DeserializationError error = deserializeJson(doc, payload);
      if (!error) {
        // Extract the ledState value from the nested JSON
        if (doc.containsKey("ledState")) {
          const char* ledStateStr = doc["ledState"]; // Get the string value associated with the "ledState" key
          Serial.print("Parsed LED State (string): ");
          Serial.println(ledStateStr);

          int ledState = atoi(ledStateStr); // Convert the string to an integer
          Serial.print("Parsed LED State (int): ");
          Serial.println(ledState);
          
          if (ledState == 1) {
            digitalWrite(ledPin, HIGH);
            Serial.println("LED is ON");
          } else {
            digitalWrite(ledPin, LOW);
            Serial.println("LED is OFF");
          }
        } else {
          Serial.println("Error: 'ledState' key not found in JSON");
        }
      } else {
        Serial.print("JSON parse error: ");
        Serial.println(error.c_str());
      }
    } else {
      Serial.print("Error on HTTP request: ");
      Serial.println(httpCode);
    }
    http.end();
  } else {
    Serial.println("WiFi Disconnected");
  }

  delay(5000); // Wait for 5 seconds before the next request
}