<?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++) {
//print_r ("el:");
//$idx = strpos($element[$i], 'function');
//print_r ($idx);
    
  if ($rowId[$i] == 0) {

    $ci_id = hexdec(uniqid());
    
    list ($af_id, $ar_id) = explode(":", $value[$i]);

    $sql = "INSERT INTO culturalunitinterpret (id, culturalunit_id, affiliation_id, archfunction_id) " .
           "VALUES ($ci_id, $cu_id, $af_id, $ar_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 culturalunitinterpret WHERE id = $rowId[$i] ";
      $result = $dal->query($sql);
    }
  }
  
  else {
    if ($element[$i] == 'select1:select2') {
      list ($af_id, $ar_id) = explode(":", $values[$i]);
      $assign = "affiliation_id=$af_id, archfunction_id=$ar_id ";
    }
    if ($element[$i] == 'select1') {
      $af_id = $values[$i];
      $assign = "affiliation_id=$af_id ";
    }
    if ($element[$i] == 'select2') {
      $ar_id = $values[$i];
      $assign = "archfunction_id=$ar_id ";
    }
    $sql = "UPDATE culturalunitinterpret SET $assign  " .
           "WHERE id = $rowId[$i] ";
    $result = $dal->query($sql);
  }    
}
    
echo json_encode($cu_id);

?>

