<?php
require_once('../Connections/yogiwherequery.php');

// Connetti al database
$conn = new mysqli($servername, $username, $password, $database);

// Verifica la connessione
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Ottieni la latitudine e la longitudine dell'utente
if (isset($_POST['lat']) && isset($_POST['lng'])) {
    $userLat = $_POST['lat'];
    $userLng = $_POST['lng'];
    $radius = 20; // Raggio in chilometri

    // Query per trovare le scuole entro 20 km dalla posizione dell'utente
    $query = "
        SELECT yogaschool.idyogaschool, yogaschool.nameschool, yogaschool.latitude, yogaschool.longitude, yogaschool.shortschooldescription, yogaschool.address, yogaschool.city, yogaschool.zip, yogaschool.country, photoyogaschool.photofilename,
        (6371 * acos(cos(radians($userLat)) * cos(radians(latitude)) * cos(radians(longitude) - radians($userLng)) + sin(radians($userLat)) * sin(radians(latitude)))) AS distance 
        FROM yogaschool LEFT JOIN photoyogaschool ON yogaschool.idyogaschool=photoyogaschool.idyogaschool AND photoyogaschool.priority='Y'
        HAVING distance < $radius
        ORDER BY distance";

    $result = $conn->query($query);

    $markers = array();

    // Controlla se ci sono risultati
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $markers[] = array(
                'idyogaschool' => $row['idyogaschool'],
                'name' => $row['nameschool'],
                'latitude' => $row['latitude'],
                'longitude' => $row['longitude'],
                'description' => $row['shortschooldescription'],
                'address' => $row['address'],
                'city' => $row['city'],
                'zip' => $row['zip'],
                'country' => $row['country'],
                'image' => '',
                'distance' => $row['distance'],
                'photofilename' => $row['photofilename']
            );
        }
        echo json_encode(array('status' => 'success', 'data' => $markers));
    } else {
        echo json_encode(array('status' => 'error', 'message' => 'Nessuna scuola trovata entro 20 km.'));
    }
} else {
    echo json_encode(array('status' => 'error', 'message' => 'Posizione utente non fornita.'));
}

$conn->close();
