#include <WiFi.h>
#include <DNSServer.h>
#include <Arduino.h>
#include "config.h"

static DNSServer dnsServer;

static void onWifiEvent(WiFiEvent_t event, WiFiEventInfo_t info) {
    switch (event) {
        case ARDUINO_EVENT_WIFI_AP_STACONNECTED:
            Serial.printf("[WiFi] Client connecté   — MAC %02X:%02X:%02X:%02X:%02X:%02X  clients: %d\n",
                          info.wifi_ap_staconnected.mac[0], info.wifi_ap_staconnected.mac[1],
                          info.wifi_ap_staconnected.mac[2], info.wifi_ap_staconnected.mac[3],
                          info.wifi_ap_staconnected.mac[4], info.wifi_ap_staconnected.mac[5],
                          WiFi.softAPgetStationNum());
            break;
        case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED:
            Serial.printf("[WiFi] Client déconnecté — MAC %02X:%02X:%02X:%02X:%02X:%02X  clients: %d\n",
                          info.wifi_ap_stadisconnected.mac[0], info.wifi_ap_stadisconnected.mac[1],
                          info.wifi_ap_stadisconnected.mac[2], info.wifi_ap_stadisconnected.mac[3],
                          info.wifi_ap_stadisconnected.mac[4], info.wifi_ap_stadisconnected.mac[5],
                          WiFi.softAPgetStationNum());
            break;
        default:
            break;
    }
}

void demarrerWifi() {
    WiFi.onEvent(onWifiEvent);
    WiFi.mode(WIFI_AP);
    WiFi.softAPConfig(WIFI_IP, WIFI_GATEWAY, WIFI_SUBNET);

    if (strlen(WIFI_PASSWORD) > 0) {
        WiFi.softAP(WIFI_SSID, WIFI_PASSWORD);
    } else {
        WiFi.softAP(WIFI_SSID);  // AP ouvert
    }

    Serial.printf("[WiFi] AP démarré — SSID: %s  IP: %s  MAC: %s\n",
                  WIFI_SSID,
                  WiFi.softAPIP().toString().c_str(),
                  WiFi.softAPmacAddress().c_str());

    // Captive portal : tous les noms DNS → 192.168.4.1
    dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
    dnsServer.start(53, "*", WIFI_IP);
    Serial.println("[WiFi] DNS captive portal démarré (port 53)");
}

void traiterDNS() {
    dnsServer.processNextRequest();
}
