#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 4);

float gia_xang = 0;
String buyPrice;
String sellPrice;
String ipAddress;
String country;
String city;

// Function to perform HTTP GET request and return response
String httpGetRequest(const char* url) {
  HTTPClient http;
  http.begin(url);
  int httpCode = http.GET();
  String payload;
  if (httpCode > 0) {
    payload = http.getString();
    Serial.println(payload);
  } else {
    Serial.println("Error on HTTP request");
  }
  http.end();
  return payload;
}

// Function to parse JSON for fuel data
void parseFuelPrice(const String& payload) {
  DynamicJsonDocument doc(4096);
  DeserializationError error = deserializeJson(doc, payload);
  if (!error) {
    gia_xang = doc["data"][0]["vung_1_xang_ron_95_v"];
  } else {
    Serial.println("Fuel JSON parse error");
  }
}

// Function to parse JSON for SJC gold prices
void parseGoldPrice(const String& payload) {
  DynamicJsonDocument doc(4096);
  DeserializationError error = deserializeJson(doc, payload);

  if (!error) {
    JsonArray dataArray = doc["DataList"]["Data"];
    for (JsonObject item : dataArray) {
      if (item["@n_7"] == "VÀNG MIẾNG SJC (Vàng SJC)") {
        buyPrice = item["@pb_7"].as<String>();
        sellPrice = item["@ps_7"].as<String>();
        break;
      }
    }
  } else {
    Serial.println("JSON parse error for SJC API");
  }
}

// Function to parse JSON for IP info
void parseIPInfo(const String& payload) {
  DynamicJsonDocument doc(2048);
  DeserializationError error = deserializeJson(doc, payload);
  if (!error) {
    ipAddress = doc["ip"].as<String>();
    country = doc["country"].as<String>();
    city = doc["city"].as<String>();
  } else {
    Serial.println("Error parsing IP info JSON");
  }
}

void setup() {
  Serial.begin(115200);
  lcd.init();
  lcd.backlight();

  WiFi.begin("Wokwi-GUEST", "", 6);
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }
  Serial.println(" Connected!");
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    // Fetch and parse fuel price
    String fuelPayload = httpGetRequest("https://wifeed.vn/api/du-lieu-vimo/hang-hoa/gia-xang-dau-trong-nuoc?page=1&limit=100&apikey=demo");
    parseFuelPrice(fuelPayload);

    // Fetch and parse gold price
    String goldPayload = httpGetRequest("http://api.btmc.vn/api/BTMCAPI/getpricebtmc?key=3kd8ub1llcg9t45hnoh8hmn7t5kc2v");
    parseGoldPrice(goldPayload);

    // Fetch and parse IP info
    String ipInfoPayload = httpGetRequest("https://ipinfo.io/json");
    parseIPInfo(ipInfoPayload);
  }

  // Display data on LCD
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Xang 95: ");
  lcd.print(gia_xang);

  lcd.setCursor(0, 1);
  lcd.print("SJC Buy: ");
  lcd.print(buyPrice);

  lcd.setCursor(0, 2);
  lcd.print("IP: ");
  lcd.print(ipAddress);

  lcd.setCursor(0, 3);
  lcd.print(country);
  lcd.print(", ");
  lcd.print(city);

  delay(10000); // Update every 10 seconds
}