<?php

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

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

$dal = new DAL();

$sql = "SELECT LO.name_seq " .
       "FROM projectworkday PW, projectworkdayoperation PWO, " .
       "operationspatialunit OS, spatialunitlot SL, lot LO " .
       "WHERE PW.parcel_id = $pa_id AND PWO.projectworkday_id = PW.id " .
       "AND OS.projectworkdayoperation_id = PWO.id AND SL.operationspatialunit_id = OS.id " .
       "AND LO.id = SL.lot_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;

$lo_id = hexdec(uniqid());

$sql = "INSERT INTO lot " .
       "(id, name, name_seq) VALUES ($lo_id, '$lot_name', $next_seq) " ;
$result = $dal->query($sql);

$co_id = hexdec(uniqid());

$sql = "INSERT INTO composition (id) VALUES ($co_id) " ;
$result = $dal->query($sql);

$lc_id = hexdec(uniqid());

$sql = "INSERT INTO lotcomposition " .
       "(id, lot_id, composition_id) VALUES ($lc_id, $lo_id, $co_id) " ;
$result = $dal->query($sql);

$sl_id = hexdec(uniqid());

$sql = "INSERT INTO spatialunitlot (id, operationspatialunit_id, lot_id) " .
       "VALUES ($sl_id, $operationspatialunit_id, $lo_id) ";
$result = $dal->query($sql);

$slp_id = hexdec(uniqid());

$sql = "INSERT INTO spatialunitlotpoints " .
       "(id, spatialunitlot_id) " .
       "VALUES ($slp, $sl_id) "; 
$result = $dal->query($sql);

$el_id = hexdec(uniqid());

$sql = "INSERT INTO elevation " .
       "(id, spatialunitlotpoints_id) " .
       "VALUES ($el_id, $slp_id) "; 
$result = $dal->query($sql);
  
$de_id = hexdec(uniqid());

$sql = "INSERT INTO depth " .
       "(id, spatialunitlot_id) " .
       "VALUES ($de_id, $sl_id) "; 
$result = $dal->query($sql);
  
$lcu_id = hexdec(uniqid());

$sql = "INSERT INTO lotculturalunit " .
       "(id, culturalunit_id, spatialunitlot_id) " .
       "VALUES ($lcu_id, $cu_id, $sl_id) "; 
$result = $dal->query($sql);

echo json_encode($result);

?>

