<?php

require_once($_SERVER['DOCUMENT_ROOT'] . '/sys/db.php');

foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "fkid") 
    $cu_id = $paramValue;  
  else if ($paramName == "id") 
    $su_id = $paramValue;  
  else if ($paramName == "name") 
    $name = $paramValue;  
  else if ($paramName == "mapareaid") 
    $mapareaid = $paramValue;  
}

$dal = new DAL();

if ($su_id == 0) {
    
  $sql = "SELECT OS.operation_id " .
         "FROM sitespatialunit SS, operationspatialunit OS " .
         "WHERE SS.culturalunit_id = $cu_id " .
         "AND OS.id = SS.operationspatialunit_id LIMIT 1 " ; 
  $op_id = $dal->query($sql)->operation_id;

  $su_id = hexdec(uniqid());

  $sql = "INSERT INTO spatialunit " .
         "(id, name, spatialunittype_id, mapareaid) " .
         "VALUES ($su_id, '$name', 5, '$mapareaid')";
  $result = $dal->query($sql);

  $os_id = hexdec(uniqid());

  $sql = "INSERT INTO operationspatialunit " .
         "(id, spatialunit_id, operation_id) " .
         "VALUES ($os_id, $su_id, $op_id) ";
  $result = $dal->query($sql);

  $ss_id = hexdec(uniqid());

  $sql = "INSERT INTO sitespatialunit " .
         "(id, culturalunit_id, operationspatialunit_id) " .
         "VALUES ($ss_id, $cu_id, $os_id) ";
  $result = $dal->query($sql);
    
}

else {
  $sql = "UPDATE spatialunit ". 
         "SET name='$name', mapareaid='$mapareaid' " .
         "WHERE id = $su_id ";
  $result = $dal->query($sql);
}
    
echo json_encode($su_id);

?>

