<?php

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

foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "id")
    $mp_id = $paramValue;
  else if ($paramName == "procedurename")
    $procedurename = $paramValue;
  else if ($paramName == "routinename")
    $routinename = $paramValue;
  else if ($paramName == "proceduredescr")
    $proceduredescr = $paramValue;
  else if ($paramName == "comments")
    $comments = $paramValue;
  else if ($paramName == "filename")
    $filename = $paramValue;
}

$dal = new DAL(); 

$sql = "SELECT ROUTINE_NAME FROM INFORMATION_SCHEMA.ROUTINES " .
       "WHERE ROUTINE_NAME = '$routinename' LIMIT 1 " ;
$rd = $dal->query($sql);

$sql = "SELECT PARAMETER_NAME as name FROM information_schema.parameters " . 
       "WHERE SPECIFIC_NAME = '$routinename' AND ROUTINE_TYPE = 'PROCEDURE' ";
$params = $dal->query($sql);

$parameters = '';
$comma = '';
foreach ($params as $param) {
  $parameters .= $comma . $param->name;
  $comma = ',';
}

if ($mp_id == 0) {
  $sql = "INSERT INTO misprocedure " .
         "(procedurename, routinename, proceduredescr, " .
         "comments, parameters, filename) " .
         "VALUES ('$procedurename', '$routinename', '$proceduredescr', " .
         "'$comments', '$parameters', '$filename') " ;
  $mp_id = $dal->query($sql);
}

else {
  $sql = "UPDATE misprocedure SET " .
         "procedurename='$procedurename', routinename='$routinename', " .
         "proceduredescr='$proceduredescr', comments='$comments', " .
         "parameters='$parameters', filename='$filename' " .
         "WHERE id = $mp_id ";
  $result = $dal->query($sql);
}         


echo json_encode($mp_id);

?>

