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

#define DHTPIN 4          // DHT22 sensor pin
#define DHTTYPE DHT22     // DHT22 sensor type

const char* ssid = "Wokwi-GUEST"; // Wifi name
const char* password = "";        // Wifi password
const char* webAppUrl = "https://script.google.com/macros/s/AKfycbxCtu7aiqqHQYnO93BU5yCtxHWpG3XaDAqxwxhGe_GfYqshHbcMJQt4Wy9jp0rKz79y/exec";  // Replace with your actual web app URL

DHT dht(DHTPIN, DHTTYPE);

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

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }

  Serial.println("Connected to WiFi");

  dht.begin();
}

void loop() {
  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature();

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

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

  // Send data to Google Apps Script
  sendDataToScript(temperature, humidity);

  delay(10000); // Delay for 30 seconds
}

void sendDataToScript(float temperature, float humidity) {
  HTTPClient http;

  // Prepare data to send
  String data = "temperature=" + String(temperature) + "&humidity=" + String(humidity);
  Serial.print("Connecting to server: ");
  Serial.println(webAppUrl);

  // Send HTTP POST request
  http.begin(webAppUrl);
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");
  int httpCode = http.POST(data);

  if (httpCode > 0) {
    Serial.print("Server response code: ");
    Serial.println(httpCode);
    String payload = http.getString();
    Serial.println("Server response: " + payload);
  } else {
    Serial.print("HTTP POST request failed with error code: ");
    Serial.println(httpCode);
  }

  http.end();
}