<?php
// inota.php

header('Content-Type: application/json');
require_once __DIR__ . '/db.php';

$data = json_decode(file_get_contents('php://input'), true);

if (!$data || !isset($data['lat'], $data['lng'], $data['dimos_id'])) {
    echo json_encode(['status' => false, 'message' => 'Missing parameters']);
    exit;
}

// έλεγχος για γεωγραφικές συντεταγμένες
$lat = filter_var($data['lat'], FILTER_VALIDATE_FLOAT);
$lng = filter_var($data['lng'], FILTER_VALIDATE_FLOAT);
$dimos_id = (int)$data['dimos_id'];

if ($lat === false || $lng === false) {
    echo json_encode(['status' => false, 'message' => 'Invalid coordinates']);
    exit;
}

// Ποετοιμασία για ασφαλή SQL
try{
    $sql = "
        SELECT ST_Contains(geom, ST_SetSRID(ST_MakePoint(:lng, :lat), 4326)) AS inside
        FROM dimos
        WHERE id = :dimos_id
        LIMIT 1
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':lng', $lng);
    $stmt->bindValue(':lat', $lat);
    $stmt->bindValue(':dimos_id', $dimos_id, PDO::PARAM_INT);
    $stmt->execute();

    $result = $stmt->fetch();
    $inside = $result ? (bool)$result['inside'] : false;

    echo json_encode(['status' => $inside]);

} catch (PDOException $e) {
    echo json_encode(['status' => false, 'message' => 'Database error']);
    exit;
}