<?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 inputs
    $name = $_POST['name'];
    // $email = $_POST['email'];
    $phone = $_POST['phone_number'];
    $message = $_POST['message'];

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

    //  if (empty($email)) {
    // echo json_encode(array("message" => "Email field is required", "error" => true));
    // die;
    // }

    // if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    //  echo json_encode(array("message" => "Email is already taken", "error" => true));
    //     die;
    // }

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

    if (empty($message)) {
        die(json_encode(array("message" => "Message field is required", "error" => true)));

    }

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

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

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

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

            $replaceValues = array(
                '$name' => $name,
                '$phone' => $phone,
                // '$email' => $email,
                // '$requested_date' => $requested_date,
                // '$requested_time' => $requested_time,
                '$message' => $message,
            );

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

        } catch (\Throwable $th) {
            //throw $th;
        }
        die(json_encode(array("message" => "New record created successfully", "error" => false)));
    } else {
        die(json_encode(array("message" => $conn->error, "error" => true)));
    }
}

$conn->close();