#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>

// WiFi & Telegram credentials
const char* ssid = "Nramar";
const char* password = "28081999";
const char* botToken = "8183590796:AAEnw8w7czYdMU92ezaspLJylXaJFmSGgxU";
const char* chat_id = "@ParkirMallSidoarjo";

WiFiClientSecure secured_client;
UniversalTelegramBot bot(botToken, secured_client);

// Sensor configuration
const int trigPins[5] = {14, 26, 33, 18, 5};
const int echoPins[5] = {27, 25, 32, 19, 17};
const int ledPins[5]  = {23, 22, 21, 16, 4}; // pastikan tidak pakai GPIO 19 dua kali

bool slotStatus[5] = {true, true, true, true, true}; // true = kosong, false = terisi

void setup() {
  Serial.begin(115200);
  
  // Init pins
  for (int i = 0; i < 5; i++) {
    pinMode(trigPins[i], OUTPUT);
    pinMode(echoPins[i], INPUT);
    pinMode(ledPins[i], OUTPUT);
    digitalWrite(ledPins[i], HIGH); // LED ON = slot kosong
  }

  // Connect WiFi
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" Connected!");

  // Setup TLS
  secured_client.setInsecure();

  // Kirim pesan awal
  bot.sendMessage(chat_id, "🚗 Sistem Parkir Online Aktif!", "");
}

long readDistanceCM(int trigPin, int echoPin) {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH, 30000); // max 30ms
  long distance = duration * 0.034 / 2;
  return distance;
}

void loop() {
  bool statusChanged = false;
  String statusPesan = "📊 Status Parkir:\n";

  for (int i = 0; i < 5; i++) {
    long distance = readDistanceCM(trigPins[i], echoPins[i]);
    bool nowEmpty = distance > 5 || distance == 0; // UBAH di sini (sebelumnya > 2)

    if (slotStatus[i] != nowEmpty) {
      slotStatus[i] = nowEmpty;
      statusChanged = true;
    }

    // LED indikasi
    digitalWrite(ledPins[i], slotStatus[i] ? HIGH : LOW); // ON jika kosong

    // Tambahkan ke pesan
    statusPesan += "Slot " + String(i + 1) + ": " + (slotStatus[i] ? "KOSONG ✅" : "TERISI ❌") + "\n";

    delay(100); // stabilisasi antar sensor
  }

  if (statusChanged) {
    bot.sendMessage(chat_id, statusPesan, "");
  }

  delay(1000);
}
