<?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']);
    $treatment = trim($_POST['treatment']); // Replace message with treatment

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

    if (strlen($name) > 20) {
        echo json_encode(['message' => 'Name should not exceed 20 characters', 'error' => true]);
        exit();
    }

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

    if (!preg_match('/^\d{10}$/', $phone)) {
        echo json_encode(['message' => 'Phone number should be exactly 10 digits', 'error' => true]);
        exit();
    }

    if (empty($treatment)) {
        echo json_encode(['message' => 'Treatment 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);
    $treatment = mysqli_real_escape_string($conn, $treatment);

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

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

    // Insert data into database
    $insert_sql = "INSERT INTO questionans (name, phone, treatment, created_at, updated_at)
                   VALUES ('$name', '$phone', '$treatment', 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" . "Treatment: $treatment\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,
                '$phone' => $phone,
                '$treatment' => $treatment,
            ];

            $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();
?>