<?php

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

function lastCombine ($id) {

  $dal = new DAL();

  $sql = "SELECT id, name, repdescription, combineidx, combinequery_id " .
         "FROM reportquery " .
         "WHERE id = $id  AND combineidx > 0 AND active = 1 LIMIT 1" ;
  $report = $dal->query($sql);

  if ($report->combinequery_id > 0) {
   lastCombine ($report->combinequery_id, $combines); 
  }
  else {
    $last = [$report->id, $report->name, $report->repdescription, $report->combineidx];
    return $last;
  }    
}  
 
foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "id")
    $rg_id = $paramValue;
  elseif ($paramName == "opt") 
    $combinetype_id = $paramValue;  
}

$dal = new DAL(); 

$sql = "UPDATE reportquery SET " .
       "combineidx=1  " .
       "WHERE id = $rg_id " ;
$result = $dal->query($sql);

list($id, $name, $repdescription, $combineidx) = lastCombine($rg_id);
$combineidx++;

$sql = "INSERT INTO reportquery " .
       "(name, repdescription, combinetype_id, combineidx) " .
       "VALUES ('$name', '$repdescription', $combinetype_id, $combineidx) " ;
$combinequery_id = $dal->query($sql);

$sql = "UPDATE reportquery SET " .
       "combinequery_id=$combinequery_id  " .
       "WHERE id = $id " ;
$result = $dal->query($sql);

echo json_encode($combinequery_id);

?>

