#include <WiFi.h>
#include <PubSubClient.h>

// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";

// MQTT Broker
const char* mqttServer = "test.mosquitto.org";
const int mqttPort = 1883;
const char* mqttTopic = "TelkomUniversity/TULT/LT07/Ruang0710";

// Pins
const int ledPin = 12;
const int inputPin = 14;
const int ldrPin = 34;

// Variables
int pirState = LOW;
int val = 0;
int lastPirState = LOW;

WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(inputPin, INPUT);
  Serial.begin(115200);

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

  // Connect to MQTT broker
  mqttClient.setServer(mqttServer, mqttPort);
  while (!mqttClient.connected()) {
    Serial.println("Connecting to MQTT broker...");
    if (mqttClient.connect("ESP32Client")) {
      Serial.println("Connected to MQTT broker");
    } else {
      delay(1000);
    }
  }
}

void loop() {
  // Read PIR state
  pirState = digitalRead(inputPin);

  // Toggle LED if PIR state changes or LDR detects light
  if (pirState != lastPirState || analogRead(ldrPin) < 500) {
    digitalWrite(ledPin, HIGH);
    Serial.println("Motion or light detected");
  } else {
    digitalWrite(ledPin, LOW);
  }

  lastPirState = pirState;

  // Publish LDR value to MQTT broker
  int ldrValue = analogRead(ldrPin);
  String ldrValueString = String(ldrValue);
  mqttClient.publish(mqttTopic, ldrValueString.c_str());

  // Check MQTT messages
  mqttClient.loop();

  delay(1000);
}