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

// WiFi credentials
const char *ssid = "Wokwi-GUEST";
const char *password = "";

// Server and user configuration
const char *serverUrl = "https://453ae019-998b-497b-b918-0b4a57654fed-00-23cv9cviuplc.pike.replit.dev/predict/?";
const char *userName = "atharva";

// Analog pin assignments
const int nirPin = 12; // NIR sensor pin
const int bpmPin = 14; // BPM sensor pin
const int spoPin = 27; // SpO2 sensor pin

// Variables for sensor values
float nirValue = 0.0;  // NIR value in mg/dL
int bpmValue = 0;      // BPM value in beats per minute
int spoValue = 0;      // SpO2 value in percentage

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

  // Initialize WiFi connection
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
}

void makeGetRequest() {
  HTTPClient http;

  // Create the URL with sensor values
  String url = String(serverUrl) +
               "?NodeName=" + userName +
               "&nir=" + nirValue +
               "&bpm=" + bpmValue +
               "&spo=" + spoValue;

  Serial.println("Sending GET request to: " + url);

  // Send the GET request
  http.begin(url);
  int httpCode = http.GET();

  // Handle response
  if (httpCode > 0) {
    Serial.printf("HTTP response code: %d\n", httpCode);
    String payload = http.getString();
    Serial.println("Server response: " + payload);
  } else {
    Serial.printf("HTTP request failed, error: %s\n", http.errorToString(httpCode).c_str());
  }

  http.end();
}

void loop() {
  // Read raw analog values
  int rawNir = analogRead(nirPin);
  int rawBpm = analogRead(bpmPin);
  int rawSpo = analogRead(spoPin);

  // Map raw sensor values to meaningful units
  nirValue = map(rawNir, 0, 4095, 0, 300) / 10.0; // Convert to mg/dL (e.g., range 0.0 - 30.0 mg/dL)
  bpmValue = map(rawBpm, 0, 4095, 40, 180);       // Convert to beats per minute (range 40-180 BPM)
  spoValue = map(rawSpo, 0, 4095, 90, 100);       // Convert to percentage (range 90%-100%)

  // Print sensor values to serial monitor with units
  Serial.printf("NIR: %.1f mg/dL, BPM: %d per min, SpO2: %d%%\n", nirValue, bpmValue, spoValue);

  // Make the API call
  makeGetRequest();

  // Delay for 20 seconds
  delay(20000);
}