<?php

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

foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "selectid") 
    $cu_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 ($mapid, $density) = explode(":", $value[$i]);

    $sc_id = hexdec(uniqid());
    $sql = "INSERT INTO surfaceconcentration (id, culturalunit_id, mapid, density) " .
           "VALUES ($sc_id, $cu_id, $mapid, $density) ";
    $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 surfaceconcentration WHERE id = $rowId[$i] ";
      $result = $dal->query($sql);
    }
  }
  
  else {
    if ($element[$i] == 'input1:input2') {
      list ($af_id, $ar_id) = explode(":", $values[$i]);
      $assign = "mapid=$mapid, density=$density ";
    }
    if ($element[$i] == 'input1') {
      $af_id = $values[$i];
      $assign = "mapid=$mapid ";
    }
    if ($element[$i] == 'input2') {
      $ar_id = $values[$i];
      $assign = "density=$density ";
    }
    $sql = "UPDATE surfaceconcentration SET $assign  " .
           "WHERE id = $rowId[$i] ";
    $result = $dal->query($sql);
  }    
}

echo json_encode($cu_id);

?>

