#include <WiFi.h>
#include <DHTesp.h>
#include <NewPing.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mysql_server = "sql5.freesqldatabase.com";  // MySQL server IP address
const char* mysql_user = "sql5716755";
const char* mysql_password = "W4yCNbwbLx";
const char* mysql_database = "sql5716755";

IPAddress serverAddr(54, 84, 79, 252); // Convert MySQL server IP address to IPAddress object

const int TRIGGER_PIN = 4;
const int ECHO_PIN = 5;
const int MAX_DISTANCE = 200;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

const int PIR_PIN = 14;
const int DHT_PIN = 15;
DHTesp dht;

WiFiClient espClient;
MySQL_Connection conn((Client *)&espClient);

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void setup_mysql() {
  Serial.println("Connecting to MySQL...");
  if (conn.connect(serverAddr, 3306, (char*)mysql_user, (char*)mysql_password, (char*)mysql_database)) {
    Serial.println("MySQL connected");
  } else {
    Serial.println("MySQL connection failed");
  }
}

void setup() {
  pinMode(PIR_PIN, INPUT);
  Serial.begin(115200);
  setup_wifi();
  setup_mysql();
  dht.setup(DHT_PIN, DHTesp::DHT22);
}

void insert_data(float temperature, float humidity, int distance) {
  MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
  char INSERT_SQL[128];
  sprintf(INSERT_SQL, "INSERT INTO sensores (CodReg, device, a0, a1, a2, a3) VALUES (\"\",\"hw01\",%f, %f, %d,999)", temperature, humidity, distance);
  cur_mem->execute(INSERT_SQL);
  cur_mem->close();
  delete cur_mem;
}

void loop() {
  TempAndHumidity data = dht.getTempAndHumidity();
  int distance = sonar.ping_cm();

  if (digitalRead(PIR_PIN) == HIGH) {
    insert_data(data.temperature, data.humidity, distance);
    Serial.println("Data inserted into MySQL database");
    Serial.print("Temperature: ");
    Serial.println(data.temperature);
    Serial.print("Humidity: ");
    Serial.println(data.humidity);
    Serial.print("Distance: ");
    Serial.println(distance);
  }

  delay(5000); // Insert data every 5 seconds (adjust as needed)
}