#include <SPI.h>
#include <MFRC522.h>
#include <ESP32Servo.h>

#define SS_PIN 5
#define RST_PIN 22
#define SERVO_PIN 13

MFRC522 rfid(SS_PIN, RST_PIN);
Servo doorServo;

String allowedUID = "A71937";   // ← paste your card UID here

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

  SPI.begin(18, 19, 23, 5);
  rfid.PCD_Init();

  doorServo.attach(SERVO_PIN);
  doorServo.write(0);   // Door closed position

  Serial.println("RFID Door Lock Ready...");
}

void loop() {

  if (!rfid.PICC_IsNewCardPresent()) return;
  if (!rfid.PICC_ReadCardSerial()) return;

  String scannedUID = "";

  for (byte i = 0; i < rfid.uid.size; i++) {
    scannedUID += String(rfid.uid.uidByte[i], HEX);
  }

  scannedUID.toUpperCase();

  Serial.print("Scanned UID: ");
  Serial.println(scannedUID);

  if (scannedUID == allowedUID) {
    Serial.println("Access Granted - Door Opening");

    doorServo.write(90);   // Open door
    delay(5000);           // Door open time

    doorServo.write(0);    // Close door
    Serial.println("Door Closed");
  }
  else {
    Serial.println("Access Denied");
  }

  rfid.PICC_HaltA();
}