#include <Wire.h> // Include the Wire library for I2C communication
#include <LiquidCrystal_I2C.h> // Include the LiquidCrystal_I2C library for LCD
#include <RTClib.h> // Include the RTClib library for RTC

#define BUTTON_PIN 2 // Define the pin for the push button
#define LED_PIN 13 // Define the pin for the LED
#define BUZZER_PIN 12 // Define the pin for the buzzer

LiquidCrystal_I2C lcd(0x27, 16, 2); // Initialize the LCD with I2C address 0x27, 16 columns, and 2 rows
RTC_DS1307 rtc; // Create an RTC object

bool reminderActive = false; // Flag to track if reminder is active

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP); // Set push button pin as input with internal pull-up resistor
  pinMode(LED_PIN, OUTPUT); // Set LED pin as output
  pinMode(BUZZER_PIN, OUTPUT); // Set buzzer pin as output

  Serial.begin(9600); // Start serial communication for debugging

  if (!rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (!rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // Uncomment the following line to set the date and time
    // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }

  lcd.init(); // Initialize the LCD
  lcd.backlight(); // Turn on the backlight
}

void loop() {
  DateTime now = rtc.now(); // Read the current time from the RTC module

  int hour = now.hour(); // Extract the current hour
  int minute = now.minute(); // Extract the current minute

  // Check if it's time for medication reminder (for demonstration, set at 15:41)
  if (hour == 15 && minute == 46 && !reminderActive) {
    displayReminder("Time to take", "medication bro!");
    activateReminder();
  }

  // Check if the button is pressed to stop the reminder
  if (digitalRead(BUTTON_PIN) == LOW && reminderActive) {
    stopReminder();
  }

  delay(1000); // Delay for stability
}

void displayReminder(String line1, String line2) {
  lcd.clear(); // Clear the LCD
  lcd.setCursor(0, 0); // Set cursor to first column, first row
  lcd.print(line1); // Print the first line of the message
  lcd.setCursor(0, 1); // Set cursor to first column, second row
  lcd.print(line2); // Print the second line of the message
  reminderActive = true; // Set the reminder active flag
}

void activateReminder() {
  digitalWrite(LED_PIN, HIGH); // Turn on the LED
  tone(BUZZER_PIN, 1000); // Activate the buzzer
  delay(5000); // Keep the buzzer and LED active for 5 seconds
}

void stopReminder() {
  noTone(BUZZER_PIN); // Turn off the buzzer
  digitalWrite(LED_PIN, LOW); // Turn off the LED
  lcd.clear(); // Clear the LCD
  reminderActive = false; // Reset the reminder active flag
}
GND5VSDASCLSQWRTCDS1307+