// #include <ESP8266WiFi.h>
#include <WiFi.h>
#include <ArduinoJson.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>

// Wi-Fi configuration
// const char* ssid = "iPhone";
// const char* password = "kurnia123";

// Telegram bot configuration
#define telegramToken  "6014947126:AAGHgmBN-A4Up2o9IaP04SrhHfiG9zDFOhg"
#define chatId  "5495966066" // Replace with your chat ID

// const char* testHost = "www.google.com";  // Replace with your test host

const int moisturePin = A0;
const int pumpPin = 1;
const int dryThreshold = 300;  // Dry threshold value
const int wetThreshold = 500;  // Wet threshold value
const int stabilityDelay = 2000;  // Stability delay for sensor (in milliseconds)

WiFiClientSecure client;
UniversalTelegramBot bot(telegramToken, client);

void setup() {
  Serial.begin(115200);
  pinMode(pumpPin, OUTPUT);
  delay(1000);  // Delay for sensor stability when powered on

  // Connect to Wi-Fi
  // WiFi.begin(ssid, password);
  // while (WiFi.status() != WL_CONNECTED) {
  //   delay(1000);
  //   Serial.println("Connecting to WiFi...");
  // }
  // Serial.println("Connected to WiFi");
  WiFi.begin("Wokwi-GUEST", "", 6);
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");
  Serial.println("Connected to WiFi");

  // Print the Wi-Fi network details
  // Serial.print("SSID: ");
  // Serial.println(WiFi.SSID());
  // Serial.print("IP address: ");
  // Serial.println(WiFi.localIP());

  // Print the initial moisture level
  int moistureValue = analogRead(moisturePin);
  Serial.print("Initial moisture level: ");
  Serial.println(moistureValue);

  // Send a test message to check the Telegram connection
  
  bot.sendMessage(chatId, "Bot started up", "");
  bool messageSent = sendTelegramMessage("Test message");
  if (messageSent) {
    Serial.println("Telegram connection successful");
  } else {
    Serial.println("Telegram connection failed");
  }

  // Test HTTPS connection
  // if (testHTTPSConnection()) {
  //   Serial.println("HTTPS connection test successful");
  // } else {
  //   Serial.println("HTTPS connection test failed");
  // }
}

void loop() {
  int moistureValue = analogRead(moisturePin);

  if (moistureValue <= wetThreshold) {
    digitalWrite(pumpPin, LOW);  // Turn off the pump
    Serial.println("Moisture level: Wet");
    sendTelegramMessage("Moisture level: Wet");
  } else if (moistureValue >= dryThreshold) {
    digitalWrite(pumpPin, HIGH);  // Turn on the pump
    Serial.println("Moisture level: Dry");
    sendTelegramMessage("Moisture level: Dry");
  }

  delay(stabilityDelay);  // Delay for sensor stability

  // Read messages from Telegram bot
  int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
  while (numNewMessages) {
    Serial.println("New message(s) received");

    for (int i = 0; i < numNewMessages; i++) {
      String text = bot.messages[i].text;

      // Respond to manual commands from Telegram bot
      if (text == "/status") {
        sendTelegramStatus(moistureValue);
      } else if (text == "/on") {
        digitalWrite(pumpPin, LOW);  // Turn on the pump
        sendTelegramMessage("Pump turned on");
      } else if (text == "/off") {
        digitalWrite(pumpPin, HIGH);  // Turn off the pump
        sendTelegramMessage("Pump turned off");
      }

      // Get new messages if any
      numNewMessages = bot.getUpdates(bot.last_message_received + 1);
    }
  }
}

bool sendTelegramMessage(String message) {
  return bot.sendMessage(chatId, message);
}

void sendTelegramStatus(int moistureValue) {
  String statusMessage = "Moisture level: " + String(moistureValue);
  sendTelegramMessage(statusMessage);
}

// bool testHTTPSConnection() {
//   WiFiClientSecure testClient;
//   if (testClient.connect(testHost, 443)) {
//     testClient.print(String("GET / HTTP/1.1\r\n") +
//                      "Host: " + testHost + "\r\n" +
//                      "Connection: close\r\n\r\n");

//     // Wait for the server's response
//     while (testClient.connected()) {
//       if (testClient.available()) {
//         String responseLine = testClient.readStringUntil('\n');
//         responseLine.trim();
//         if (responseLine == "HTTP/1.1 200 OK") {
//           return true;  // Successful HTTPS connection
//         }
//       }
//     }

//     // Print error code if available
//     int errorCode = testClient.getWriteError();
//     if (errorCode != 0) {
//       Serial.print("HTTPS connection error code: ");
//       Serial.println(errorCode);
//     }
//   }
//   return false;  // HTTPS connection failed
// }