#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

const char* ssid = "OPPO";
const char* password = "123456789";

WiFiServer server(80);

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

  //  ADD THIS LINE (CUSTOM I2C PINS)
  Wire.begin(6, 7);   // SDA = GPIO6, SCL = GPIO7

  // OLED init
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println("OLED failed");
    while(1);
  }

  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);

  // WiFi connect
  WiFi.begin(ssid, password);
  displayMessage("Connecting WiFi...");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

  displayMessage("WiFi Connected");

  Serial.println("Connected!");
  Serial.print("Server IP: ");
  Serial.println(WiFi.localIP());

  displayMessage("IP:\n" + WiFi.localIP().toString());

  server.begin();
}

void loop() {
  WiFiClient client = server.available();

  if (client) {
    displayMessage("Client Connected");

    while (client.connected()) {

      // Receive message
      if (client.available()) {
        String msg = client.readStringUntil('\n');
        Serial.println("Recv: " + msg);
        displayMessage("Recv:\n" + msg);
      }

      // Send message
      if (Serial.available()) {
        String input = Serial.readStringUntil('\n');
        client.println(input);
        displayMessage("Me:\n" + input);
      }
    }

    client.stop();
    displayMessage("Client Disconnected");
  }
}

// OLED display function
void displayMessage(String msg) {
  display.clearDisplay();
  display.setCursor(0, 10);
  display.println(msg);
  display.display();
}