<?php
function loopGetResponse($threadId){
    sleep(5);
    global $client;
    $maxRetries = 5;
    $attempts = 0;
    $assistantMessage = null;

    while ($attempts < $maxRetries) {
        // Step 4: Fetch the latest messages from the thread
        $responseMessages = $client->threads()->messages()->list($threadId, [
            'limit' => 1, // We only want the most recent message
        ]);

        // Step 5: Extract the assistant's message
        foreach ($responseMessages['data'] as $message) {
            if ($message['role'] === 'assistant') {
                $assistantMessage = $message['content'];
                break 2; // Exit both loops once we find the assistant's response
            }
        }

        // Step 6: If no assistant response, wait before retrying
        if ($assistantMessage === null || count($assistantMessage) == 0) {
            sleep(3); // Wait for 3 seconds before retrying (adjust if needed)
        }

        $attempts++;
    }
    if ($assistantMessage) {

        $gptResultRaw = $assistantMessage[0]['text']['value'];
        $gptResultRaw = str_replace("```json", "", $gptResultRaw);
        $gptResultRaw = str_replace("```", "", $gptResultRaw);
        $gptResultRaw = trim($gptResultRaw);
        return $gptResultRaw;
    }else{
        return false;
    }

    
}

function getPlacePhotoUrl($photoName, $maxWidth = 400) {
    global $apiKey;
    return "https://places.googleapis.com/v1/{$photoName}/media?max_width_px={$maxWidth}&key={$apiKey}";
}

/**
 * Extract place details from the API response.
 */
function extractPlaceDetails($place) {
    $details = [];
   
    if (isset($place['id'])) {
        $details['place_id'] = $place['id'];
    }
    // Extract name
    if (isset($place['displayName']['text'])) {
        $details['name'] = $place['displayName']['text'];
    }

    // Extract phone number
    if (isset($place['nationalPhoneNumber'])) {
        $details['phone'] = $place['nationalPhoneNumber'];
    }

    // Extract the first photo
    if (isset($place['photos'][0]['name'])) {
        $photoName = $place['photos'][0]['name'];
        $details['image'] = $photoName;
    }

    // Extract reviews
    /*if (isset($place['reviews'])) {
        $details['reviews'] = [];
        foreach ($place['reviews'] as $review) {
            $details['reviews'][] = [
                'rating' => $review['rating'],
                'text' => $review['text'],
            ];
        }
    }*/

    return $details;
}

/**
 * Search for places using the Google Places API.
 */
function searchPlacesOld($query){
     global $apiKey;
    
    $url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" . urlencode($query) . "&key=" . $apiKey;

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

function searchPlaces($query) {
    global $apiKey;
    $url = "https://places.googleapis.com/v1/places:searchText";

    // Request payload
    $data = [
        "textQuery" => $query, // textQuery should be a string
        "languageCode" => "en", // Optional: Specify language
        "regionCode" => "MY",   // Optional: Specify region (Malaysia)
        "maxResultCount" => 30   // Optional: Limit the number of results
    ];

    $jsonData = json_encode($data);

    // Initialize cURL
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/json",
            "X-Goog-Api-Key: {$apiKey}",
            "X-Goog-FieldMask: places.id,places.displayName,places.nationalPhoneNumber,places.photos,places.reviews", // Required Field Mask
        ],
        CURLOPT_POSTFIELDS => $jsonData,
    ]);

    // Execute the request
    $response = curl_exec($ch);

    // Check for errors
    if (curl_errno($ch)) {
        throw new Exception(curl_error($ch));
    }

    curl_close($ch);

    // Decode the response
    $result = json_decode($response, true);

    // Extract details for each place
    $places = [];

    if (isset($result['places'])) {
        foreach ($result['places'] as $place) {
            $places[] = extractPlaceDetails($place);
        }
    }
   
    return $places;
}

function placeDetails($placeId){
    global $apiKey;
    $detailsUrl = "https://maps.googleapis.com/maps/api/place/details/json?place_id=$placeId&fields=name,formatted_address,editorial_summary,photos,website,rating&key=$apiKey";
    $detailsResponse = file_get_contents($detailsUrl);
    return json_decode($detailsResponse);
}