<?php

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

foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "baseid") 
    $pa_id = $paramValue;  
  else if ($paramName == "rowid") 
    $cu_id = $paramValue; 
  else if ($paramName == "rowval") 
    $site_name = $paramValue; 
  else if ($paramName == "os_id") 
    $os_id = $paramValue;  
}

$dal = new DAL();

if ($cu_id == 0) {

  $sql = "SELECT CU.name_seq " .
         "FROM projectworkday PW, projectworkdayoperation PWO, operationspatialunit OS, " . 
         "spatialunit SU, sitespatialunit SS, culturalunit CU " .
         "WHERE PW.parcel_id = $pa_id AND PWO.projectworkday_id = PW.id " .
         "AND OS.projectworkdayoperation_id = PWO.id AND SU.id = OS.spatialunit_id " .
         "AND SU.spatialunittype_id = 1 AND SS.operationspatialunit_id  = OS.id " .
         "AND CU.id = SS.culturalunit_id " .
         "ORDER BY name_seq DESC LIMIT 1 " ;
  $result = $dal->query($sql);       
  if (null == $result)
    $next_seq = 1; 
  else
    $next_seq = $result->name_seq + 1;

  $cu_id = hexdec(uniqid());

  $sql = "INSERT INTO culturalunit " .
         "(id, name, name_seq) VALUES ($cu_id, '$site_name', $next_seq)  " ;
  $result = $dal->query($sql);

  $si_id = hexdec(uniqid());

  $sql = "INSERT INTO site (id, culturalunit_id) VALUES ($si_id, $cu_id) ";
  $result = $dal->query($sql);

  $ss_id = hexdec(uniqid());

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

else {

  $ss_id = hexdec(uniqid());

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

echo json_encode($cu_id);

?>

