#define BLYNK_TEMPLATE_ID "TMPL6iG4D-Qrf"
#define BLYNK_TEMPLATE_NAME "FarmTech"
#define BLYNK_AUTH_TOKEN "EevzGnG01KhuZqxG7QW49EOlm84iC21Z"
#include <BlynkSimpleEsp32.h>
char ssid[] = "Wokwi-GUEST";
char pass[] = "";

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

// Defining LED PINs on the ESP32 Board.
const int LED_PIN = 10;
DHT dht(3, DHT22);

// Google script Web_App_URL.
const String WEB_APP_URL = "https://script.google.com/macros/s/AKfycbx2baSDrProWKaNA4vI4apJhJuiXcolfH_zpYh41EaQW4XvLE7e1YNsU15E2gpkLI7m/exec";

const int wet = 239;
const int dry = 595;

unsigned long previousMillis_Blynk = 0;
unsigned long previousMillis_GSheets = 0;
const long interval_Blynk = 3000; // 3 วินาที
const long interval_GSheets = 3000; // 3 วินาที

void setup() {
  Serial.begin(115200);
  Serial.println();
  Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);

  pinMode(LED_PIN, OUTPUT);

  WiFi.mode(WIFI_STA);
  Serial.print("Connecting to WiFi");
  WiFi.begin("Wokwi-GUEST", "", 6);
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("WiFi connected.");
  Serial.println("------------");

  digitalWrite(LED_PIN, LOW);
}

void loop() {
  Blynk.run();
  unsigned long currentMillis = millis();

  // Blynk Data Sending
  if (currentMillis - previousMillis_Blynk >= interval_Blynk) {
    previousMillis_Blynk = currentMillis;
    sendBlynkData();
  }

  // Google Sheets Data Sending
  if (currentMillis - previousMillis_GSheets >= interval_GSheets) {
    previousMillis_GSheets = currentMillis;
    sendGSheetsData();
  }
}

void sendBlynkData() {
  int rh = dht.readHumidity();
  float t = dht.readTemperature();
  int SM = random(wet, dry); //analogRead(26);
  int sm = map(SM, wet, dry, 100, 0);
  Blynk.virtualWrite(V0, rh);
  Blynk.virtualWrite(V1, t);
  Blynk.virtualWrite(V2, sm);
}

void sendGSheetsData() {
  if (WiFi.status() == WL_CONNECTED) {
    digitalWrite(LED_PIN, HIGH);
    int rh = dht.readHumidity();
    float t = dht.readTemperature();
    int SM = random(wet, dry); //analogRead(26);
    int sm = map(SM, wet, dry, 100, 0);
    // Create a URL for sending or writing data to Google Sheets.
    String Send_Data_URL = WEB_APP_URL + "?sts=write";
    Send_Data_URL += "&temp=" + (String)t;
    Send_Data_URL += "&humi=" + (String)rh;
    Send_Data_URL += "&soilm=" + (String)sm;

    Serial.println();
    Serial.println("-------------");
    Serial.println("Send data to Google Spreadsheet...");
    Serial.print("URL : ");
    Serial.println(Send_Data_URL);

    // Writing data to Google Sheets.
    HTTPClient http;

    // HTTP GET Request.
    http.begin(Send_Data_URL.c_str());
    http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);

    // Gets the HTTP status code.
    int httpCode = http.GET();
    Serial.print("HTTP Status Code : ");
    Serial.println(httpCode);

    // Getting response from google sheets.
    String payload;
    if (httpCode > 0) {
      payload = http.getString();
      Serial.println("Response: " + payload);
    }

    http.end();

    digitalWrite(LED_PIN, LOW);
    Serial.println("-------------");
  }
}