#include <WiFi.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>

// Wi-Fi Credentials
const char* ssid = "YOUR_SSID";  // Replace with your wifi user name
const char* password = "YOUR_PASSWORD"; // replace with your wifi password

// DHT11 settings
#define DHTPIN 14          // GPIO where DHT11 is connected
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

// Create server on port 80
WiFiServer server(80);

// Global temperature variable
float temperature = 0.0;

void setup() {
  Serial.begin(115200);
  dht.begin();

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500); Serial.print(".");
  }
  Serial.println("\nConnected! IP address: " + WiFi.localIP().toString());

  server.begin();
}

void loop() {
  WiFiClient client = server.available();

  if (client) {
    Serial.println("Client connected");
    while (client.connected()) {
      if (client.available()) {
        String request = client.readStringUntil('\r');
        Serial.println(request);
        client.readStringUntil('\n');

        if (request.indexOf("/temperature") != -1) {
          temperature = dht.readTemperature(); // °C
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/plain");
          client.println("Connection: close");
          client.println();
          client.println(temperature);
        } else {
          temperature = dht.readTemperature();
          String html = "<!DOCTYPE html><html><head><title>ESP32 Temp</title>";
          html += "<meta name='viewport' content='width=device-width, initial-scale=1'>";
          html += "<style>body{font-family:Arial;text-align:center;} h1{margin-top:30px;font-size:2.5em;} h2{color:gray;font-size:1.2em;} #temp{font-size:2.2em;margin-top:20px;}</style>";
          html += "<script>setInterval(()=>{fetch('/temperature').then(r=>r.text()).then(t=>{document.getElementById('temp').innerHTML=t+'&deg;C'})},5000);</script>";
          html += "</head><body>";
          html += "<h1>QUAD ROBOTICS</h1>";
          html += "<h2>A unit of Quad Store</h2>";
          html += "<h3>Room Temperature</h3>";
          html += "<p id='temp'>" + String(temperature) + "&deg;C</p>";
          html += "</body></html>";

          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");
          client.println();
          client.println(html);
        }
        break;
      }
    }
    delay(1);
    client.stop();
    Serial.println("Client disconnected");
  }
}
