#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>

// **Hardware Connections**
#define SS_PIN 10
#define RST_PIN 9
#define SERVO_PIN 6  // Servo connected to D6

MFRC522 mfrc522(SS_PIN, RST_PIN);
LiquidCrystal_I2C lcd(0x27, 16, 2);  // Adjust I2C address if needed
Servo gateServo;

void setup() {
    Serial.begin(9600);
    SPI.begin();
    mfrc522.PCD_Init();
    lcd.init();
    lcd.backlight();
    gateServo.attach(SERVO_PIN);

    lcd.setCursor(0, 0);
    lcd.print("Waiting for Toll");
    Serial.println("System Ready...");
}

void loop() {
    // Wait for a new RFID card
    if (!mfrc522.PICC_IsNewCardPresent() || !mfrc522.PICC_ReadCardSerial()) {
        return;
    }

    // Read UID and convert to String
    String uidStr = "";
    for (byte i = 0; i < mfrc522.uid.size; i++) {
        uidStr += String(mfrc522.uid.uidByte[i], HEX);
    }

    // Display UID and send to laptop
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("UID: " + uidStr);
    lcd.setCursor(0, 1);
    lcd.print("Validating...");

    Serial.println(uidStr); // Send UID to laptop

    // Wait for response from laptop
    String balance = "";
    while (Serial.available() == 0) {
        delay(100);  // Wait for a response
    }

    // Read response (balance amount)
    balance = Serial.readString();
    balance.trim();

    // Display balance on LCD
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Balance: Rs." + balance);

    // Open gate for 2 seconds
    gateServo.write(90);  // Open gate
    delay(2000);
    gateServo.write(0);   // Close gate

    // Reset LCD
    delay(2000);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Waiting for Toll");
}
