<?php

header('Content-Type: application/json');

// Include the database connection
include 'db_connect.php';
require 'email_functions.php';
include '../apicall.php'; // Include the API call function

// Check connection
if ($conn->connect_error) {
    die(json_encode(['message' => 'Connection failed: ' . $conn->connect_error, 'error' => true]));
}

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

    if (empty($email)) {
        die(json_encode(['message' => 'Email field is required', 'error' => true]));
    }

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['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(['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) {
        $apiMessage = "You have received a new newsletter subscription request.\n\n" . "Subscriber Email: $email\n\n" . 'Please add this email to your newsletter list.';

        $apiResponse = sendPostRequest($apiMessage);

        try {
            $to = 'divyang@webplanex.us';
            $subject = 'New Newsletter Subscription';
            $templateFile = '../email/newsletters.html';

            $replaceValues = [
                '$email' => $email,
            ];

            $message1 = generateEmailTemplate($templateFile, $replaceValues);
            sendEmail($to, $subject, $message1);
        } catch (\Throwable $th) {
            // Handle email exception
            echo json_encode(['message' => 'Email sending failed: ' . $th->getMessage(), 'error' => true]);
            exit();
        }

        echo json_encode(['message' => 'New subscription created successfully', 'error' => false]);
    } else {
        echo json_encode(['message' => $conn->error, 'error' => true]);
    }
}

$conn->close();
?>