<?php
header("Content-Type: application/json");

// 🔐 OPTIONAL: API key security
// $headers = array_change_key_case(getallheaders(), CASE_UPPER);

// if (!isset($headers['X-API-KEY']) || trim($headers['X-API-KEY']) !== 'DINOBROWSER_2025') {
//     http_response_code(403);
//     echo json_encode(["error" => "Unauthorized"]);
//     exit;
// }


// 📥 Read input
$input = json_decode(file_get_contents("php://input"), true);
$message = $input['message'] ?? '';

if (!$message) {
    echo json_encode(["error" => "Message is required"]);
    exit;
}

// 🔁 Forward to n8n (Cloudflare Tunnel URL)
$n8n_url = "https://sleeps-singh-warranties-lawsuit.trycloudflare.com/webhook/ai-agent";

$payload = json_encode([
    "message" => $message
]);

$ch = curl_init($n8n_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

$response = curl_exec($ch);
curl_close($ch);

// 📤 Send AI response back to client
echo $response;
