/* Pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      ESP32C6
*             Reader/PCD    Feather
 * Signal      Pin          Pin
 * -----------------------------------------------------------------------------------------
 * SPI SS 1    SDA(SS)      SDA/4
 * SPI SCK     SCK          SCK
 * SPI MOSI    MOSI         MOSI
 * SPI MISO    MISO         MISO
 *
 */

#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <HTTPClient.h>

#include <MFRC522v2.h> // https://github.com/OSSLibraries/Arduino_MFRC522v2
#include <MFRC522DriverSPI.h>
#include <MFRC522DriverPinSimple.h>
#include <MFRC522Debug.h>

#define SS_PIN SDA
#define DEBUG

const int RED_PIN = 5;
const int GREEN_PIN = 6;
const int BLUE_PIN = 7;


MFRC522DriverPinSimple ss_1_pin(SS_PIN); // Configurable, take an unused pin, only HIGH/LOW required, must be different to SS 2.
MFRC522DriverSPI driver_1{ss_1_pin};
MFRC522 reader{driver_1};   // Create MFRC522 instance.

const char *rootCACertificate = R"string_literal(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U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TDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
)string_literal";

void read_card(char reader_uid[]);
void send_uid(char reader_uid[]);

void setup() {
  #ifdef DEBUG
    Serial.begin(115200);
    while (!Serial) delay(10);
  #endif

  reader.PCD_Init(); // Init each MFRC522 card.
  #ifdef DEBUG
    MFRC522Debug::PCD_DumpVersionToSerial(reader, Serial);	// Show details of PCD - MFRC522 Card Reader details.
  #endif
}

void loop() {
  if (reader.PICC_IsNewCardPresent() && reader.PICC_ReadCardSerial()) {
    char reader_uid[32] = "";
    readCard(reader_uid);
    sendUid(reader_uid);
  }
  else {
    delay(200);
  }
}

void readCard(char reader_uid[]) {
  reader.PICC_HaltA();
  reader.PCD_StopCrypto1();
  byte_to_string(reader.uid.uidByte, 4, reader_uid);
  #ifdef DEBUG
    Serial.println(reader_uid);
  #endif
  displaySuccess();
}

void sendUid(char reader_uid[]) {
  connectToWifi();
  postUid(reader_uid);
}

void connectToWifi() {
  WiFiManager wm;
  bool res;
  res = wm.autoConnect("KLUK"); // password protected ap

  if(!res) {
    #ifdef DEBUG
      Serial.println("Failed to connect");
    #endif
    displayError();
    // ESP.restart();
  } 
  else {
    //if you get here you have connected to the WiFi    
    #ifdef DEBUG
    Serial.println("connected...yeey :)");
    #endif
  }
}
void postUid(char reader_uid[]) {
  NetworkClientSecure *client = new NetworkClientSecure;
  client->setCACert(rootCACertificate);
  HTTPClient https;
  #ifdef DEBUG
    Serial.print("[HTTPS] begin...\n");
  #endif
  // configure traged server and url
  https.begin("https://robi.kluk.fr/rfid_tags");  // HTTP
  https.addHeader("Content-Type", "application/json");

  // start connection and send HTTP header and body
  int httpCode = https.POST("{\"identifier\":\"" + String(reader_uid) + "\"}");
  #ifdef DEBUG
    Serial.print("httpCode: ");
    Serial.println(httpCode);
  #endif

  if (httpCode > 0) {
    if (httpCode == HTTP_CODE_CREATED) {
    } else {
      #ifdef DEBUG
        Serial.println("Remote error while sending uid");
      #endif
      displayError();
    }
  } else {
      #ifdef DEBUG
        Serial.print("Remote error while sending uid");
      #endif
      displayError();
  }

  https.end();
  #ifdef DEBUG
    Serial.print("[HTTPS] ended...\n");
  #endif
}

void byte_to_string(byte array[], unsigned int len, char buffer[]) {
  for (unsigned int i = 0; i < len; i++)
  {
    byte nib1 = (array[i] >> 4) & 0x0F;
    byte nib2 = (array[i] >> 0) & 0x0F;
    buffer[i*2+0] = nib1  < 0xA ? '0' + nib1  : 'A' + nib1  - 0xA;
    buffer[i*2+1] = nib2  < 0xA ? '0' + nib2  : 'A' + nib2  - 0xA;
  }
  buffer[len*2] = '\0';
}

void displayError() {
  analogWrite(RED_PIN, 200);
  delay(1000);
  analogWrite(RED_PIN, 0);
}

void displaySuccess() {
  analogWrite(GREEN_PIN, 200);
  delay(1000);
  analogWrite(GREEN_PIN, 0);
}
