<?php

// Include the database connection
include 'db_connect.php';
require 'email_functions.php';
include '../apicall.php'; // Include the API call function

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

    // 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 cannot be more than 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 must be exactly 10 digits', 'error' => true]);
        exit();
    }

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

    // Check if phone number already exists
    $check_sql = "SELECT * FROM whatsapp 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 with current timestamps for created_at and updated_at
    $insert_sql = "INSERT INTO whatsapp (name, phone, created_at, updated_at)
                   VALUES ('$name', '$phone', NOW(), NOW())";

    if ($conn->query($insert_sql) === true) {
        
        $apiMessage = "New Community join request:\n\n" . "Name: $name\n" . "Phone: $phone\n\n" . 'Please review the details and get back to the client.';

        $apiResponse = sendPostRequest($apiMessage);

        try {
            $to = 'divyang@webplanex.us';
            $subject = 'New WhatsApp Community Join Request';
            $templateFile = '../email/whatsapp.html';

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

            $message1 = generateEmailTemplate($templateFile, $replaceValues);
            sendEmail($to, $subject, $message1);
        } 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 successfully', 'error' => false, 'name' => $name, 'phone' => $phone]);
    } else {
        echo json_encode(['message' => $conn->error, 'error' => true]);
    }
}

$conn->close();
?>