<?php

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

// Check connection
if ($conn->connect_error) {
    echo json_encode(array("message" => "Connection failed: " . $conn->connect_error, "error" => true));
    exit();
}

// Handling form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate and sanitize inputs
    $name = trim($_POST['name']);
    $phone = trim($_POST['phone']);
    $message = trim($_POST['message']);

    // 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();
    }

    if (empty($message)) {
        echo json_encode(array("message" => "Message 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);
    $message = mysqli_real_escape_string($conn, $message);

    // Insert data into database
    $insert_sql = "INSERT INTO contact_us (name, phone, message, created_at, updated_at)
VALUES ('$name', '$phone', '$message', NOW(), NOW())";

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

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

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

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

        } catch (\Throwable $th) {

        }
        echo json_encode(array("message" => "New record created successfully", "error" => false));
    } else {
        echo json_encode(array("message" => $conn->error, "error" => true));
    }
}

$conn->close();