<?php

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


if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $name = $_POST['name'];
    $phone = $_POST['phone_number'];

    // Validate each field individually
    if (empty($name)) {
        echo json_encode(array("message" => "Name field is required", "error" => true));
        exit();
    }

    if (empty($phone)) {
        echo json_encode(array("message" => "Phone field is required", "error" => true));
        exit();
    }

    // Sanitize inputs to prevent SQL injection
    $name = mysqli_real_escape_string($conn, $name);
    $phone = mysqli_real_escape_string($conn, $phone);

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

    if ($check_result->num_rows > 0) {
        echo json_encode(array("message" => "Phone number is already registered", "error" => true));
        exit();
    }

    // Insert data into database with current timestamps for created_at and updated_at
    $insert_sql = "INSERT INTO whatsapp (name, phone, created_at, updated_at)
                   VALUES ('$name', '$phone', NOW(), NOW())";

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

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

            $replaceValues = array(
                '$name' => $name,
                '$phone' => $phone,
                '$message' => $message,
            );

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

        } catch (\Throwable $th) {
            // Handle email exception
        }
        // echo json_encode(array("message" => "New record created successfully", "error" => false));
        echo json_encode(array("message" => "New record created successfully", "error" => false, "name" => $name, "phone" => $phone));
    } else {
        echo json_encode(array("message" => $conn->error, "error" => true));
    }
}

$conn->close();