<?php

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

foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "selectid") 
    $su_id = $paramValue;  
  else if ($paramName == "elements") 
    $elements = $paramValue;  
  else if ($paramName == "rowids") 
    $rowids = $paramValue;  
  else if ($paramName == "values") 
    $values = $paramValue;  
}

$rowId =  explode (",", $rowids);
$element = explode (",", $elements);
$value = explode (",", $values);

$dal = new DAL();

for ($i=0; $i<count($rowId); $i++) {

  if ($rowId[$i] == 0) {

    
    list ($pointype_id, $pos) = explode(":", $value[$i]);

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

    $sp_id = hexdec(uniqid());
    $sql = "INSERT INTO spatialunitpoints (id, spatialunit_id, points_id, pointype_id) " .
           "VALUES ($sp_id, $su_id, $po_id, $pointype_id) ";
    $result = $dal->query($sql);
  }

  else if (strpos($element[$i], 'function') !== false) {
    $funcVal = array_map('intval', explode(':', $value[$i]))[0];

    if ($funcVal == -1) {
     $sql = "DELETE FROM spatialunitpoints WHERE id = $rowId[$i] ";
      $result = $dal->query($sql);
    }
  }
  
  else {

    if ($element[$i] == 'input:select') {
      list ($pointype_id, $pos) = explode(":", $value[$i]);
      $sql = "UPDATE points SET pos='$pos'  " .
             "WHERE id = " .
             "(SELECT points_id FROM spatialunitpoints WHERE id = $rowId[$i]) ";
      $result = $dal->query($sql);
      $sql = "UPDATE spatialunitpoints SET pointype_id=$pointype_id " .
             "WHERE id = $rowId[$i] ";
      $result = $dal->query($sql);
    }
    if ($element[$i] == 'input') {
      $pos = $value[$i];
      $sql = "UPDATE points SET pos='$pos'  " .
             "WHERE id = " .
             "(SELECT points_id FROM spatialunitpoints WHERE id = $rowId[$i]) ";
      $result = $dal->query($sql);
    }
    if ($element[$i] == 'select') {
      $pointype_id = $value[$i];
      $sql = "UPDATE spatialunitpoints SET pointype_id=$pointype_id " .
             "WHERE id = $rowId[$i] ";
      $result = $dal->query($sql);
    }
  }    
}
    
echo json_encode($cu_id);

?>

