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

// WiFi and MQTT Server credentials
const char* mqttServer = "broker.emqx.io";
int port = 1883;
String stMac;
char mac[50];
char clientId[50];
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

// Pin definitions
const int pinRed = 26;
const int pinGreen = 27;
const int pinBlue = 14;

void setup() {
  Serial.begin(115200);
  randomSeed(analogRead(0));
  delay(10);

  // WiFiManager configuration
  WiFiManager wifiManager;
  bool wifiConnected = wifiManager.autoConnect("......", "......");

  if (wifiConnected) {
    Serial.println("Terkoneksi Dengan Hotspot ......");
  } else {
    Serial.println("Tidak Terkoneksi");
  }

  // Display WiFi connection details
  Serial.println("WiFi connected");
  Serial.println("IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.println(WiFi.macAddress());
  stMac = WiFi.macAddress();
  stMac.replace(":", "_");
  Serial.println(stMac);

  // Setup MQTT
  client.setServer(mqttServer, port);
  client.setCallback(callback);

  // Setup pin modes
  pinMode(pinRed, OUTPUT);
  pinMode(pinGreen, OUTPUT);
  pinMode(pinBlue, OUTPUT);
}

void mqttReconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    long r = random(1000);
    sprintf(clientId, "clientId-%ld", r);
    if (client.connect(clientId)) {
      Serial.print(clientId);
      Serial.println(" connected");
      client.subscribe("......");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void callback(char* topic, byte* message, unsigned int length) {
  if ((char)message[0] == '1') {
    digitalWrite(pinRed, HIGH);
    digitalWrite(pinGreen, HIGH);
    digitalWrite(pinBlue, HIGH);
  } else {
    digitalWrite(pinRed, LOW);
    digitalWrite(pinGreen, LOW);
    digitalWrite(pinBlue, LOW);
  }
}

void loop() {
  delay(10);
  if (!client.connected()) {
    mqttReconnect();
  }
  client.loop();
}