<?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 ($type, $value, $exten) = explode(":", $value[$i]);
    
    $sql = "SELECT id FROM telno " .
           "WHERE value = '$value' AND exten = '$exten' " .
           "LIMIT 1 ";
    $tn_id = $dal->query($sql)->id;
           
    if (null === $tn_id) {       

//      $tn_id = hexdec(uniqid());
      $sql = "INSERT INTO telno " .
             "(value, exten) " .
             "VALUES ('$value', '$exten') ";
      $tn_id = $dal->query($sql);
    }
    
    $oct_id = hexdec(uniqid());
    $sql = "INSERT INTO organizationcontactelno " .
           "(id, organizationcontact_id, telno_id, telnotype) " .
           "VALUES ($oct_id, $oc_id, $tn_id, '$type') ";
    $result = $dal->query($sql);
    
  }

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

    if (($rowEle[0] ==  'select') && array_map('intval', explode(':', $value[$i]))[0] == -1) {
      $sql = "DELETE FROM organizationcontactelno 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') {
          $sql = "UPDATE organizationcontactelno " .
                 "SET telnotype='$rowVal[$j] " .
                 "WHERE id = $rowId[$i] ";
          $result = $dal->query($sql);
        }
        
        else {
          if ($rowEle[$j] ==  'input1') {
            $set .= "$comma value='$rowVal[$j]'";  
            $comma = ",";  
          }
          else if ($rowEle[$j] ==  'input2') {
            $set .= "$comma exten='$rowVal[$j]'";  
            $comma = ",";  
          }
          $sql = "UPDATE telno " .
                 "SET $set " .
                 "WHERE id = $rowId[$i] ";
          $result = $dal->query($sql);
        }
      }        
    }
  }
}

echo json_encode($oc_id);

?>

