<?php
//save_markers.php

session_start();
error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);
header('Content-Type: application/json');
require_once __DIR__ . '/db.php';

$dimos_id = $_SESSION['dimos_id'] ?? null;
if (!$dimos_id) {
    echo json_encode(['status'=>'error','message'=>'Missing dimos_id']);
    exit;
}

if (empty($_POST) && empty($_FILES)) {
    echo json_encode(['status'=>'error','message'=>'No data received']);
    exit;
}

$data = $_POST;

// Προσθήκη dimos_id από session
$data['dimos_id'] = $dimos_id;

$categoryTableMap = [
    'Χώροι Στάθμευσης' => 'parking',
    'Διαβάσεις' => 'crossings',
    'Ράμπες Πεζοδρομίων' => 'pedestrian_ramps',
    'Ράμπες Εισόδου Κτιρίων' => 'building_ramps'
];

$category = $data['category'] ?? null;
if (!$category || !isset($categoryTableMap[$category])) {
    echo json_encode(['status'=>'error','message'=>'Unknown category']);
    exit;
}

$table = $categoryTableMap[$category];

//Fetch old images (Edit mode)
$oldImages = ['image1'=>null, 'image2'=>null];

if (!empty($data['id'])) {
    $stmt = $pdo->prepare("SELECT image1, image2 FROM $table WHERE id = ?");
    $stmt->execute([$data['id']]);
    $oldImages = $stmt->fetch(PDO::FETCH_ASSOC) ?: $oldImages;
}

//Image upload
$uploadDir = 'C:/Apache24/images/';

foreach (['image1','image2'] as $imgField) {

    if (!empty($_FILES[$imgField]['tmp_name'])) {

        $originalName = basename($_FILES[$imgField]['name']);
        $originalName = preg_replace("/[^a-zA-Z0-9_\.-]/", "_", $originalName); // Μόνο ασφαλείς χαρακτήρες
        $microtime = (int)(microtime(true) * 1000000);
        $newFilename = $microtime . '_' . $originalName;

        if (!move_uploaded_file($_FILES[$imgField]['tmp_name'], $uploadDir . $newFilename)) {
            echo json_encode(['status'=>'error','message'=>'Image upload failed']);
            exit;
        }

        $data[$imgField] = $newFilename;

    } else {
        //  Υπάρχουσα εικόνα
        $data[$imgField] = $oldImages[$imgField];
    }
}

// Allowed fields
$allowedFields = [
    'parking' => ['id','odos','arithmos','dimos_id','dimotiki_enotita_id','status','vehicle_type','car_plate','length','width','side_clearance_width','side_clearance_lr','ramp_nearby','accessible_route','simansi_stylou','road_marking','lighting','roof','street_view','comments','image1','image2','lat','lng'],
    'crossings' => ['id','odos1','arithmos1','odos2','arithmos2','dimos_id','dimotiki_enotita_id','typos_odou','nisida','zebra_painting','painting_date','street_lights_type','sidewalk_light','traffic_signal','signal_phase_duration','simansi_stylou','sound_signal','touch_device','light_position','street_view','comments','image1','image2','lat','lng'],
    'pedestrian_ramps' => ['id','odos','arithmos','dimos_id','dimotiki_enotita_id','length','width','slope','ground_marking','light_position','street_view','comments','image1','image2','lat','lng'],
    'building_ramps' => ['id','odos','arithmos','dimos_id','dimotiki_enotita_id','length','width','slope','door_width','door_type','push_button','tactile_paving','handrails','roof','ground_marking','simansi_styloy','lighting','street_view','comments','image1','image2','lat','lng']
];

$numericFields = [
    'parking' => ['length','width','side_clearance_width','side_clearance_lr'],
    'crossings' => ['signal_phase_duration'],
    'pedestrian_ramps' => ['length','width','slope'],
    'building_ramps' => ['length','width','slope','door_width']
];

// Prepare data
$fields = array_intersect(array_keys($data), $allowedFields[$table]);

$insertCols = [];
$insertVals = [];
$updateSet = [];
$params = [];

foreach ($fields as $field) {
    if ($field === 'lat' || $field === 'lng') continue;

    $insertCols[] = $field;
    $insertVals[] = ":$field";
    if ($field !== 'id') $updateSet[] = "$field = EXCLUDED.$field";

    $val = trim($data[$field]); // Έλεγχος για κενά που δεν χρειάζονται

    // Έλεγχος string
    if (!in_array($field, $numericFields[$table])) {
        $val = trim($val);
        $val = htmlspecialchars($val, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
        if ($val === '') $val = null;
    }

    // Έλεγχος numeric fields
    if (in_array($field, $numericFields[$table])) {
        $val = is_numeric($val) ? $val : null; // Έλεγχος, αν όχι αριθμός τότε null
    }

    $params[$field] = $val;
}

//Geometry
$insertCols[] = 'geom';
$insertVals[] = 'ST_SetSRID(ST_MakePoint(:lng, :lat),4326)';
$updateSet[] = 'geom = EXCLUDED.geom';

$params['lat'] = isset($data['lat']) ? (float)$data['lat'] : 0.0; // Έλεγχος γεωγραφικών συντεταγμένων
$params['lng'] = isset($data['lng']) ? (float)$data['lng'] : 0.0; // Έλεγχος γεωγραφικών συντεταγμένων

// Upsert
$sql = "
INSERT INTO $table (".implode(',',$insertCols).")
VALUES (".implode(',',$insertVals).")
ON CONFLICT (id)
DO UPDATE SET ".implode(',',$updateSet);

try {
    $stmt = $pdo->prepare($sql);
    foreach ($params as $k=>$v) {
        $stmt->bindValue(":$k", $v);
    }
    $stmt->execute();

    if (empty($data['id'])) {
        $data['id'] = $pdo->lastInsertId("{$table}_id_seq");
    }

// Αποφυγή εμφάνισης άλλων πληροφοριών όταν υπάρχει error
} catch (PDOException $e) {
    error_log($e->getMessage());
    echo json_encode(['status'=>'error','message'=>'Database error']);
    exit;
}

// Response
echo json_encode([
    'status'=>'success',
    'id'=>$data['id'],
    'image1'=>$data['image1'],
    'image2'=>$data['image2']
]);
