#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
String apiKey = "6b3c4fe6ffa348d7958c0fa2ac0acfd4";
String serverName = "http://api.ipgeolocation.io/ipgeo?apiKey=" + apiKey;
const char* thingspeakURL = "http://api.thingspeak.com/update";
String thingspeakApiKey = "SSIVNUFSSLRC9EZQ";
void setup() {
  Serial.begin(115200);
  Serial.print("Conectando-se ao Wi-Fi ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConectado ao Wi-Fi!");
}
void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin(serverName);
    
    int httpResponseCode = http.GET(); 
    if (httpResponseCode > 0) {
      String payload = http.getString();
      Serial.println("Resposta do servidor:");
      // JSON
      // Serial.println(payload);
      
      StaticJsonDocument<1024> doc;
      DeserializationError error = deserializeJson(doc, payload);
      if (!error) {
        String country = doc["country_name"].as<String>();
        String city = doc["city"].as<String>();
        float latitude = doc["latitude"];
        float longitude = doc["longitude"];
        
        Serial.print("País: ");
        Serial.println(country);
        Serial.print("Cidade: ");
        Serial.println(city);
        Serial.print("Latitude: ");
        Serial.println(latitude, 6);
        Serial.print("Longitude: ");
        Serial.println(longitude, 6);
        enviarParaThingSpeak(latitude, longitude, city, country);
      } else {
        Serial.print("Erro ao analisar JSON: ");
        Serial.println(error.f_str());
      }
    } else {
      Serial.print("Erro na requisição HTTP: ");
      Serial.println(httpResponseCode);
    }
    http.end();
  } else {
    Serial.println("Erro na conexão Wi-Fi");
  }
  delay(60000); 
}
void enviarParaThingSpeak(float latitude, float longitude, String city, String country) {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    city.replace(" ", "%20");
    country.replace(" ", "%20");
    String url = String(thingspeakURL) + "?api_key=" + thingspeakApiKey +
                 "&field1=" + String(latitude, 6) +
                 "&field2=" + String(longitude, 6) +
                 "&field3=" + city +
                 "&field4=" + country;
    http.begin(url);
    int httpResponseCode = http.GET(); 
    if (httpResponseCode > 0) {
      Serial.print("Dados enviados para o ThingSpeak com sucesso, código: ");
      Serial.println(httpResponseCode);
    } else {
      Serial.print("Erro ao enviar dados para o ThingSpeak, código: ");
      Serial.println(httpResponseCode);
    }
    http.end(); 
  }
}