/*
Google Apps Script:

var sheetID = '';  // Replace with your actual spreadsheet ID

function doGet(e) { 
  Logger.log( JSON.stringify(e) );
  var result = 'Ok';
  if (e.parameter == 'undefined') {
    result = 'No Parameters';
  }
  else {
    var sheet_id = '.....'; 	// Spreadsheet ID
    var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet();
    var newRow = sheet.getLastRow() + 1;						
    var rowData = [];
    var Curr_Date = new Date();
    rowData[0] = Curr_Date; // Date in column A
    var Curr_Time = Utilities.formatDate(Curr_Date, "Asia/Bangkok", 'HH:mm:ss');
    rowData[1] = Curr_Time; // Time in column B
    for (var param in e.parameter) {
      Logger.log('In for loop, param=' + param);
      var value = stripQuotes(e.parameter[param]);
      Logger.log(param + ':' + e.parameter[param]);
      switch (param) {
        case 'temp':
          rowData[2] = value; // Temperature in column C
          result = 'temp Written on column C'; 
          break;
        case 'humi':
          rowData[3] = value; // Temperature in column D
          result = 'humidity Written on column D'; 
          break;
      }
    }
    Logger.log(JSON.stringify(rowData));
    var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
    newRange.setValues([rowData]);
  }
  return ContentService.createTextOutput(result);
}
function stripQuotes( value ) {
  return value.replace(/^["']|['"]$/g, "");
}

*/

// IMPORTANT!! add "attrs": { "fastTLS": "1" } in wokwi diagram.json for esp board

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

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

const char* ssid = "Wokwi-GUEST"; // Wifi name
const char* password = "";        // Wifi password
const char* webAppUrl = "https://script.google.com/..../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(5000); // Delay for 5 seconds
}

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

  // Your server address
  String serverPath = String(webAppUrl) + "?temp=" + String(temperature) + "&humi=" + String(humidity);

  Serial.print("Connecting to server: ");
  Serial.println(serverPath);

  // Send HTTP GET request
  if (http.begin(serverPath)) {
    int httpCode = http.GET();
    if (httpCode > 0) {
      Serial.print("Server response code: ");
      Serial.println(httpCode);
      //String payload = http.getString();
      //Serial.println("Server response: " + payload);
    } else {
      Serial.print("HTTP GET request failed with error code: ");
      Serial.println(httpCode);
    }
    http.end();
  } else {
    Serial.println("Unable to connect to the server");
  }
}