#include <WiFi.h>
#include <WebServer.h>
#include <DHT.h>

const char* ssid = "Redmi";
const char* password = "12345678";

// DHT11 στο pin 33
#define DHT_PIN 33
#define DHTTYPE DHT11
DHT dht(DHT_PIN, DHTTYPE);

WebServer server(80);

// Τελευταίες έγκυρες μετρήσεις
float temperature = 0.0;
float humidity = 0.0;
unsigned long lastRead = 0;
const unsigned long readInterval = 2000; // διάβασμα κάθε 2 δευτερόλεπτα

// Ανάγνωση αισθητήρα
void readSensor() {
  if (millis() - lastRead >= readInterval) {
    float h = dht.readHumidity();
    float t = dht.readTemperature();
    if (!isnan(h) && !isnan(t)) {
      humidity = h;
      temperature = t;
    } else {
      Serial.println("Σφάλμα ανάγνωσης DHT11");
    }
    lastRead = millis();
  }
}

String getHTML() {
  String html = "<!DOCTYPE html><html>";
  html += "<head>";
  html += "<meta charset='UTF-8'>";
  html += "<meta name='viewport' content='width=device-width, initial-scale=1'>";
  html += "<style>";
  html += "body { font-family: Arial; text-align: center; background: #ffe4e1; margin: 0; padding: 20px; }";
  html += ".container { max-width: 600px; margin: 0 auto; background: #fff0f0; padding: 30px; border-radius: 20px; box-shadow: 0 4px 15px rgba(255,140,140,0.3); }";
  html += "h1 { color: #b22222; font-size: 28px; margin-bottom: 5px; }";
  html += "h2 { color: #ff6347; font-size: 20px; font-weight: normal; margin-top: 0; }";
  html += ".sensor-box { background: #ffe0e0; border-radius: 15px; padding: 20px; margin: 20px 0; }";
  html += ".sensor { font-size: 32px; color: #b22222; margin: 10px 0; }";
  html += ".sensor span { color: #ff4500; font-weight: bold; }";
  html += ".unit { font-size: 18px; color: #cd5c5c; }";
  html += ".footer { color: #ffa07a; margin-top: 20px; font-size: 14px; }";
  html += "</style>";
  html += "<script>";
  html += "function updateData() {";
  html += "  fetch('/data').then(response => response.json()).then(data => {";
  html += "    document.getElementById('temp').innerText = data.temp.toFixed(1);";
  html += "    document.getElementById('hum').innerText = data.hum.toFixed(1);";
  html += "  }).catch(err => console.log('Σφάλμα:', err));";
  html += "}";
  html += "setInterval(updateData, 2000);"; // ανανέωση κάθε 2 δευτερόλεπτα
  html += "</script>";
  html += "</head>";
  html += "<body>";
  html += "<div class='container'>";
  html += "<h1>1ο ΕΠΑΛ Συκεών</h1>";
  html += "<h2>Θερμοκρασία - Υγρασία από τον αισθητήρα DHT11 του ARD:Icon II</h2>";
  html += "<div class='sensor-box'>";
  html += "<div class='sensor'>🌡️ Θερμοκρασία: <span id='temp'>--</span> <span class='unit'>°C</span></div>";
  html += "<div class='sensor'>💧 Υγρασία: <span id='hum'>--</span> <span class='unit'>%</span></div>";
  html += "</div>";
  html += "<div class='footer'>Αυτόματη ανανέωση κάθε 2 δευτερόλεπτα</div>";
  html += "</div>";
  html += "</body></html>";
  return html;
}

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

  Serial.print("Σύνδεση στο ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

  int attempts = 0;
  while (WiFi.status() != WL_CONNECTED && attempts < 40) {
    delay(500);
    Serial.print(".");
    attempts++;
  }

  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("\n✅ Συνδέθηκε! IP: " + WiFi.localIP().toString());

    // Δρομολόγηση (routing)
    server.on("/", []() {
      server.send(200, "text/html", getHTML());
    });

    server.on("/data", []() {
      String json = "{\"temp\":" + String(temperature) + ",\"hum\":" + String(humidity) + "}";
      server.send(200, "application/json", json);
    });

    server.begin();
    Serial.println("🌐 Web server ξεκίνησε – άνοιξε το browser στην IP παραπάνω");
  } else {
    Serial.println("\n❌ Αποτυχία σύνδεσης!");
  }
}

void loop() {
  server.handleClient();
  readSensor();
}