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

LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo lockServo;

int buttons[4] = {2, 3, 4, 5};
int password[4] = {1, 2, 3, 4};
int entered[4];
int indexPos = 0;

const int buzzer = 9;
const int servoPin = 6;

void setup() {
  // LCD
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("SMART SAFE BOX");
  lcd.setCursor(0, 1);
  lcd.print("ENTER CODE...");
  delay(1500);
  lcd.clear();

  // Buttons
  for (int i = 0; i < 4; i++)
    pinMode(buttons[i], INPUT_PULLUP);

  // Servo
  lockServo.attach(servoPin);
  lockServo.write(0);  // locked

  // Buzzer
  pinMode(buzzer, OUTPUT);
}

bool checkPassword() {
  for (int i = 0; i < 4; i++) {
    if (entered[i] != password[i]) return false;
  }
  return true;
}

void loop() {
  lcd.setCursor(0, 0);
  lcd.print("ENTER CODE:    ");
  lcd.setCursor(0, 1);
  lcd.print("Keys: ");
  lcd.print(indexPos);
  lcd.print("     ");

  for (int i = 0; i < 4; i++) {
    if (digitalRead(buttons[i]) == LOW) {
      delay(200);
      entered[indexPos] = i + 1;
      indexPos++;

      if (indexPos == 4) {
        lcd.clear();
        if (checkPassword()) {
          lcd.setCursor(0, 0);
          lcd.print("CORRECT CODE!");
          lcd.setCursor(0, 1);
          lcd.print("SAFE UNLOCKED");
          lockServo.write(90);  // unlock
        } else {
          lcd.setCursor(0, 0);
          lcd.print("WRONG CODE");
          lcd.setCursor(0, 1);
          lcd.print("ACCESS DENIED");
          tone(buzzer, 600, 400);
          lockServo.write(0); // ensure locked
        }

        delay(2000);
        lcd.clear();
        indexPos = 0;
      }
    }
  }
}
