<?php
// Define your secret key (keep this value secure)
$secretKey = 'z9F@rT3!qW7eH1#nL5xU8?dS2yM4&pJ0vK';

// Define the raw webhook URL where data will be forwarded
$webhookUrl = 'https://webhook.latenode.com/3758/dev/e2a9f583-c42a-4071-a455-b63ce2434748';

// Retrieve the raw POST data (assuming JSON is posted from the client)
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// Check if the JSON is valid
if (!$data) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid JSON']);
    exit;
}

// Validate the secret key provided by the client
if (!isset($data['secret']) || $data['secret'] !== $secretKey) {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized: Invalid secret key']);
    exit;
}

// Validate required fields (only these fields are required)
if (empty($data['cn']) || empty($data['em']) || empty($data['pn']) || empty($data['msg'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing one or more required fields: Name, Email, Phone Number, or Message']);
    exit;
}

// Remove the secret key from data before forwarding it
unset($data['secret']);

// Initialize cURL to forward data to the actual webhook URL
$ch = curl_init($webhookUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

// Execute the request and get the response
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);




// Check for a successful response (HTTP status 200–299)
 if ($httpCode >= 200 && $httpCode < 300) {
    echo json_encode([
        'success' => true,
        'message' => 'Data forwarded successfully',
        'redirect_url' => 'thankyou.php', // Include the URL to redirect to
        'webhook_response' => $response
    ]);
} else {
    http_response_code(500);
    echo json_encode([
        'error' => 'Failed to forward data',
        'webhook_response' => $response
    ]);
} 
?>
