<?php
/*=======================================================================
 *
 * cron_export4job2.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/

// include_once ("../include/auth.inc.php");
include_once ("../include/mcglobal.inc.php");


// Overload function because of call by console
function authCheckEmployeeRights($emp_id, $menuModeId, $referer = "") {
  return true;
}

// Check process is still running
// ..........

$retVal = "OK";
$userTypeName = "hq";
$errMsg = "";
$hq_id = "";
$usr_id = "";
if (!isset($argv[1]) || $argv[1] != "acapella7890") :
   $errMsg = "watchdog cron export.job2 failed by access code";
endif;

if ($errMsg != "") :
   sendInternalMail($errMsg);
   die();
endif;

// Execution-Time for script
set_time_limit(30000);

$path = getAbsoluteSystemPath();

$constAmStarttimeInDays = 4;
$startTime = getDateTime("datetime_plus_offset", array(0,0,0,0,-($constAmStarttimeInDays),0), "Y-m-d H:i:s");

// Get all failed tasks writing to job2 by exports
$sqlquery = "SELECT DISTINCT jb.jb_export_time, jb.hq_id, COUNT(*) AS num, exl.exl_id"
          . " FROM job AS jb LEFT JOIN exportlog AS exl ON jb.jb_export_time = exl.exl_exporttime"
          . " WHERE jb.jb_export_time >= '" . $startTime . "' AND"
          . "       jb.jb_export_time < '9999-12-31 23:59:59'  AND"
          . "       (NOT EXISTS (SELECT * FROM job2 AS jb2 WHERE jb2.jb_id = jb.jb_id))"
          . " GROUP BY jb.jb_export_time";
$result = $db->query($sqlquery);
$job2Array = array();
if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
while ($row = $result->fetch_assoc()):
      $job2Array[] = array($row["exl_id"], $row["hq_id"], $row["jb_export_time"], $row["num"]);
endwhile;
$result->free();

$job2ArrayLen = count($job2Array);
if ($job2ArrayLen > 0)  :
   $retVal = "NOK";
   for ($i = 0; $i < $job2ArrayLen; $i++) :
       $exl_id = $job2Array[$i][0];
       $hq_id = $job2Array[$i][1];
       $empIdRootAdmin = getEmpIdOfRootAdmin($userTypeName);  // In the loop because refers to global $hq_id
       $usr_id = getFieldValueFromId("employee", "emp_id", $empIdRootAdmin, "usr_id");
       $call_counter = "1";

       // Call script to write "job2"
       if ($exl_id != "" && $hq_id != "" && $usr_id != "" && $call_counter != "") :
          $mcDebugExportErrLogFile = $path . "/log/job2exec_" . $hq_id . "_err.stdout+err";
          $cmd = "php " . $path . "/export/export4job2.php acapella7890 " . $hq_id . " " . $usr_id . " " . $exl_id . " " . $call_counter . " > " . $mcDebugExportErrLogFile . " 2>&1 &";
          system($cmd);
       endif;
echo $exl_id . " " . $hq_id . " " . $usr_id . " " . $call_counter . "\n";
// die();
   endfor;
endif;

echo $retVal;
