<?php
// config laden
require_once 'config.php';

// Verbindungsaufbau zur Datenbank
$config = include('db-connection.php');
$host = $config['host'];
$port = $config['port'];
$dbname = $config['dbname'];
$user = $config['user'];
$password = $config['password'];

// Verbindung aufbauen
$dbconn = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password")
    or die('Verbindungsaufbau fehlgeschlagen: ' . pg_last_error());

// Eingabedaten aus JSON-Body
$data = file_get_contents('php://input');
$data = mb_convert_encoding($data, 'UTF-8', 'auto');
// Debugging: Gib den rohen Inhalt von php://input aus
//echo "Raw data: " . $data;
$data = json_decode($data, true);

// Überprüfen, ob die erforderlichen Daten vorhanden sind
$requiredFields = ['first_name', 'last_name', 'year_of_birth', 'street', 'house_no', 'localdistrict', 'city', 'geom', 'Lat', 'Lon'];
foreach ($requiredFields as $field) {
    if (!isset($data[$field])) {
        echo json_encode(['success' => false, 'error' => "Fehlende Daten: $field"]);
        exit;
    }
}

// Optional Felder setzen
$stone_position = isset($data['stone_position']) ? $data['stone_position'] : null;
$status = isset($data['status']) ? $data['status'] : null;
$comment = isset($data['comment']) ? $data['comment'] : null;
$last_photo = isset($data['last_photo']) ? pg_escape_bytea($data['last_photo']) : null;
$caretaker = isset($data['caretaker']) ? $data['caretaker'] : null;
$url_wikipedia = isset($data['URL_Wikipedia']) ? $data['URL_Wikipedia'] : null;
$confirmed_by = isset($data['Confirmed_by']) ? $data['Confirmed_by'] : null;
$manual_address = isset($data['manual_address']) ? (bool)$data['manual_address'] : false;
$url_kodb = $data['URL_KoDb']; // Dieser Wert muss eindeutig sein
$last_cleaned = isset($data['last_cleaned']) ? $data['last_cleaned'] : null;
$cleaned_by = isset($data['cleaned_by']) ? $data['cleaned_by'] : null;
$instance_nr = isset($data['instance_nr']) ? $data['instance_nr'] : null;

// SQL-Insert-Query vorbereiten
$query = "
    INSERT INTO public.{$tablePrefix}  (
        first_name, last_name, year_of_birth, street, house_no, localdistrict, city, geom, Lat, Lon, 
        stone_position, status, comment, last_photo, caretaker, URL_Wikipedia, Confirmed_by, 
        manual_address, URL_KoDb, last_cleaned, cleaned_by, instance_nr
    )
    VALUES (
        $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, 
        $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22
    )
    RETURNING gid;
";

// Parameter für das Query
$params = array(
    $first_name, $last_name, $year_of_birth, $street, $house_no, $localdistrict, $city, 
    $geom, $Lat, $Lon, $stone_position, $status, $comment, $last_photo, 
    $caretaker, $url_wikipedia, $confirmed_by, $manual_address, $url_kodb, $last_cleaned, $cleaned_by, $instance_nr
);

// Sicherstellen, dass alle 22 Werte im Array vorhanden sind
if (count($params) != 22) {
    $errorDetails = [];
    foreach ($params as $index => $param) {
        $errorDetails[] = "Parameter " . ($index + 1) . ": " . var_export($param, true);
    }
    echo json_encode(['success' => false, 'error' => 'Es fehlen Parameter für den INSERT!', 'details' => $errorDetails]);
    exit;
}

// Query ausführen
$result = pg_query_params($dbconn, $query, $params);
if (!$result) {
    echo json_encode(['success' => false, 'error' => pg_last_error($dbconn)]);
    exit;
}

// Das Ergebnis des Inserts holen
$row = pg_fetch_assoc($result);

// Erfolgreiche Antwort mit der GID zurückgeben
$response = [
    'success' => true,
    'gid' => $row['gid']  // Der zurückgegebene Wert von GID
];
echo json_encode($response);

// Verbindung schließen
pg_free_result($result);
pg_close($dbconn);
?>
