#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <AsyncTCP.h>
#include "LittleFS.h"

AsyncWebServer server(80);

// Archivos donde se guardan los datos
const char* ssidPath    = "/ssid.txt";
const char* passPath    = "/pass.txt";
const char* ipPath      = "/ip.txt";
const char* gatewayPath = "/gateway.txt";
const char* ipmodePath  = "/ipmode.txt";   // Nuevo parámetro

// Variables globales
String ssid, pass, ip, gateway, ipmode;
IPAddress localIP, localGateway;
IPAddress subnet(255, 255, 0, 0);

// ----------- Funciones -----------

void initLittleFS() {
  if (!LittleFS.begin(true)) {
    Serial.println("Error al montar LittleFS");
  }
}

// Leer archivo
String readFile(const char * path){
  File file = LittleFS.open(path);
  if(!file || file.isDirectory()) return String();
  return file.readStringUntil('\n');
}

// Escribir archivo
void writeFile(const char * path, const char * message){
  File file = LittleFS.open(path, FILE_WRITE);
  if(file) file.print(message);
}

// Conexión WiFi
bool connectWiFi() {
  if (ssid == "") return false;

  WiFi.mode(WIFI_STA);

  if (ipmode == "static") {
    if (ip == "" || gateway == "") {
      Serial.println("⚠️ Datos de IP estática incompletos.");
      return false;
    }
    localIP.fromString(ip.c_str());
    localGateway.fromString(gateway.c_str());

    if (!WiFi.config(localIP, localGateway, subnet)) {
      Serial.println("⚠️ Error al configurar IP estática");
      return false;
    }
    Serial.println("🔧 Modo: IP estática");
  } 
  else {
    Serial.println("🔧 Modo: DHCP (automático)");
  }

  WiFi.begin(ssid.c_str(), pass.c_str());
  unsigned long start = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - start < 10000) {
    delay(500); Serial.print(".");
  }
  Serial.println();

  return WiFi.status() == WL_CONNECTED;
}

// Inicia el WiFi Manager
void startWiFiManager() {
  initLittleFS();

  ssid    = readFile(ssidPath);
  pass    = readFile(passPath);
  ip      = readFile(ipPath);
  gateway = readFile(gatewayPath);
  ipmode  = readFile(ipmodePath);

  if(connectWiFi()) {
    Serial.println("✅ Conectado a WiFi!");
    Serial.print("IP: "); Serial.println(WiFi.localIP());
  }
  else {
    Serial.println("⚠️ No conectado. Creando AP...");
    WiFi.softAP("ElProfe-WIFI-MANAGER", NULL);
    Serial.print("IP del AP: "); Serial.println(WiFi.softAPIP());

    server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
      request->send(LittleFS, "/wifimanager.html", "text/html");
    });

    server.on("/", HTTP_POST, [](AsyncWebServerRequest *request){
      int params = request->params();
      for(int i=0;i<params;i++){
        const AsyncWebParameter* p = request->getParam(i);
        if(p->isPost()){
          if (p->name() == "ssid")    { ssid = p->value(); writeFile(ssidPath, ssid.c_str()); }
          if (p->name() == "pass")    { pass = p->value(); writeFile(passPath, pass.c_str()); }
          if (p->name() == "ip")      { ip   = p->value(); writeFile(ipPath, ip.c_str()); }
          if (p->name() == "gateway") { gateway = p->value(); writeFile(gatewayPath, gateway.c_str()); }
          if (p->name() == "ipmode")  { ipmode = p->value(); writeFile(ipmodePath, ipmode.c_str()); }
        }
      }
      request->send(200, "text/plain", "Datos guardados. Reiniciando...");
      delay(2000);
      ESP.restart();
    });

    server.begin();
  }
}
