#include <WiFi.h>
#include "PubSubClient.h"
#include <WebServer.h>
#include <uri/UriBraces.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqttServer = "broker.emqx.io";
int port = 1883;
String stMac;
char mac[50];
char clientId[50];

WiFiClient espClient;
PubSubClient client(espClient);
WebServer server(80);

#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
float h, t, f;
const int ledPin = 2;
int LDR =  36;    // analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDRValue = 0;   // thats a variable to store LDR values
int lightSensitivity = 500;     // this is the approx value of lignt surronding your LDR


void readLight(){
    LDRValue = analogRead(LDR);    // reads the LDR value through LDR
    Serial.print("LDR Value = ");
    Serial.println(LDRValue);     // prints the LDR value to Serial Monitor
    //delay(50);  // this is the speed by which LDR sends value to Arduino
/*
    if (LDRValue < lightSensitivity)
    {
        digitalWrite(13, HIGH);     // NO YELLOW LIGHT
    }
    else
    {
        digitalWrite(13, LOW);      // YELLOW LIGHT
    }
*/
    delay(3000);
}
void sendHtml() {
  h = dht.readHumidity();
  t = dht.readTemperature();
  f = dht.readTemperature(true);

  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  String response = R"(
    <!DOCTYPE html><html>
      <head>
        <title>ESP32 Web Server Demo</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
          html { font-family: sans-serif; text-align: center; }
          body { display: inline-flex; flex-direction: column; }
          h1 { margin-bottom: 1.2em; } 
        </style>
      </head>
            
      <body>
        <h1>ESP32 Web Server</h1>
        
        <div>
          <h2>Temperature and Humidity</h2>
          <p>Humidity: #HUMIDITY#%</p>
          <p>Temperature: #TEMPERATURE#°C (#TEMPERATURE_F#°F)</p>
        </div>
      </body>
    </html>
  )";

  response.replace("#HUMIDITY#", String(h));
  response.replace("#TEMPERATURE#", String(t));
  response.replace("#TEMPERATURE_F#", String(f));
  server.send(200, "text/html", response);
}
void setup() {
  Serial.begin(115200);
  randomSeed(analogRead(0));
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  wifiConnect();
dht.begin();
  server.on("/", sendHtml);
  server.begin();
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println(WiFi.macAddress());
  stMac = WiFi.macAddress();
  stMac.replace(":", "_");
  Serial.println(stMac);
  
  client.setServer(mqttServer, port);
  client.setCallback(callback);
  pinMode(ledPin, OUTPUT);
  

  Serial.println("HTTP server started (http://localhost:8180)");
}

void wifiConnect() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
}

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("topicName/led");
    } 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) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String stMessage;
  
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    stMessage += (char)message[i];
  }
  Serial.println();

  if (String(topic) == "topicName/led") {
    Serial.print("Changing output to ");
    if(stMessage == "on"){
      Serial.println("on");
      digitalWrite(ledPin, HIGH);
    }
    else if(stMessage == "off"){
      Serial.println("off");
      digitalWrite(ledPin, LOW);
    }
  }
}

void loop() {
  delay(10);
  if (!client.connected()) {
    mqttReconnect();
  }
  client.loop();
  h = dht.readHumidity();
  t = dht.readTemperature();
  f = dht.readTemperature(true);
  readLight();
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  sendHtml();

  float hif = dht.computeHeatIndex(f, h);
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print("%  Temperature: ");
  Serial.print(t);
  Serial.print("°C ");
  Serial.print(f);
  Serial.print("°F  Heat index: ");
  Serial.print(hic);
  Serial.print("°C ");
  Serial.print(hif);
  Serial.println("°F");

  delay(2000);
  // Adjust the delay according to your needs
}