<?php

	// ToDo's
	// Whitelists oder Prepared Statements gegen SQL-Injection hinzufügen

    // PostgreSQL-Serververbindung
    include 'init.php';

    // HTTP-POST-Methode für Formulardaten
    $table = htmlspecialchars($_POST['table'], ENT_QUOTES);
    $dma_id = htmlspecialchars($_POST['dma_id'], ENT_QUOTES);

    if($table == 'valves') {
        $dma_id_field = "valve_dma_id";
    }

    if($table == 'buildings') {
        $dma_id_field = "building_dma_id";
    }

    if($table == 'pipelines') {
        $dma_id_field = "pipeline_dma_id";
    }
    
    try {
        // Datenbankabfrage
        $result = $pdo -> query("SELECT *, ST_AsGeoJSON(geom) as geojson FROM $table WHERE $dma_id_field = '$dma_id'");

        $features = [];

        foreach($result as $row) {
            // PHP-Objekt erstellen
            $geometry = json_decode($row['geojson']);
            
            // PHP-Objekt bereinigen 
            unset($row['geom']);
            unset($row['geojson']);
            
            // JSON-Feature hinzufügen
            $feature = [
                "type"=>"Feature", 
                "geometry"=>$geometry, 
                "properties"=>$row
            ];

            array_push($features, $feature);
        };

        // Feature-Collection hinzufügen
        $featureCollection = [
            "type"=>"FeatureCollection",
            "features"=>$features
        ];

        echo json_encode($featureCollection);

    // Fehlernachricht ausgeben
    } catch(PDOException $e) {
        echo "ERROR ".$e->getMessage();

    }

?>