#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* token = "6tGAukGYflmoLhSFd2GZ8bKVZKLri2eHvMx6eOX8lbP"; //Line token form https://notify-bot.line.me/th/
#define DHTPIN 13      // Pin connected to DHT22
#define DHTTYPE DHT22 // DHT sensor type
#define PIR 27
DHT dht(DHTPIN, DHTTYPE);
void setup() {
  pinMode(PIR,INPUT);
  Serial.begin(115200);
  delay(4000);
  dht.begin();
  delay(2000);
  WiFi.begin("Wokwi-GUEST", "", 6);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
  Serial.println(" READY ");
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin("https://notify-api.line.me/api/notify");
    http.addHeader("Authorization", "Bearer " + String(token));
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
   float temperature = dht.readTemperature(); // Gets the values of the temperature
   float humidity = dht.readHumidity(); // Gets the values of the humidity 
    const int student=digitalRead(PIR);
    if(student){
      http.POST("message=นายชนิณทร์ ใจช่วง IS ALREADY HERE");
    }
    if (isnan(humidity) || isnan(temperature)) {
      Serial.println("Failed to read from DHT sensor!");
    } else {
      Serial.print("Humidity: ");
      Serial.print(humidity);
      Serial.print(" %\t");
      Serial.print("Temperature: ");
      Serial.print(temperature);
      String humid = String(humidity);
      http.POST("message=ชื้นสูงในห้องเรียน : "+humid+" %");
      String tempMessage = String(temperature);
      http.POST("message=อุณหภูมิในห้องเรียน : "+tempMessage+" °C");
      if (temperature > 35) {
        http.POST("message=แจ้งเตือนอุณหภูมิสูง🌡");
        Serial.println("High temperature message sent");
      }
      if (humidity > 55) {
        http.POST("message=แจ้งเตือนความชื้นสูง🌫");
         Serial.println("High humidity message sent");
        Serial.println("==================================");
      }
    }
    int httpCode = http.POST("READY");  // Use an empty POST request to send only headers
    if (httpCode > 0) {
      String response = http.getString();
    } else {
      Serial.println(".....");
    }
    http.end();
    delay(5000); // Send a message and read sensor data every 15 Minute
  }
}