<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
session_start();
if($_SESSION['sml_si']!=session_id()) {
    die();
}
require(__DIR__.'/../../config/config.inc.php');
require(__DIR__.'/../functions.php');
$id_user = $_SESSION['id_user'];
$id_map = (int)$_GET['id_map'];
$distance_limit = isset($_GET['distance']) ? (float)$_GET['distance'] : 10; // meters
if($distance_limit <= 0) $distance_limit = 10;
$map = get_map($id_map, $id_user);
$address_format = json_decode($map['address_format'], true);
$calculated_deg = ($distance_limit / 111000) * 2.0;
$delta = max(0.01, $calculated_deg);
$query = "SELECT 
            m1.id as id1, m1.name as name1, m1.lat as lat1, m1.lon as lon1,
            m1.street as street1, m1.city as city1, m1.postal_code as postal_code1, m1.country as country1, m1.county as county1, m1.state as state1, 
            m2.id as id2, m2.name as name2, m2.lat as lat2, m2.lon as lon2, 
            m2.street as street2, m2.city as city2, m2.postal_code as postal_code2, m2.country as country2, m2.county as county2, m2.state as state2,
            ( 6371000 * acos( cos( radians(m1.lat) ) * cos( radians( m2.lat ) ) * cos( radians( m2.lon ) - radians( m1.lon ) ) + sin( radians( m1.lat ) ) * sin( radians( m2.lat ) ) ) ) AS distance 
          FROM sml_markers m1 
          JOIN sml_markers m2 ON m1.id < m2.id 
            AND m1.id_map = m2.id_map 
            AND m2.lat BETWEEN m1.lat - $delta AND m1.lat + $delta
            AND m2.lon BETWEEN m1.lon - $delta AND m1.lon + $delta
          WHERE m1.id_map = ? 
            AND m1.lat IS NOT NULL AND m1.lat != '' 
            AND m2.lat IS NOT NULL AND m2.lat != ''
          HAVING distance <= ? 
          ORDER BY distance ASC";
$duplicates = array();
if(isset($mysqli) && $stmt = $mysqli->prepare($query)) {
    $stmt->bind_param('id', $id_map, $distance_limit);
    $stmt->execute();
    $result = custom_get_result($stmt);
    while($row = $result->fetch_assoc()) {
        $row_m1 = [
            'street' => $row['street1'],
            'city' => $row['city1'],
            'postal_code' => $row['postal_code1'],
            'country' => $row['country1'],
            'county' => $row['county1'],
            'state' => $row['state1']
        ];
        $row['address1'] = format_address_string($row_m1, $address_format);
        $row_m2 = [
            'street' => $row['street2'],
            'city' => $row['city2'],
            'postal_code' => $row['postal_code2'],
            'country' => $row['country2'],
            'county' => $row['county2'],
            'state' => $row['state2']
        ];
        $row['address2'] = format_address_string($row_m2, $address_format);
        $duplicates[] = $row;
    }
    $stmt->close();
}
header('Content-Type: application/json');
echo json_encode($duplicates);
?>