<?php
// get_dimos_centroid.php
header('Content-Type: application/json');

$host = "localhost";
$port = 5433;
$dbname = "postgres";
$user = "postgres";
$pass = "postgresse!";

try {
    $pdo = new PDO("pgsql:host=$host;port=$port;dbname=$dbname", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['error' => 'Σφάλμα σύνδεσης βάσης']);
    exit;
}

// Παίρνουμε το dimos_id από το GET
$dimos_id = isset($_GET['dimos_id']) ? (int)$_GET['dimos_id'] : 0;

if($dimos_id > 0){
    $stmt = $pdo->prepare("
        SELECT ST_Y(centroid) AS lat, ST_X(centroid) AS lng
        FROM dimos
        WHERE id = :dimos_id
        LIMIT 1
    ");
    $stmt->execute([':dimos_id' => $dimos_id]);
    $dimos = $stmt->fetch(PDO::FETCH_ASSOC);

    if($dimos){
        echo json_encode([
            'lat' => (float)$dimos['lat'],
            'lng' => (float)$dimos['lng']
        ]);
        exit;
    }
}

// fallback
echo json_encode(['lat' => null, 'lng' => null]);
