<?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 ($descr,$cardinal_id) = explode(":", $value[$i]);

    $bo_id = hexdec(uniqid());

    $sql = "INSERT INTO bound (id, cardinal_id, descr, part_id) " .
           "VALUES ($bo_id, '$cardinal_id', '$descr', " .
           "(SELECT id FROM part WHERE spatialunit_id = $su_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 bound WHERE id = $rowId[$i] ";
      $result = $dal->query($sql);
    }
  }
  
  else {

    if ($element[$i] == 'input:select') {
      list ($descr,$cardinal_id) = explode(":", $value[$i]);
      $assign = "cardinal_id=$cardinal_id, 'descr=$descr' ";
    }
    else if ($element[$i] == 'input') {
      $pos = $value[$i];
      $assign = "'descr=$descr' ";
    }
    else if ($element[$i] == 'select') {
      $assign = "cardinal_id=$cardinal_id ";
    }
    $sql = "UPDATE bounds SET $assign  " .
           "WHERE id = $rowId[$i] ";
  }    
}

echo json_encode($su_id);

?>

