<?php

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

foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "selectid") 
    $oc_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 ($status_id, $title, $dept, $date) = explode(":", $value[$i]);

    $ocj_id = hexdec(uniqid());

    $sql = "INSERT INTO organizationcontactjobtitle " .
           "(id, organizationcontact_id, status_id, title, department, date) " .
           "VALUES ($ocj_id, $oc_id, $status_id, '$title', '$dept', '$date') ";
    $result = $dal->query($sql);
  }

  else {
    $rowEle = explode (":", $element[$i]);

    if (($rowEle[0] ==  'select') && array_map('intval', explode(':', $value[$i]))[0] == -1) {
      $sql = "DELETE FROM organizationcontactjobtitle WHERE id = $rowId[$i] ";
      $result = $dal->query($sql);
    }

    else {
      $rowVal = explode (":", $value[$i]);
      $comma = "";  
      $set = "";
      for ($j=0; $j<count($rowEle); $j++) {
        if ($rowEle[$j] ==  'select') {
          $set .= "$comma status_id=$rowVal[$j]";  
          $comma = ",";  
        }
        else if ($rowEle[$j] ==  'input1') {
          $set .= "$comma title='$rowVal[$j]'";  
          $comma = ",";  
        }
        else if ($rowEle[$j] ==  'input2') {
          $set .= "$comma department='$rowVal[$j]'";  
          $comma = ",";  
        }
        else if ($rowEle[$j] ==  'date') {
          $set .= "$comma date='$rowVal[$j]'";  
          $comma = ",";  
        }
      }        
      
      $sql = "UPDATE organizationcontactjobtitle " .
             "SET $set " .
             "WHERE id = $rowId[$i] ";
      $result = $dal->query($sql);
    }
  }
}

echo json_encode($oc_id);

?>

