<?php
// Dynamically get the current domain
$currentDomain = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' 
    ? "https://" 
    : "http://";
$currentDomain .= $_SERVER['HTTP_HOST']; // Add the host (e.g., example.com)
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
if (strpos($referer, $currentDomain) !== 0) {
    echo json_encode(["error" => "Requests from this referer are not allowed"]);
    exit;
}
$apiKey = filter_input(INPUT_GET, 'key', FILTER_SANITIZE_STRING);
if($apiKey==''|| strlen($apiKey) > 250){ return;}
$input = filter_input(INPUT_GET, 'input', FILTER_SANITIZE_STRING);
if($input=='' || strlen($input) > 250){ return;}
$ctcode = filter_input(INPUT_GET, 'code', FILTER_SANITIZE_STRING);
if(strlen($ctcode) > 10){ return;}
$ctcode = $ctcode!='' ? (explode(",", $ctcode)) : '';//echo $ctcode;exit;
$rslcode =  filter_input(INPUT_GET, 'rslcode', FILTER_SANITIZE_STRING);
// Construct the URL for the Places API
$url = "https://places.googleapis.com/v1/places:autocomplete";
// Initialize cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "X-Goog-Api-Key: $apiKey",
    "Accept-Language: $rslcode"
]);
// Set the JSON payload
$jsonPayload = json_encode([
    "input" => $input,
    "includedRegionCodes" => $ctcode
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);
// Execute the cURL request
$response = curl_exec($ch);
// Handle errors
if (curl_errno($ch)) {
    echo json_encode(["error" => curl_error($ch)]);
} else {
    echo $response; // Forward the API's response to the frontend
}
// Close the cURL session
curl_close($ch);
/*
function wp_get_autocomplete_suggestions($input) {
    // Validate input
    if (empty($input)) {
        return ["error" => "Input is required"];
    }

    // Your Google API key (replace with your actual key)
    $apiKey = '';

    // Construct the URL for the Places API
    $url = 'https://places.googleapis.com/v1/places:autocomplete';

    // Prepare the payload
    $body = json_encode([
        'input' => $input,
    ]);

    // Send the request using wp_remote_post
    $response = wp_remote_post($url, [
        'headers' => [
            'Content-Type'  => 'application/json',
            'X-Goog-Api-Key'=> $apiKey,
        ],
        'body' => $body,
    ]);

    // Check for errors
    if (is_wp_error($response)) {
        return ['error' => $response->get_error_message()];
    }

    // Return the API response
    $response_body = wp_remote_retrieve_body($response);
    return json_decode($response_body, true);
}
function register_autocomplete_endpoint() {
    register_rest_route('custom/v1', '/autocomplete', [
        'methods'  => 'GET',
        'callback' => 'handle_autocomplete_request',
        'args'     => [
            'input' => [
                'required' => true,
                'sanitize_callback' => 'sanitize_text_field',
            ],
        ],
        'permission_callback' => '__return_true', // For public access
    ]);
}
add_action('rest_api_init', 'register_autocomplete_endpoint');

function handle_autocomplete_request($data) {
    $input = $data['input'];

    // Call your autocomplete function
    $suggestions = wp_get_autocomplete_suggestions($input);

    // Return suggestions
    if (isset($suggestions['error'])) {
        return new WP_Error('error', $suggestions['error'], ['status' => 400]);
    }

    return $suggestions;
}
*/