<?php
/*
  Adds to results table (to be picked up by simulation server) only if there are
  currently less than maximum allowed jobs being run by this user.
  Will error if maximum jobs are being run and not add this job.

  If this model has already run then previous results will not be touched but a new simulation will be started.
*/

require "../Pages/UserAdmin/super_secret_stuff.php";
require "CommonFunc.php";
if(!empty($_GET["auth"]) && !empty($_GET["pid"]) && !empty($_GET["mode"])){
  $con = mysqli_connect($website,$mysqli_username,$pw,$dbase);

  // Input error checks
  $auth = $_GET["auth"];
  $user_id = userid($con,$auth);
  if($user_id <= 0)goto errormsg1;

  $projid = $_GET["pid"];
  $pid = projid($con,$projid,$user_id);
  if($pid <= 0)goto errormsg2;
  
  // Get project name (to add to output file)
  $res = mysqli_query($con,"GET name FROM calibro_projects WHERE calproj_id = {$pid}");
  $row = mysqli_fetch_array($res);
  $mname = str_replace(' ', '_', $row[0]);
  $now = date("ymdhis");
  $jsonfile = "calibro_report_{$mname}_{$now}.json";
  $pdffile  = "calibro_report_{$mname}_{$now}.pdf";


  $mode = $_GET["mode"];
  if($mode != "pdf" && $mode != "json")goto errormsg3;

  // Delete old results
  $path = $proj_file_path_deep . "job_" . $pid . "/";
  $jsonfile = $path . $jsonfile;
  $pdffile  = $path . $pdffile;
  if(!file_exists($path))mkdir($path);
  if(file_exists($jsonfile))unlink($jsonfile);
  if(file_exists($pdffile) )unlink($pdffile);
 // echo ("DEBUG: path = {$path}<br/>");
  // consider deleting the below sleep line
  sleep(20); // if file is on network then wait for some time so that get_result below will not get the old results (crude but should work)
  mysqli_query($con,"DELETE FROM calibro_results WHERE calproj_id = {$pid}");
  
  // Simulate
  mysqli_query($con,"INSERT INTO Calibro_results(calproj_id,result,submitted_by) VALUES({$pid},0,{$user_id})");
  mysqli_close($con);

  // Fetch result
  get_result($path,$mode);

}else{
  echo ("ERROR in RunPAM.php: authentication code or project id or PAM or mode not provided!");
}
exit;

errormsg1: echo ("ERROR in AddModel.php: bad authentication code"); goto theend;
errormsg2: echo ("ERROR in AddModel.php: bad project id"); goto theend;
errormsg3: echo ("ERROR in AddModel.php: bad mode"); goto theend;
theend:
mysqli_close($con);
exit;
?>
