<?php

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

foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "fkeyid") 
    $pa_id = $paramValue;  
  else if ($paramName == "rowval") 
    $name = $paramValue;  
  else if ($paramName == "selid") 
    $pf_id = $paramValue;  
}

$dal = new DAL();

if ($pf_id == 0) {       

  $sql = "SELECT FO.seq FROM parcelfop PF, fop FO " .
         "WHERE PF.parcel_id = $pa_id AND FO.id = PF.fop_id " . 
         "ORDER BY FO.seq DESC LIMIT 1 " ;
  $lastSeq = $dal->query($sql)->seq;
  
  if (null === $lastSeq)
    $nextSeq = 1;
  else
    $nextSeq = $lastSeq + 1;

  $name = 'fop ' . $nextSeq;

  $fo_id = hexdec(uniqid());

  $sql = "INSERT INTO fop (id, name, seq) VALUES ($fo_id, '$name', $nextSeq) ";
  $result = $dal->query($sql);

  $pf_id = hexdec(uniqid());

  $sql = "INSERT INTO parcelfop " .
         "(id, parcel_id, fop_id) " .
         "VALUES ($pf_id, $pa_id, $fo_id) ";
  $result = $dal->query($sql);
}

else {
  $sql = "SELECT fop_id FROM parcelfop WHERE id = $pf_id LIMIT 1 " ;
  $fo_id = $dal->query($sql)->fop_id;
    
    
  $sql = "UPDATE fop SET name='$name' WHERE id = $fo_id ";
  $result = $dal->query($sql);
}
echo json_encode($pf_id);

?>

