<?php

// Include the database connection
include 'db_connect.php';
require 'email_functions.php';

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Handling form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate and sanitize email input
    $email = $_POST['email'];

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(array("message" => "Invalid email format", "error" => true));
        die;
    }

    // Sanitize email input to prevent SQL injection
    $email = mysqli_real_escape_string($conn, $email);

    // Check if email already exists
    $check_sql = "SELECT * FROM newsletters WHERE email = '$email'";
    $check_result = $conn->query($check_sql);

    if ($check_result->num_rows > 0) {

        die(json_encode(array("message" => "Email is already taken", "error" => true)));
    }

    // Insert data into database
    $insert_sql = "INSERT INTO newsletters (email, created_at, updated_at)
                   VALUES ('$email', NOW(), NOW())";


    if ($conn->query($insert_sql) === true) {

        try {
            $to = 'divyang@webplanex.us';
            $subject = "Testing";
            $templateFile = '../email/newsletters.html';

            $replaceValues = array(

                '$email' => $email


            );

            $message1 = generateEmailTemplate($templateFile, $replaceValues);
            sendEmail($to, $subject, $message1);

        } catch (\Throwable $th) {
            // Handle email exception
        }
        echo json_encode(array("message" => "New Questions created successfully", "error" => false));

    } else {
        echo json_encode(array("message" => $conn->error, "error" => true));
    }
}
$conn->close();
