#include <WiFi.h> // Use #include <ESP8266WiFi.h> for ESP8266
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include "DHT.h"
#define DHTTYPE DHT11   // DHT 11
#define DHTPIN 5
DHT dht(DHTPIN, DHTTYPE);  

const char* ssid = "TP-Link_688A";
const char* password = "debarbamiguel";

// Replace with your server's URL (ensure https:// if using SSL)
const char* serverName = "http://www.modulo8.migueldebarba.com.br/jsoninsert/insert.php";

void setup() {
  dht.begin();
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  
  Serial.println("Connecting to WiFi...");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected!");
  Serial.println("MAC: "+ WiFi.macAddress());
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    float h = dht.readHumidity();
    float t = dht.readTemperature();    
    
    // Specify the destination URL
    http.begin(serverName);
    http.addHeader("Content-Type", "application/json");

    // Create JSON document
    StaticJsonDocument<200> doc;
    doc["mac_idmac"] = String(WiFi.macAddress());
    doc["sensor_idsensor"] = "1";
    doc["umidade"] = h;
    doc["temperatura"] = t;

    // Serialize JSON to a string
    String jsonString;
    serializeJson(doc, jsonString);

    // Send HTTP POST request
    int httpResponseCode = http.POST(jsonString);

    if (httpResponseCode > 0) {
      String response = http.getString();
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
      Serial.println(response);
    } else {
      Serial.print("Error on sending POST: ");
      Serial.println(httpResponseCode);
    }

    // Free resources
    http.end();
  }
  
  delay(random(13,18)*60000); // Send data every 10 seconds
}
