<?php

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

foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "id") 
    $su_id = $paramValue;  
  else if ($paramName == "projectparcel_fk") 
    $pp_id = $paramValue;  
  else if ($paramName == "sitedefinition_fk") 
    $cu_id = $paramValue;  
  else if ($paramName == "dailyoperation_fk") 
    $pwo_id = $paramValue;  
  else if ($paramName == "name") 
    $name = $paramValue;  
  else if ($paramName == "mapid") 
    $mapid = $paramValue;  
  else if ($paramName == "device_id") 
    $device_id = $paramValue;  
  else if ($paramName == "pos") 
    $pos = $paramValue;  
}

$dal = new DAL();

if ($su_id == 0) {

  $sql = "SELECT name_seq " .
         "FROM spatialunit SU, projectparcelspatialunit PS " .
         "WHERE PS.projectparcel_id = $pp_id " .
         "AND SU.id = PS.spatialunit_id AND spatialunitype_id = 5 " .
         "ORDER BY name_seq DESC LIMIT 1 " ;
  $result = $dal->query($sql);  

  if (null == $result)
    $next_seq = 1; 
  else
    $next_seq = $result->name_seq + 1;
  
  $name = "PTP $next_seq";

  $su_id = hexdec(uniqid());
  $sql = "INSERT INTO spatialunit " .
         "(id, name, spatialunitype_id, name_seq) " .
         "VALUES ($su_id, '$name', 5, $next_seq) " ;
  $result = $dal->query($sql);

  $ps_id = hexdec(uniqid());
  $sql = "INSERT INTO projectparcelspatialunit " .
         "(id, spatialunit_id, projectparcel_id) " .
         "VALUES ($ps_id, $su_id, $pp_id) " ;
  $result = $dal->query($sql);

  $pos_id = hexdec(uniqid());

  $sql = "INSERT INTO projectworkdayoperationspatialunit " .
         "(id, spatialunit_id, projectworkdayoperation_id) " .
         "VALUES ($pos_id, $su_id, $pwo_id) ";
  $result = $dal->query($sql);

  $cs_id = hexdec(uniqid());

  $sql = "INSERT INTO culturalunitspatialunit " .
         "(id, culturalunit_id, projectworkdayoperation_id) " .
         "VALUES ($cs_id, $cu_id, $pwo_id) ";
  $result = $dal->query($sql);

  $po_id = hexdec(uniqid());

  $sql = "INSERT INTO points " .
         "(id, device_id, pos) VALUES ($po_id, $device_id, $pos) " ;
  $result = $dal->query($sql);

  $sp_id = hexdec(uniqid());
  $sql = "INSERT INTO spatialunitpoints " .
         "(id, spatialunit_id, points_id) VALUES ($sp_id, $su_id, $po_id) " ;

  $si_id = hexdec(uniqid());
  $sql = "INSERT INTO siteintensification " .
         "(id, culturalunit_id) VALUES ($si_id, $cu_id) " ;
  $result = $dal->query($sql);
}

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

//  $sql = "UPDATE siteintensification SET " .
//         "intensificationtype_id=$intensificationtype_id, " .
//         "modification='$modification', rationale='$rationale'" .
//         "WHERE id = $si_id " ;
//  $result = $dal->query($sql);
    
}
    
echo json_encode($su_id);

?>

