// module RFID RC522

// carte esp32c3

// Ce que le programme fait :
// Il initialise le module RC522 et demarre la communication SPI.
// Lorsque vous approchez un porte-cle ou une carte RFID du module, il lit l'ID unique et l'affiche sur la page web

#include <WiFi.h>
#include <WebServer.h>
#include <WebSocketsServer.h>
#include <SPI.h>
#include <MFRC522.h>

// Configuration SPI pour ESP32-C3
#define SS_PIN 5    
#define RST_PIN 2   
#define SCK 6
#define MISO 4
#define MOSI 7

// Connexion WiFi
const char* ssid = "XXXX";          // Remplace par ton reseau WiFi
const char* password = "XXXX";  // Remplace par ton mot de passe

WebServer server(80);
WebSocketsServer webSocket(81);

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Instance du module RFID

// Page Web avec historique des cartes
void handleRoot() {
  server.send(200, "text/html", R"rawliteral(
  <!DOCTYPE html>
  <html>
  <head>
    <title>ESP32 RFID</title>
    <script>
      var ws = new WebSocket("ws://" + location.hostname + ":81/");
      ws.onmessage = function(event) {
        var newItem = document.createElement("li");
        newItem.textContent = event.data;
        document.getElementById("history").prepend(newItem);  // Ajoute en haut de la liste
      };
    </script>
  </head>
  <body>
    <h1>Lecteur RFID ESP32-C3</h1>
    <h2>Cartes lues :</h2>
    <ul id="history"></ul>
  </body>
  </html>
  )rawliteral");
}

void setup() {
  Serial.begin(115200);
  SPI.begin(SCK, MISO, MOSI, SS_PIN);
  mfrc522.PCD_Init();

  WiFi.begin(ssid, password);
  Serial.print("Connexion a ");
  Serial.println(ssid);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("\nConnecte au WiFi !");
  Serial.print("Adresse IP : ");
  Serial.println(WiFi.localIP());

  server.on("/", handleRoot);
  server.begin();
  webSocket.begin();
}

void loop() {
  server.handleClient();
  webSocket.loop();

  if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
    String id = "";
    for (byte i = 0; i < mfrc522.uid.size; i++) {
      id += String(mfrc522.uid.uidByte[i], HEX) + " ";
    }
    Serial.println("Carte detectee : " + id);
    webSocket.broadcastTXT(id);

    mfrc522.PICC_HaltA();
    mfrc522.PCD_StopCrypto1();
  }
}