<?php

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

foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "summaryid") 
    $oc_id = $paramValue;  
  else if ($paramName == "addname") 
    $name = $paramValue;  
  else if ($paramName == "selid") 
    $pr_id = $paramValue;  
}

$dal = new DAL();

if ($pr_id == 0) {         

  $year = date("Y");
  $sql = "SELECT refno FROM project WHERE refno LIKE '$year%' " .
         "ORDER BY refno DESC LIMIT 1 " ;
  $refno = $dal->query($sql)->refno;  

  if (null == $refno)
    $next_refno = "$year-0001"; 
  else {
    $seq = intval (substr ($refno, strpos ($refno, "-") + 1)) + 1;
    $seq = str_pad($seq, 4, "0", STR_PAD_LEFT);
    $next_refno = "$year-$seq";
  }

  $sql = "INSERT INTO project (name, refno, site_name) " .
         "VALUES ('$name', '$next_refno', '$next_refno') ";
  $pr_id = $dal->query($sql);

  $sql = "INSERT INTO projectorganizationcontact " .
         "(project_id, organizationcontact_id) " .
         "VALUES ($pr_id, $oc_id) ";
  $result = $dal->query($sql);
}

else {
  $sql = "UPDATE project SET name='$name' WHERE id = $pr_id ";
  $result = $dal->query($sql);
}
    

echo json_encode($pr_id);

?>

