#include <WiFi.h>
#include <ESP_Mail_Client.h>

// WiFi configuration
#define WIFI_SSID "YUVARAJSWIFI"
#define WIFI_PASSWORD "12345678"

// SMTP server configuration
#define SMTP_server "smtp.gmail.com"
#define SMTP_Port 465

// Sender email credentials
#define sender_email "yuvrajfortestandrewards@gmail.com"
#define sender_password "yyygwljiplvytunh"

// Recipient email address
#define Recipient_email "yuvrajkaniyar@gmail.com"
#define Recipient_name "Yuvraj"

// Create an SMTPSession instance
SMTPSession smtp;

// Flame sensor pin
#define FLAME_SENSOR_PIN 5

// Threshold for fire detection
#define FIRE_DETECTED LOW

void setup() {
  Serial.begin(115200);
  Serial.println();

  // Initialize flame sensor pin
  pinMode(FLAME_SENSOR_PIN, INPUT);

  // Connect to WiFi
  Serial.print("Connecting to WiFi...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(200);
  }
  Serial.println("\nWiFi connected.");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  // Enable debug messages for SMTP
  smtp.debug(1);
}

void loop() {
  // Check flame sensor status
  if (digitalRead(FLAME_SENSOR_PIN) == FIRE_DETECTED) {
    Serial.println("Fire detected! Sending alert email...");
    sendFireAlertEmail();
    delay(30000); // Wait for 30 seconds before checking again
  }
}

void sendFireAlertEmail() {
  // Configure SMTP session
  ESP_Mail_Session session;
  session.server.host_name = SMTP_server;
  session.server.port = SMTP_Port;
  session.login.email = sender_email;
  session.login.password = sender_password;
  session.login.user_domain = "";

  // Create an email message
  SMTP_Message message;
  message.sender.name = "Fire Alert System";
  message.sender.email = sender_email;
  message.subject = "Fire Alert! Immediate Attention Required";
  message.addRecipient(Recipient_name, Recipient_email);

  // Email body
  String htmlMsg = "<div style=\"color:#ff0000;\"><h1>Fire Alert!</h1><p>A fire has been detected by the ESP32 system. Immediate action is required.</p></div>";
  message.html.content = htmlMsg.c_str();
  message.html.charSet = "us-ascii";
  message.html.transfer_encoding = Content_Transfer_Encoding::enc_7bit;

  // Connect to SMTP server and send email
  if (!smtp.connect(&session)) {
    Serial.println("Error connecting to SMTP server: " + smtp.errorReason());
    return;
  }

  if (!MailClient.sendMail(&smtp, &message)) {
    Serial.println("Error sending Email: " + smtp.errorReason());
  } else {
    Serial.println("Fire alert email sent successfully!");
  }

  // Close the SMTP session
  smtp.closeSession();
}
