#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

#define BUTTON1_PIN 12 // Pin for button 1
#define BUTTON2_PIN 14 // Pin for button 2

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET    -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

const char* stages[] = {
  "Raw Materials",
  "Manufacturing",
  "Distribution",
  "Retail",
  "Consumer"
};

int currentStage = 0;
bool button1Pressed = false;
bool button2Pressed = false;

void setup() {
  Serial.begin(115200); // Initialize Serial communication for debugging

  // Initialize the OLED display with the correct I2C address
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Use 0x3C or 0x3D
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Stay in an infinite loop if allocation fails
  }

  // Initialize the buttons
  pinMode(BUTTON1_PIN, INPUT_PULLUP);
  pinMode(BUTTON2_PIN, INPUT_PULLUP);

  display.display();
  delay(2000); // Pause for 2 seconds

  // Clear the buffer
  display.clearDisplay();
  display.setTextSize(2);      // Normal 1:1 pixel scale
  display.setTextColor(SSD1306_WHITE); // Draw white text
  display.setCursor(0, 10);     // Start at top-left corner
  display.cp437(true);         // Use full 256 char 'Code Page 437' font

  updateDisplay();
}

void loop() {
  if (digitalRead(BUTTON1_PIN) == LOW) {
    if (!button1Pressed) {
      button1Pressed = true;
      advanceStage();
    }
  } else {
    button1Pressed = false;
  }

  if (digitalRead(BUTTON2_PIN) == LOW) {
    if (!button2Pressed) {
      button2Pressed = true;
      resetStage();
    }
  } else {
    button2Pressed = false;
  }
}

void updateDisplay() {
  display.clearDisplay();
  display.setCursor(0, 10);
  display.print(stages[currentStage]);
  display.display();
}

void advanceStage() {
  currentStage++;
  if (currentStage >= 5) {
    currentStage = 0;
  }
  updateDisplay();
}

void resetStage() {
  currentStage = 0;
  updateDisplay();
}