void checkForUpdates();
void performOTA();

void checkForUpdates() {
  Serial.println("Checking for firmware updates...");

  // Step 1: Check the current version on the server
  HTTPClient http;
  http.begin(versionUrl);
  int httpCode = http.GET();

  if (httpCode == HTTP_CODE_OK) {
    String newVersionStr = http.getString();
    float newVersion = newVersionStr.toFloat();

    Serial.printf("Current version: %.1f, Available version: %.1f\n", currentVersion, newVersion);

    // Step 2: Compare the version
    if (newVersion > currentVersion) {
      Serial.println("New version available. Starting update...");
      performOTA();  // Perform the OTA update if a new version is found
    } else {
      Serial.println("No new version available.");
    }
  } else {
    Serial.printf("Failed to retrieve version. HTTP error code: %d\n", httpCode);
  }
  http.end();
}

void performOTA() {
  HTTPClient http;
  http.begin(firmwareUrl);
  int httpCode = http.GET();

  if (httpCode == HTTP_CODE_OK) {
    int contentLength = http.getSize();
    if (contentLength > 0) {
      bool canBegin = Update.begin(contentLength);
      if (canBegin) {
        Serial.println("Starting OTA update...");
        WiFiClient *client = http.getStreamPtr();
        size_t written = Update.writeStream(*client);
        if (written == contentLength) {
          Serial.println("Update complete");
          if (Update.end()) {
            Serial.println("Update successfully finished. Rebooting...");
            ESP.restart();  // Reboot to apply the update
          } else {
            Serial.printf("Update failed: %s\n", Update.errorString());
          }
        } else {
          Serial.println("Update failed: Written size mismatch.");
        }
      } else {
        Serial.println("Not enough space for update.");
      }
    } else {
      Serial.println("Firmware file is empty.");
    }
  } else {
    Serial.printf("Firmware HTTP error code: %d\n", httpCode);
  }
  http.end();
}
