/*
  MuTech Robotics - H3 "Did I lock the door?" on your phone
  Board : ESP32 development board (30-pin), 5 V USB adapter
  Sensor: reed switch (normally open) fixed INSIDE THE DOOR FRAME behind the strike plate,
          small magnet glued to the TIP OF THE BOLT. Bolt thrown = magnet next to reed = LOCKED.
          (A switch on the door edge would only tell you "closed", not "locked".)
  Phone : free Telegram bot - works from anywhere, not only on home Wi-Fi.
          Create a bot with @BotFather, put the token + your chat ID below.

  Wiring
    Reed switch lead A -> GND
    Reed switch lead B -> D27   (internal pull-up: LOW = magnet near = LOCKED)

  Commands: /status
  Libraries: "UniversalTelegramBot" + "ArduinoJson" (Library Manager)
*/
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <time.h>

const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASS = "YOUR_PASSWORD";
const char* BOT_TOKEN = "YOUR_BOT_TOKEN";
const char* CHAT_ID   = "YOUR_CHAT_ID";
const int REED = 27;

WiFiClientSecure client; UniversalTelegramBot bot(BOT_TOKEN, client);
bool lockedNow = false; String since = "--";
unsigned long lastPoll = 0, changeAt = 0; bool pending = false;

String clockNow() {
  struct tm tm; if (!getLocalTime(&tm, 200)) return "--:--";
  char b[16]; strftime(b, sizeof b, "%I:%M %p", &tm); return String(b);
}
bool readLocked() { return digitalRead(REED) == LOW; }

void setup() {
  pinMode(REED, INPUT_PULLUP);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) delay(300);
  client.setInsecure();                       // simple TLS for the bot (no certificate check)
  configTime(19800, 0, "pool.ntp.org");       // IST (UTC+5:30); change 19800 for your time zone
  lockedNow = readLocked(); since = clockNow();
  bot.sendMessage(CHAT_ID, String("Door sensor online. Door is ") + (lockedNow ? "LOCKED" : "UNLOCKED"), "");
}

void loop() {
  bool now = readLocked();
  if (now != lockedNow && !pending) { pending = true; changeAt = millis(); }
  if (pending && millis() - changeAt > 500) {                 // debounce
    pending = false;
    if (readLocked() != lockedNow) {
      lockedNow = readLocked(); since = clockNow();
      bot.sendMessage(CHAT_ID, String(lockedNow ? "Front door LOCKED " : "Front door UNLOCKED ") + since, "");
    }
  }
  if (millis() - lastPoll > 2000) {
    lastPoll = millis();
    int n = bot.getUpdates(bot.last_message_received + 1);
    for (int i = 0; i < n; i++) {
      if (bot.messages[i].chat_id != CHAT_ID) continue;
      if (bot.messages[i].text == "/status")
        bot.sendMessage(CHAT_ID, String(lockedNow ? "Still LOCKED (since " : "UNLOCKED (since ") + since + ")", "");
    }
  }
}
