#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
#include <DHT.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);

DHT dht(18, DHT22); //Pin, Jenis DHT

// SSID dan Password WiFi
const char* ssid = "Wokwi-GUEST";
const char* password = "";
float lembab;
float suhu;
// Telegram BOT
#define BOTtoken "7035955949:AAF-UldBlfqjxe6qGpkjc9OQeurgSUlNDEY"
#define CHAT_ID "1464476909"

#define pin_merah   15

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);

// Cek Pesan Setiap 1 detik
int interval = 1000;
unsigned long waktu_terakhir;
bool status_merah;

void setup() {
  // atur mode pin menjadi output
  LCD.init();
  LCD.backlight();
  LCD.setCursor(0, 0);
  LCD.print("IOT SUHU-LEMBAB");
  LCD.setCursor(0, 1);
  LCD.print("  KELAS CE-4B  ");
  
  pinMode(pin_merah, OUTPUT);

  // Serial monitor
  Serial.begin(115200);
  
  // Hubungkan ke Wi-Fi
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Sedang menghubungkan ke WiFi..");
  }
  
  // IP Address
  Serial.println(WiFi.localIP());
  Serial.print("Atur Waktu: ");
  configTime(0, 0, "pool.ntp.org"); 
  time_t now = time(nullptr);
  while (now < 24 * 3600)
  {
    Serial.print(".");
    delay(100);
    now = time(nullptr);
  }
  Serial.println(now);
}

void loop() {
  lembab = dht.readHumidity();
  suhu = dht.readTemperature();
  LCD.setCursor(0, 0);
  LCD.print("SUHU : ");
  LCD.print(round(suhu));
  LCD.print(" C ");
  LCD.setCursor(0, 1);
  LCD.print("LEMBAB : ");
  LCD.print(round(lembab));
  LCD.print(" % ");
  cek_pesan();
}

// Cek Pesan Terbaru
void cek_pesan(){
  if (millis() > waktu_terakhir + interval){
    int banyakPesan = bot.getUpdates(bot.last_message_received + 1);
  
    while(banyakPesan) {
      Serial.println("got response");
      handleNewMessages(banyakPesan);
      banyakPesan = bot.getUpdates(bot.last_message_received + 1);
    }
    waktu_terakhir = millis();
  }
}

// Memproses pesan yang diterima
void handleNewMessages(int numNewMessages) {
  for (int i=0; i<numNewMessages; i++) {
    
    // Cek Chat ID
    String chat_id = String(bot.messages[i].chat_id);
    Serial.println(chat_id);
    if (chat_id != CHAT_ID){
      bot.sendMessage(chat_id, "Unauthorized user", "");
      continue;
    }
    
    // Terima pesan dari telegram
    String text = bot.messages[i].text;
    Serial.println(text);

    String from_name = bot.messages[i].from_name;

    if (text == "/start") {
      String welcome = "Selamat Datang, " + from_name + ".\n";
     // Komen berikut untuk kontrol LED
      welcome += "/ledon \n"; //untuk LED Merah ON 
      welcome += "/ledoff \n"; // untuk LED Merah OFF
      welcome += "/statusled\n"; // mendapatkan status LED Merah
      welcome += "/suhu\n"; // mendapatkan status LED Merah
      welcome += "/lembab\n"; // mendapatkan status LED Merah
      bot.sendMessage(chat_id, welcome, "");
    }

    if (text == "/ledon") {
      bot.sendMessage(chat_id, "LED Merah ON", "");
      led_merah(true);
    }
    
    if (text == "/ledoff") {
      bot.sendMessage(chat_id, "LED Merah OFF", "");
      led_merah(false);
    }

    if (text == "/suhu") {
      String msg="Suhu ruangan: ";
             msg += msg.concat(suhu);
             msg += "C";
      bot.sendMessage(chat_id,msg,"");
    } 
   if (text == "/lembab") {
     String  msg="Kelembaban: ";
             msg += msg.concat(lembab);
             msg += "%";
      bot.sendMessage(chat_id,msg,"");
    }

    if (text == "/statusled") {
      if (digitalRead(pin_merah)){
        bot.sendMessage(chat_id, "LED Merah ON", "");
      }
      else{
        bot.sendMessage(chat_id, "LED Merah OFF", "");
      }
    }
    
     }
}

void led_merah(bool isOn){
  if(isOn){
    digitalWrite(pin_merah, HIGH);
  }
  else{
    digitalWrite(pin_merah, LOW);
  }
}