#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* localtunnelURL = "https://loose-onions-shake.loca.lt/iot/saveDB.php"; // LocalTunnel URL

int can = 3;
String number = "1234"; // random number
String numberTemp = "****";

int currentNumber = 0; // Active number

const int incButton = 26;
const int decButton = 27;
const int predictButton = 14;

HTTPClient http;

String tmp = ""; // "1***"

int numberArrCounter = 0; // Which indexed we are?
void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }

  Serial.println("Connected to WiFi");
  pinMode(incButton, INPUT);
  pinMode(decButton, INPUT);
  pinMode(predictButton, INPUT);

  Serial.begin(115200);
}

void loop() {

  if (digitalRead(incButton))
  {
    // Serial.println("incButton: pressed");
    if (currentNumber < 9)
    {
      currentNumber += 1;
    }
    Serial.println(currentNumber);
    delay(200);
  }
  else if (digitalRead(decButton) )
  {
    // Serial.println("decButton: pressed");
    if (currentNumber > 0) {
      currentNumber -= 1;
    }
    Serial.println(currentNumber);
    delay(200);
  }
  else if (digitalRead(predictButton))
  {
    // Serial.println("predictButton: pressed");
    if (String(currentNumber) == String(number[numberArrCounter]))
    {
      Serial.println("Dogru cevap");
      if (numberArrCounter < 4)
      {
        numberArrCounter += 1;
        tmp = getNumber(numberArrCounter);
        numberTemp=tmp;
        Serial.println(tmp);
        can = 3;
        // Serial.println("numberArrcounter:");
        // Serial.println(numberArrCounter);
      }
    }
    else if (String(currentNumber) != String(number[numberArrCounter]))
    {
      Serial.println("Yanlıs cevap");
      if (can > 0)
      {
        can -= 1;
        Serial.printf("Can: %d", (can + 1));
      }
      else if (can == 0)
      {
        Serial.println("Can kalmadı!!");
      }
    }
    delay(200);
  }
  String sndValue = "https://loose-onions-shake.loca.lt/iot/saveDB.php?can=" + String(can) + "&index=" + String(numberArrCounter) + "&tmp=" + String(numberTemp) + "&randomNumber=" + number + "&currentNumber=" + String(currentNumber);
  http.begin(sndValue);
  http.GET();
  http.addHeader("Bypass-Tunnel-Reminder", "true");
  delay(1000);
}
String getNumber(int index) {
  String tempNumber = "";
  for (int i = 0; i < 4; i++)
  {
    if (i < index)
    {
      tempNumber += String(number[i]);
    }
    else {
      tempNumber += "*";
    }
  }
  return tempNumber;
}