#include <WiFiNINA.h>

char ssid[] = "";      // your network SSID (name)
char pass[] = "";  // your network password
int status = WL_IDLE_STATUS;         // the WiFi radio's status

char server[] = "192.168.17.164"; // Replace with your Raspberry Pi's IP address

WiFiClient client;

void setup() {
  Serial.begin(9600);
  
  // Check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    while (true);
  }

  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    delay(10000);
  }
  Serial.println("Connected to WiFi!");
  Serial.println("Enter name to add a user");
}

void loop() {
  if (Serial.available()) {
    String input = Serial.readStringUntil('\n');
    int separator1 = input.indexOf(';');
    int separator2 = input.lastIndexOf(';');
    
    if(separator1 != -1 && separator2 != -1 && separator1 != separator2) {
      String lid = input.substring(0, separator1);
      String username = input.substring(separator1 + 1, separator2);
      String email = input.substring(separator2 + 1);
      addUser(lid, username, email);
    }
    else {
      Serial.println("Invalid format. Please enter in the format: lid;username;email");
    }
  }
}

String urlEncode(const String &s) {
  const char *hex = "Your hex";
  String encoded = "";
  
  for (char c : s) {
    if ('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9') {
      encoded += c;
    } else {
      encoded += '%';
      encoded += hex[c >> 4];
      encoded += hex[c & 15];
    }
  }
  return encoded;
}

void addUser(String lid, String username, String email) {
  if (client.connect(server, 80)) {
    Serial.println("Connected to server!");

    String encodedLid = urlEncode(lid);
    String encodedName = urlEncode(username);
    String encodedEmail = urlEncode(email);
    String url = "/add_user.php?lid=" + encodedLid + "&name=" + encodedName + "&email=" + encodedEmail;

    client.print("GET ");
    client.print(url);
    client.println(" HTTP/1.1");
    client.println("Host: " + String(server));
    client.println("Connection: close");
    client.println();

    while(client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.print(c);
      }
    }
    client.stop();
  } else {
    Serial.println("Failed to connect to server");
  }
}