%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /home/komfo908/www/dnis666/
Upload File :
Create Path :
Current File : /home/komfo908/www/dnis666/apiKomfort.php

<?php
define('GOOGLE_MAPS_API_KEY', 'AIzaSyCP05f0goV5A92vr7NgGcSdZkXWGRO_MGo');

function remove_non_numeric_characters($string) {
    return preg_replace('/\D/', '', $string);
}

function get_coordinates($address) {
    $address = urlencode($address);
    $url = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&key=" . GOOGLE_MAPS_API_KEY;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    curl_close($ch);

    $response = json_decode($response, true);

    if ($response['status'] == 'OK') {
        return $response['results'][0]['geometry']['location'];
    }

    return null;
}

function get_nearby_stores($lat, $lng) {
    $radius = 20000; // Raio de 20 km
    $keyword = urlencode("Komfort House");
    $url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={$lat},{$lng}&radius={$radius}&keyword={$keyword}&key=" . GOOGLE_MAPS_API_KEY;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    curl_close($ch);

    $response = json_decode($response, true);

    error_log("Response from Places API: " . json_encode($response));

    if ($response['status'] == 'OK') {
        return $response['results'];
    }

    return null;
}

function calculate_distance($lat1, $lng1, $lat2, $lng2) {
    $earth_radius = 6371; // Raio da Terra em KM
    $dLat = deg2rad($lat2 - $lat1);
    $dLng = deg2rad($lng2 - $lng1);
    $a = sin($dLat / 2) * sin($dLat / 2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLng / 2) * sin($dLng / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    return $earth_radius * $c;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $payload = file_get_contents('php://input');
    $input = json_decode($payload, true);

    if (isset($input['address'])) {
        $user_address = $input['address'];
        $clean_address = remove_non_numeric_characters($user_address);

        if (empty($clean_address)) {
            echo json_encode(["error" => "Endereço não pode estar vazio."]);
            exit;
        }

        $user_location = get_coordinates($clean_address);

        if ($user_location) {
            $user_lat = $user_location['lat'];
            $user_lng = $user_location['lng'];
            $stores = get_nearby_stores($user_lat, $user_lng);

            error_log("Nearby stores: " . json_encode($stores));

            if ($stores) {
                $closest_store = null;
                $shortest_distance = INF; // Inicia com infinito

                foreach ($stores as $store) {
                    if (!isset($store['geometry']['location']['lat']) || !isset($store['geometry']['location']['lng'])) {
                        continue; // Ignorar lojas sem coordenadas
                    }

                    $store_lat = $store['geometry']['location']['lat'];
                    $store_lng = $store['geometry']['location']['lng'];
                    $distance = calculate_distance($user_lat, $user_lng, $store_lat, $store_lng);

                    error_log("Loja encontrada: " . json_encode($store));
                    error_log("Distância até usuário: " . $distance . " km");

                    // Se for a primeira loja ou a mais próxima até agora, atualiza
                    if ($closest_store === null || $distance < $shortest_distance) {
                        $shortest_distance = $distance;
                        $closest_store = $store;
                        error_log("Nova loja mais próxima selecionada: " . json_encode($closest_store));
                    }
                }

                $response = [
                    'user_address' => $user_address,
                    'clean_address' => $clean_address,
                    'user_location' => $user_location,
                    'closest_store' => $closest_store,
                    'distance_km' => $shortest_distance !== INF ? $shortest_distance : null
                ];

                header('Content-Type: application/json');
                echo json_encode($response);
            } else {
                echo json_encode(["error" => "Nenhuma loja encontrada nas proximidades."]);
            }
        } else {
            echo json_encode(["error" => "Não foi possível obter as coordenadas do endereço fornecido."]);
        }
    } else {
        echo json_encode(["error" => "Por favor, forneça um endereço."]);
    }
} else {
    echo json_encode(["error" => "Método de requisição não suportado. Use POST."]);
}
?>

Zerion Mini Shell 1.0