#include <WiFi.h>
#include <HTTPClient.h>
#include<SPI.h>
#include <MFRC522.h>
#define SS_PIN 5
#define RST_PIN 9//not used for esp32
byte readCard[4];
MFRC522 mfrc522(SS_PIN, RST_PIN);

const char* ssid     = "TL";
const char* password = "a6de45eae0632f44de6a92511e";
const char* serverName = "https://informatik.hs-bremerhaven.de/online/qrcorona/weiterverarbeiten.php";

int freq = 2000;
int channel = 0;
int resolution = 8;


void sendData(String key) {
  HTTPClient http;
  http.begin(serverName);
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");
  String httpRequestData = String("roomname=TestRaum&fromtime=12:34&totime=12:35&qr="+key);
  int httpResponseCode = http.POST(httpRequestData);
  Serial.println(httpResponseCode);
}

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

  Serial.println();
  Serial.print("Verbinde zu: ");
  Serial.println(ssid);



// Bring Up Wifi
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("IP: ");
  Serial.println(WiFi.localIP());

// init RFID
  SPI.begin();       
  mfrc522.PCD_Init();

// Piep
//  ledcSetup(channel, freq, resolution);
//  ledcAttachPin(27, channel);
//  for (int i = 0; i<20000; i=i+100){
//    ledcWriteTone(channel, i);
//    Serial.println(i);
//    delay(200);
//  }


}

void loop() {
  if(WiFi.status()== WL_CONNECTED){
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
      return;
     }
    if ( ! mfrc522.PICC_ReadCardSerial()) { 
      return;
    }
    String CardID="";
    Serial.println(F("Scanned PICC's UID:"));
    for ( uint8_t i = 0; i < 4; i++) {
      readCard[i] = mfrc522.uid.uidByte[i];
      Serial.print(readCard[i], HEX);
      CardID=CardID+String(readCard[i], HEX);
    }
    sendData(CardID);
    Serial.println("");
    mfrc522.PICC_HaltA();
  }
}