<?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']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $subject = trim($_POST['subject']);
    $message = trim($_POST['message']);

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

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

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['message' => 'Invalid email format', 'error' => true]);
        exit();
    }

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

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

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

    // 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);
    $subject = mysqli_real_escape_string($conn, $subject);
    $message = mysqli_real_escape_string($conn, $message);

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

    if ($check_result->num_rows > 0) {
        die(json_encode(['message' => 'Email is already taken', 'error' => true]));
    }

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

    if ($conn->query($insert_sql) === true) {
        $apiMessage = "You have received a new inquiry request.\n\n" . "Client Name: $name\n" . "Contact Number: $phone\n" . "Message: $message\n\n" . 'Please review the details and take the necessary actions.';

        $apiResponse = sendPostRequest($apiMessage);

        try {
            $to = 'divyang@webplanex.us';
            $emailSubject = 'New Question Submission';
            $templateFile = '../email/questions.html';

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

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

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

$conn->close();
?>