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

// Παίρνουμε τα δεδομένα POST
$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['dimos_id'])) {
    echo json_encode(['success' => false, 'message' => 'Δεν δόθηκε dimos_id']);
    exit;
}

$dimos_id = (int)$data['dimos_id'];

$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(['success' => false, 'message' => 'Σφάλμα σύνδεσης βάσης']);
    exit;
}

// Παίρνουμε το centroid του δήμου
$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) {
    $_SESSION['dimos_id'] = $dimos_id;
    $_SESSION['centroid_lat'] = (float)$dimos['lat'];
    $_SESSION['centroid_lng'] = (float)$dimos['lng'];
    $_SESSION['zoom'] = 14;

    echo json_encode(['success' => true]);
    exit;
} else {
    echo json_encode(['success' => false, 'message' => 'Δήμος δεν βρέθηκε']);
}
