<?php

require_once($_SERVER['DOCUMENT_ROOT'] . '/sys/db.php');
 
foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "id") 
    $pr_id = $paramValue; 
  else if ($paramName == "name") 
    $name = $paramValue; 
  else if ($paramName == "site_name") 
    $site_name = $paramValue; 
  else if ($paramName == "refno") 
    $refno = $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";
  }
    
  if ($site_name == "")
    $site_name = $name;

  $sql = "INSERT INTO project " .
         "(name, site_name, refno) " . 
         "VALUES ('$name', '$site_name', '$next_refno') ";
  $pr_id = $dal->query($sql);
  
  $sql = "INSERT INTO parcel " .
         "(project_id, name) " .
         "VALUES ($pr_id, '$next_refno: Study Area') ";
  $pa_id = $dal->query($sql);

  $sql = "INSERT INTO projectparcel " .
         "(project_id, parcel_id) " .
         "VALUES ($pr_id, $pa_id) ";
  $pa_id = $dal->query($sql);

    
}

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

echo json_encode($pr_id);

?>

