#include <DHT.h>
#include <ESP32Servo.h>
#include <WiFi.h>
#include "ThingSpeak.h"
#include <HTTPClient.h>
#include <UrlEncode.h>

const char* WIFI_NAME = "Wokwi-GUEST";
const char* WIFI_PASS = "";
const int myChannelNumber = 2550097;
const char* write_API_Key = "QI0F26NW2L4QVW4K";
const char* server = "api.thingspeak.com";
WiFiClient client;

float temperature = 0;
float humidity = 0;
int potentiometerValue = 0;

const float GAMMA = 0.7;
const float RL10 = 50;
int luminosite = 0;

#define DHTPIN 12            
#define DHTTYPE DHT22        

#define LDRPIN 33 
#define LED_BAR_GRAPH_1 23   
#define LED_BAR_GRAPH_2 22   
#define LED_BAR_GRAPH_3 21   
#define LED_BAR_GRAPH_4 19   
#define RGB_R 25             
#define RGB_G 27             
#define RGB_B 26             
#define SERVO_PIN 13         
#define POTENTIOMETER_PIN 35 

DHT dht(DHTPIN, DHTTYPE);
Servo servo;

float co2Threshold = 350;
float temperatureThreshold = 30;

String phoneNumber = "212705489106";
String apiKey = "2663452";

void sendMessage(String message){
  String url = "https://api.callmebot.com/whatsapp.php?phone=" + phoneNumber + "&apikey=" + apiKey + "&text=" + urlEncode(message);
  
  HTTPClient http;
  
  http.begin(url);
  
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");

  int httpResponseCode = http.POST(url);

  if (httpResponseCode == 200) {
    Serial.println("Message sent successfully");
  } else {
    Serial.println("Error sending the message");
    Serial.print("HTTP response code: ");
    Serial.println(httpResponseCode);
  }
  
  http.end();
}

void setup() {
  Serial.begin(9600);

  connecte_WIFI();

  pinMode(LDRPIN, INPUT);

  pinMode(RGB_R, OUTPUT);
  pinMode(RGB_G, OUTPUT);
  pinMode(RGB_B, OUTPUT);

  pinMode(LED_BAR_GRAPH_1, OUTPUT);
  pinMode(LED_BAR_GRAPH_2, OUTPUT);
  pinMode(LED_BAR_GRAPH_3, OUTPUT);
  pinMode(LED_BAR_GRAPH_4, OUTPUT);

  servo.attach(SERVO_PIN);
  servo.write(90);
}

void connecte_WIFI(){
  WiFi.begin(WIFI_NAME, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Wifi not connected");
  }
  Serial.println("Wifi connected!");
  Serial.println("Local IP: " + String(WiFi.localIP()));
  WiFi.mode(WIFI_STA);
  ThingSpeak.begin(client);

  Serial.println("Setup finished");
  Serial.println("---");
}

void loop() {

  // Scenario 1: CO2 élevé
  potentiometerValue = analogRead(POTENTIOMETER_PIN);
  potentiometerValue = map(potentiometerValue, 0, 4095, 0, 1000);

  Serial.print("Valeur de CO2 : ");
  Serial.print(potentiometerValue);
  Serial.println(" ppm");

  if (potentiometerValue > co2Threshold) {
    servo.write(180); 
    sendMessage("WARNING, A DANGER IS DETECTED !");
  }else{
    servo.write(90);
  }

  // Scenario 2: Température
  temperature = dht.readTemperature();
  humidity = dht.readHumidity();

  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.println(" °C");

  Serial.print("Humidity: ");
  Serial.print(humidity);
  Serial.println(" %");

  if (temperature > temperatureThreshold) {
    digitalWrite(RGB_R, HIGH);
    digitalWrite(RGB_G, HIGH);
    digitalWrite(RGB_B, LOW);
  } else if (temperature < temperatureThreshold) {
    digitalWrite(RGB_R, LOW);
    digitalWrite(RGB_G, HIGH);
    digitalWrite(RGB_B, HIGH);
  }

  // Scenario 3: Luminosité
  luminosite = analogRead(LDRPIN);
  float voltage = luminosite * 5/4095.0;
  float resistance = 2000 * voltage / (1 - voltage / 5);
  luminosite = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
  Serial.print("Luminosité: ");
  Serial.print(luminosite);
  Serial.println(" lux");

  if (luminosite < 1000) {
    digitalWrite(LED_BAR_GRAPH_1, HIGH);
    digitalWrite(LED_BAR_GRAPH_2, LOW);
    digitalWrite(LED_BAR_GRAPH_3, LOW);
    digitalWrite(LED_BAR_GRAPH_4, LOW);
  } else if ((luminosite >= 1000) && (luminosite < 2500)) {
    digitalWrite(LED_BAR_GRAPH_1, HIGH);
    digitalWrite(LED_BAR_GRAPH_2, HIGH);
    digitalWrite(LED_BAR_GRAPH_3, LOW);
    digitalWrite(LED_BAR_GRAPH_4, LOW);
  } else if ((luminosite >= 2500) && (luminosite < 4000)) {
    digitalWrite(LED_BAR_GRAPH_1, HIGH);
    digitalWrite(LED_BAR_GRAPH_2, HIGH);
    digitalWrite(LED_BAR_GRAPH_3, HIGH);
    digitalWrite(LED_BAR_GRAPH_4, LOW);
  } else {
    digitalWrite(LED_BAR_GRAPH_1, HIGH);
    digitalWrite(LED_BAR_GRAPH_2, HIGH);
    digitalWrite(LED_BAR_GRAPH_3, HIGH);
    digitalWrite(LED_BAR_GRAPH_4, HIGH);
  }

  delay(1000);

  sendDataToThingSpeak();
}

void sendDataToThingSpeak() {
  ThingSpeak.setField(1, temperature);
  delay(500);
  ThingSpeak.setField(2, humidity);
  delay(500);
  ThingSpeak.setField(3, potentiometerValue);
  delay(500);
  ThingSpeak.setField(4, luminosite);
  delay(500);

  int writeResult = ThingSpeak.writeFields(myChannelNumber, write_API_Key);

  if (writeResult == 200) {
    Serial.println("Data pushed successfully");
  } else {
    Serial.println("Push error: " + String(writeResult));
  }
  Serial.println("---");
}
$abcdeabcde151015202530354045505560fghijfghij