<?php
/*=======================================================================
 *
 * 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;
}


$errMsg = "";
$hq_id = "";
$usr_id = "";
if (isset($argv[1]) && $argv[1] == "acapella7890") :
   if (isset($argv[2]) && $argv[2] != "") : 
      $hq_id = $argv[2];
      if (isset($argv[3]) && $argv[3] != "") : 
         $usr_id = $argv[3];
         if (isset($argv[4]) && $argv[4] != "") :
            $exl_id = $argv[4];
            if (isset($argv[5]) && $argv[5] != "") :
               $call_counter = $argv[5];
            endif;
         else :
            $errMsg = "export.job2 failed by missing exportlog ID";
         endif;
      else :
         $errMsg = "export.job2 failed by missing user ID";
      endif;
   else :
      $errMsg = "export.job2 failed by missing headquarters ID";
   endif;
else :
   $errMsg = "export.job2 failed by access code";
endif;

if ($errMsg != "") :
   sendInternalMail($errMsg . " [HQ_ID:" . $hq_id . "] " . " [USR_ID:" . $usr_id . "] ");
   die();
endif;

ini_set('memory_limit', '256M');

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


// include_once ("../include/ftp.inc.php");
include_once ("../include/html.inc.php");
include_once ("../include/inc_job.inc.php");
$automailer = "INIT";
include_once ("../include/jb_detail_history.inc.php");


// Get table names (currently only for make jobs persistent in "jb_history_data")
getDBNames($dbhistory);

// Define global parameters
defineGlobalParameters($hq_id);


// **** Write historic job data ****

$maxCalls = 50;
if (isset($call_counter)) :
   $call_counter++;
   if ($call_counter >= $maxCalls) :
      $errMsg = "export.job2 terminated by reaching maximum calls";
      sendInternalMail($errMsg . " [HQ_ID:" . $hq_id . "] " . " [USR_ID:" . $usr_id . "] " . " [EXL_ID:" . $exl_id . "] " . " [MAX_CALLS:" . $maxCalls . "] ");
      die();
   endif;
else :
   $call_counter = 1;
endif;


$stringOfExportedIds = getFieldValueFromId("exportlog", "exl_id", $exl_id, "exl_rows");
if ($stringOfExportedIds == "") :
   $errMsg = "export.job2 failed by missing job IDs from exportlog";
   sendInternalMail($errMsg . " [HQ_ID:" . $hq_id . "] " . " [USR_ID:" . $usr_id . "] " . " [EXL_ID:" . $exl_id . "] ");
   die();
endif;

// Get all job IDs of the current exportlog row NOT existing in job2
$sqlquery = "SELECT jb.jb_id FROM job AS jb WHERE jb.jb_id IN (" . $stringOfExportedIds . ") AND (NOT EXISTS (SELECT * FROM job2 AS jb2 WHERE jb2.jb_id = jb.jb_id))";
// echo "\n\n" . $sqlquery . "\n\n"; die();
$result = $db->query($sqlquery);
if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
$arrayOfExportedIds = array();
while ($row = $result->fetch_assoc()):   
      $arrayOfExportedIds[] = $row["jb_id"];
endwhile;
$result->free();

$arrayOfExportedIdsLen = count($arrayOfExportedIds);
if ($arrayOfExportedIdsLen > 0) :

   // Check global usage of the context menu
   $maskJobInternalRemarkItems = getParameterValue("0", "MASK_JOBDETAILS_INTERNAL_REMARK_ITEMS", $hq_id);
   if ($maskJobInternalRemarkItems != "1") : $maskJobInternalRemarkItems = getParameterValue("0", "MASK_JOBDETAILS_INTERNAL_REMARK_ITEMS", "0"); endif;

   $f_act_rem = $f_act;
   $f_act = "";
   
   $mcDebugExportLogFile = "../log/job2exec_" . $hq_id . ".log";
   writeToFile($mcDebugExportLogFile, "----------------------------------------------------------------------------------------------");
   writeToFile($mcDebugExportLogFile, "[HQ_ID:" . $hq_id . "] " . " [USR_ID:" . $usr_id . "] " . " [EXL_ID:" . $exl_id . "]");
   writeToFile($mcDebugExportLogFile, "#JobsExported: " . $arrayOfExportedIdsLen);

   for ($x = 0; $x < $arrayOfExportedIdsLen; $x++) :

       $job_id = $arrayOfExportedIds[$x];
       $tmpDelimiter = "-;-";
       writeToFile($mcDebugExportLogFile, $job_id);
       // [1.] Store view of the headquarters and store raw data of the job (also headquarters view)
       $jobentry = ""; $tourentry = ""; $jobcosts = ""; $courierentry = ""; $employeeentry = "";
       $userTypeName = "hq";
       $tmpJobDataArray = getJobSnapshot($job_id, "1");
       $currentJobRawData = $tmpJobDataArray[0];
       $currentJobParameterState = $tmpJobDataArray[1];
       $currentJobRawData = str_replace('\'', '\\\'', $currentJobRawData);
       $jbHistoryData = $currentJobParameterState . $tmpDelimiter . $jobentry . $tmpDelimiter . $tourentry
                      . $tmpDelimiter . $jobcosts . $tmpDelimiter . $courierentry . $tmpDelimiter . $employeeentry;
       $jbHistoryData = str_replace('\'', '\\\'', $jbHistoryData);

       // $sqlquery = "UPDATE job SET jb_history_data = '" . $jbHistoryData . "' WHERE jb_id = '" . $job_id . "'";
       // $result = $db->query($sqlquery);
       // if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
       
       $currentJobRawData = escapeMysqlForBinary(compress($currentJobRawData));
       $jbHistoryData = escapeMysqlForBinary(compress($jbHistoryData));
       
       $opState = "::";
       if (existsEntry("job2",array("jb_id",$job_id))) :
           $res = updateStmt("job2", "jb_id", $job_id, array("jb2_history_rawdata", $currentJobRawData));
           if ($db->affected_rows > 0) :
              $opState .= " [RAWDATA.UPD => OK]";
           else :
              $opState .= " [RAWDATA.UPD => NOK]";
           endif;
       else:
           insertStmt("job2", array("jb_id", $job_id, "jb2_history_rawdata", $currentJobRawData));
           $opState .= " [RAWDATA.INS]";
       endif;
       if (existsEntry("job2",array("jb_id",$job_id))) :
           $res = updateStmt("job2", "jb_id", $job_id, array("jb2_history_hq", $jbHistoryData));
           if ($db->affected_rows > 0) :
              $opState .= " [HISTORY.UPD => OK]";
           else :
              $opState .= " [HISTORY.UPD => NOK]";
           endif;
       else:
           insertStmt("job2", array("jb_id", $job_id, "jb2_history_hq", $jbHistoryData));
           $opState .= " [HISTORY.INS]";
       endif;
       if (existsEntry("job2",array("jb_id",$job_id))) :
          $opState = "OK " . $opState;
       else :
          $opState = "NOK";
       endif;
       
       writeToFile($mcDebugExportLogFile, "::[1] " . $opState);

       // [2.] Store view of a mail
       $jobentry = ""; $tourentry = ""; $jobcosts = ""; $courierentry = ""; $employeeentry = "";
       $userTypeName = "hq";

       $f_act = "export";
       $currentJobParameterState = getJobSnapshot($job_id);
       $f_act = "";
       $jbHistoryData = $currentJobParameterState . $tmpDelimiter . $jobentry . $tmpDelimiter . $tourentry
                      . $tmpDelimiter . $jobcosts . $tmpDelimiter . $courierentry . $tmpDelimiter . $employeeentry;
       $jbHistoryData = str_replace('\'', '\\\'', $jbHistoryData);

       $jbHistoryData = escapeMysqlForBinary(compress($jbHistoryData));

       $opState = "::";
       if (existsEntry("job2",array("jb_id",$job_id))) :
           $res = updateStmt("job2", "jb_id", $job_id, array("jb2_history_mail", $jbHistoryData));
           if ($db->affected_rows > 0) :
              $opState .= " [MAIL.UPD => OK]";
           else :
              $opState .= " [MAIL.UPD => NOK]";
           endif;
       else:
           insertStmt("job2", array("jb_id", $job_id, "jb2_history_mail", $jbHistoryData));
           $opState .= " [MAIL.INS]";
       endif;
       if (existsEntry("job2",array("jb_id",$job_id))) :
          $opState = "OK " . $opState;
       else :
          $opState = "NOK";
       endif;

       writeToFile($mcDebugExportLogFile, "::[2] " . $opState);

       // [3.] Store view of the customer
       $jobentry = ""; $tourentry = ""; $jobcosts = ""; $courierentry = ""; $employeeentry = "";
       $userTypeName = "cs";
       $currentJobParameterState = getJobSnapshot($job_id);
       $jbHistoryData = $currentJobParameterState . $tmpDelimiter . $jobentry . $tmpDelimiter . $tourentry
                      . $tmpDelimiter . $jobcosts . $tmpDelimiter . $courierentry . $tmpDelimiter . $employeeentry;
       $jbHistoryData = str_replace('\'', '\\\'', $jbHistoryData);                  

       $jbHistoryData = escapeMysqlForBinary(compress($jbHistoryData));   

       $opState = "::";
       if (existsEntry("job2",array("jb_id",$job_id))) :
           $res = updateStmt("job2", "jb_id", $job_id, array("jb2_history_cs", $jbHistoryData));
           if ($db->affected_rows > 0) :
              $opState .= " [CS.UPD => OK]";
           else :
              $opState .= " [CS.UPD => NOK]";
           endif;
       else:
           insertStmt("job2", array("jb_id", $job_id, "jb2_history_cs", $jbHistoryData));
           $opState .= " [CS.INS]";
       endif;
       if (existsEntry("job2",array("jb_id",$job_id))) :
          $opState = "OK " . $opState;
       else :
          $opState = "NOK <====";
       endif;

       writeToFile($mcDebugExportLogFile, "::[3] OK");
   endfor;
   
   $userTypeName = "hq";  // VERY IMPORTANT TO RESET !!!
   $f_act == $f_act_rem;

   // Call itself
   $path = getAbsoluteSystemPath();
   $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 &";
   writeToFile($mcDebugExportLogFile, $cmd);
   system($cmd);
endif;
