<?php

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

foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "spatialunitlot_id")
    $spatialunitlot_id = $paramValue;
  elseif ($paramName == "activitytype_id") 
    $activitytype_id = $paramValue;  
  elseif ($paramName == "int_descr") 
    $int_descr = $paramValue;  
  elseif ($paramName == "int_rationale") 
    $int_rationale = $paramValue;  
}

$dal = new DAL();

$sql = "SELECT SL.id AS spatialunitlot_id, OA.activitytype_id, " .
       "OD.descr AS int_descr, OD.rationale AS int_rationale " .
       "FROM operationspatialunitactivity OA, operationactivitydetail OD, " .
       "activitytype AT, operationspatialunit OS, spatialunitlot SL " . 
       "WHERE SL.id = $sl_id AND OS.id = SL.operationspatialunit_id " .
       "AND OA.operationspatialunit_id = OS.id AND AT.id = activitytype_id " .
       "AND OD.operationspatialunitactivity_id = OS.id LIMIT 1 ";
$result = $dal->query($sql);

$sql = "SELECT id " .
       "FROM operationspatialunitactivity " .
       "WHERE id = $sl_id LIMIT 1 ";
$result = $dal->query($sql);

if (null == $result) {

  $osa_id = hexdec(uniqid());

  sql = "INSERT INTO operationspatialunitactivity " .
        "(id, spatialunitlot_id, activitytype_id) " .
        "VALUES ($osa_id, $spatialunitlot_id, $activitytype_id) " ;
  $result = $dal->query($sql);
  
  $oad_id = hexdec(uniqid());

  $sql = "INSERT INTO operationactivitydetail " .
         "(id, operationspatialunitactivity_id descr, rationale) " .
         "VALUES ($oad_id, $osa_id, $int_descr, $int_rationale) " ;
  $result = $dal->query($sql)->id;
}
else {        

  $sql = "UPDATE operationspatialunitactivity SET " .
         "spatialunitlot_id='$spatialunitlot_id', activitytype_id=$activitytype_id " .
         "WHERE id = $sl_id " ;
  $result = $dal->query($sql);

  $sql = "UPDATE operationactivitydetail SET " .
         "descr='$int_descr', rationale='$int_rationale' " .
         "WHERE operationspatialunitactivity_id = $sl_id ";
  $result = $dal->query($sql);
}

echo json_encode($result);

?>

