<?php

// API keys
$openaiApiKey = "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";
$googlePlacesApiKey = "AIzaSyAq1ODKKCVgTT3yvuqrsSIL8biDjhNu8NM";



// Function to call Google Places API
function searchGooglePlaces($query)
{
    global $googlePlacesApiKey;
    
    $url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" . urlencode($query) . "&key=" . $googlePlacesApiKey;

    $response = file_get_contents($url);
    return json_decode($response, true);
}

// OpenAI function definition
$functions = [
    [
        "name" => "search_google_places",
        "description" => "Search for a location using Google Places API",
        "parameters" => [
            "type" => "object",
            "properties" => [
                "query" => [
                    "type" => "string",
                    "description" => "The name or description of the place to search for"
                ]
            ],
            "required" => ["query"]
        ]
    ]
];

// User input
//$userInput = "Find coffee shops near Kuala Lumpur";
$userInput = $_GET['message'];
// OpenAI API request
$ch = curl_init("https://api.openai.com/v1/chat/completions");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Authorization: Bearer $openaiApiKey"
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    "model" => "gpt-4o-mini",
    "messages" => [["role" => "user", "content" => $userInput]],
    "functions" => $functions
]));

$response = curl_exec($ch);
curl_close($ch);
$responseData = json_decode($response, true);

// Check if OpenAI suggests a function call
if (!empty($responseData['choices'][0]['message']['function_call'])) {
    $functionCall = $responseData['choices'][0]['message']['function_call'];
    
    if ($functionCall['name'] === "search_google_places") {
        $args = json_decode($functionCall['arguments'], true);
        $placesResult = searchGooglePlaces($args['query']);

        // Print the result
        echo json_encode($placesResult, JSON_PRETTY_PRINT);
    }
} else {
    print_r($responseData['choices'][0]['message']['content']);
}
