<?php

include 'db_connect.php';
require 'email_functions.php';
include '../apicall.php'; // Include API call file

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = trim($_POST['name']);
    $phone = trim($_POST['phone'] ?? $_POST['phone_number']);
    $message = trim($_POST['message']);

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

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

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

    // Escape 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 the database
    $stmt = $conn->prepare('INSERT INTO contact_us (name, phone, message, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())');
    $stmt->bind_param('sss', $name, $phone, $message);

    if ($stmt->execute()) {
        $apiMessage = "You have received a new contact us request.\n\n" . "Name: $name\n" . "Phone: $phone\n" . "Message: $message\n\n" . 'Please review the details and take the necessary steps.';

        $apiResponse = sendPostRequest($apiMessage);

        // Send email notification
        try {
            $to = 'divyang@webplanex.us';
            $subject = 'New Contact Form Submission';
            $templateFile = '../email/contacts.html';

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

            $emailMessage = generateEmailTemplate($templateFile, $replaceValues);
            sendEmail($to, $subject, $emailMessage);
        } catch (Exception $e) {
            echo json_encode(['message' => 'Email error: ' . $e->getMessage(), 'error' => true]);
            exit();
        }

        echo json_encode(['message' => 'Data inserted, API called, and email sent successfully.', 'error' => false]);
    } else {
        echo json_encode(['message' => 'Database error: ' . $stmt->error, 'error' => true]);
    }

    $stmt->close();
}

$conn->close();
?>