<?php

require_once($_SERVER['DOCUMENT_ROOT'] . '/sys/db.php');
 
foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "id") 
    $cu_id = $paramValue; 
  else if ($paramName == "projectparcel_fk") 
    $pp_id = $paramValue; 
  else if ($paramName == "dailyoperation_fk") 
    $pwo_id = $paramValue; 
  else if ($paramName == "propertypart_fk") 
    $su_id = $paramValue; 
}

$dal = new DAL();

if ($cu_id == 0) {

  $sql = "SELECT CU.name_seq " .
         "FROM projectparcelspatialunit PS, " .
         "culturalunitspatialunit CS, culturalunit CU " .
         "WHERE PS.projectparcel_id = $pp_id " .
         "AND CS.spatialunit_id = PS.spatialunit_id AND CU.id = CS.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;

  $sql = "SELECT PR.site_name " .
         "FROM projectparcel PP, project PR " .
         "WHERE PP.id = $pp_id AND PR.id = PP.project_id " .
         "LIMIT 1 " ;
  $site_name = $dal->query($sql)->site_name;

  $name = "$site_name $next_seq";

  $cu_id = hexdec(uniqid());

  $sql = "INSERT INTO culturalunit " .
         "(id, name, name_seq) VALUES ($cu_id, '$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);

  $cs_id = hexdec(uniqid());

  $sql = "INSERT INTO culturalunitspatialunit " .
         "(id, spatialunit_id, culturalunit_id, projectworkdayoperation_id) " .
         "VALUES ($cs_id, $su_id, $cu_id, $pwo_id) ";
  $result = $dal->query($sql);
  
  $sql = "SELECT id from projectworkdayoperationspatialunit " .
         "WHERE spatialunit_id = $su_id AND projectworkdayoperation_id = $pwo_id ";
  $result = $dal->query($sql);
  
  if (null === $result) {

    $pos_id = hexdec(uniqid());

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

echo json_encode($cu_id);

?>


