<?php
require_once '../../../autoload.php';
error_log ( "### modify_masterstudy..." );
$data_in = json_decode(file_get_contents('php://input'), true);
$sqlupdate = '';
$rstud_idlistadd = '';
$rstud_idlistdel = '';
$mstud_id = '-1';
foreach ($data_in as $value)
{
    $mstud_id = $value['newmstudid'];

    //commandes
    if($value['action'] == 'add')
    {

      if($value['mstudid'] != $value['newmstudid'])
      {
        if($rstud_idlistadd =='')
        {
          $rstud_idlistadd = $value['rstudid'];
        }else{
          $rstud_idlistadd .= ','.$value['rstudid'];
        }
      }


    }
    else 
      if($value['action'] == 'del')
      {
        if($value['mstudid'] != '-1')
        {
          if($rstud_idlistdel == '')
          {
            $rstud_idlistdel = $value['rstudid'];
          }
          else
          {
            $rstud_idlistdel .= ','.$value['rstudid'];
          }
        }
      }
}

$sql = '';
if($rstud_idlistadd != '')
{
  $sql .= "update raw_study_description set mstud_id = $mstud_id where rstud_id in ($rstud_idlistadd);";
  $sql .= "update raw_study_description set desc_id = null from master_study_description where raw_study_description.mstud_id = master_study_description.mstud_id and raw_study_description.mstud_id = $mstud_id and master_study_description.desc_id is not null;";
  $sql .= "update study set mstud_id_auto = $mstud_id , description_auto = description from master_study_description where master_study_description.mstud_id =$mstud_id and rstud_id in ($rstud_idlistadd);";
}
if($rstud_idlistdel != '')
{
  $sql .= "update raw_study_description set mstud_id = -1 where rstud_id in ($rstud_idlistdel);";
  $sql .= "update study set mstud_id_auto = -1 , description_auto = description from raw_study_description where raw_study_description.rstud_id = study.rstud_id and study.rstud_id in ($rstud_idlistdel);";
}

if($sql != '')
{
  $conn = get_dbconnection();

  if($conn)
  {
    	if ( pg_query($conn,$sql) == false )
          echo json_encode(["status" => "Error"]);
      else
          echo json_encode(["status" => "OK"]);
  }
}
else
  echo json_encode(["status" => "Error"]);
?>
