<?php

// 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('Connection failed: ' . $conn->connect_error);
}

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

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

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

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

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

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

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

    // 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) {
        // Prepare data for API call
        $apiMessage = "You have received a new appointment request.\nPlease find the details below:

        Client Name: $name
        Contact Number: $phone
        Message: $message
        \n\nPlease review the details and take the necessary steps.
        ";

        // Call the API
        $apiResponse = sendPostRequest($apiMessage);

        try {
            $to = 'divyang@webplanex.us';
            $subject = 'New Appointment Submission';
            $templateFile = '../email/appointments.html';

            $replaceValues = [
                '$name' => $name,
                '$phone' => $phone,
                '$message' => $message,
            ];

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

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

$conn->close();
?>