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

include_once ("../include/mcglobal.inc.php");
include_once ("../include/html.inc.php");
// include_once ("../include/inc_html2pdf.inc.php");
include_once ("../include/inc_file.inc.php");
// include_once ("../include/image.inc.php");
include_once ("../include/inc_job.inc.php");
// include_once ("../include/ftp.inc.php");
include_once ('../include/email/htmlMimeMail.php');


$autoMode = false;
if (!isset($argv[1]) || $argv[1] == "") :
   $isCron = false;
//   include_once ("../include/auth.inc.php");
   getSecHttpVars("1",array("f_act", "csId"));
   $autoMode = true;
//   $usrAccessArray["hq"] = "1"; $usrAccessArray["cs"] = "1";
//   authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
//   authCheckEmployeeRights($emp_id, "1", "1");
else :
   // Init parameters
   $f_act = ""; $title = ""; 

   $isCron = true;
   if ($argv[1] == "acapella7890") : $autoMode = true; endif;
   if ($autoMode) :
      if (isset($argv[2]) && $argv[2] != "") : $csId = $argv[2]; endif;
   endif;
endif;

// Error reporting
error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);

// Set timezone
// date_default_timezone_set('Europe/Berlin');

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


$absoluteSystemPath = getAbsoluteSystemPath();  // Definition of absolute path, filename and extension. Has to be called here BEFORE calling function "outputMetaFieldSpecial()" !!!!
$localPath = $absoluteSystemPath . "/temp/download/";


// Log file
$logFile = getParameterValue("0", "AUTO_EXPORT_LOGFILE_LYRECO_NAP", "0");
if ($logFile == "") :
   $logFile = getParameterValue("0", "AUTO_EXPORT_LOGFILE_NAP", "0");
   if ($logFile == "") : $logFile = "../log/auto_export_lyreco_nap.log"; endif;
endif;

// Send mode
$sendMode = "MAIL";

// Pick up data from the first station of each job
$pickUpArray = array();

// Scan event description mapping
$scanMsgArray = array();
$scanMsgArray["0"] = "OK";
$scanMsgArray["1"] = "NA,nicht angetroffen";
$scanMsgArray["2"] = "NA,Betriebsferien,Streik";
$scanMsgArray["3"] = "AV,Ware gefällt nicht";
$scanMsgArray["4"] = "Kd Verursacher,sonst.Gründe";
$scanMsgArray["5"] = "Adressklärung,Anl.nicht möglich";
$scanMsgArray["6"] = "AV,Bestelldaten sind falsch";
$scanMsgArray["7"] = "AV,Auftrag doppelt erfasst";
$scanMsgArray["8"] = "Sonstige Gründe";
$scanMsgArray["9"] = "FP,Fehlpaket";
$scanMsgArray["10"] = "AV,Richtiger Artikel auf LS";
$scanMsgArray["11"] = "Paket im Lager beschädigt";
$scanMsgArray["12"] = "Verspätete Abf.Nachtsprung LKW";
$scanMsgArray["13"] = "Pakete im falschen RDC gelandet";
$scanMsgArray["14"] = "Nachtspr.LKW verspätet im RDC";
$scanMsgArray["15"] = "Besch.Pak.durch Nachtsprung";
$scanMsgArray["16"] = "Pakete im RDC vertauscht";
$scanMsgArray["17"] = "Aus Zeitgründen nicht ausgel.";
$scanMsgArray["18"] = "Besch.Pak.durch Fahrer/RDC";
$scanMsgArray["19"] = "Sonstiges,Fehler Versandteam";
$scanMsgArray["20"] = "Autobahnvollsp.,höh.Gewalt";
$scanMsgArray["21"] = "Sonstiges";


// Get jobs for auto_export
function getDoneJobsOfCustomer($csId) {
  global $db, $logFile, $pickUpArray;
  $retArray = array();

  $constAmStarttimeInDays = 1;  // Yesterday

  $startTime = getDateTime("datetime_plus_offset", array(0,0,0,0,-($constAmStarttimeInDays),0), "Y-m-d") . " 00:00:00";
  $endTime =   getDateTime("datetime_plus_offset", array(0,0,0,0,-($constAmStarttimeInDays),0), "Y-m-d") . " 23:59:59";
  // $currentTime = getDateTime("0");
// echo $startTime . " bis " . $endTime . "\n"; die();

  // Get jobs of the specified customer
  $sqlquery = "SELECT jb.jb_id, jb.jb_status, jb.cr_id, jb.cr_sid, jb.hq_id, jb.jb_ordertime, jb.jb_finishtime, jb.jb_tourname,"
            . "       tr.tr_id, tr.tr_sort, tr.tr_status, tr.tr_commission_no, tr.tr_finishtime, tr.tr_comp, tr.tr_comp2, tr.tr_person, tr.tr_phone, tr.tr_hsno, tr.tr_signname, tr.tr_sign, tr.tr_cs_freetext,"
            . "       ad.ad_street, ad.ad_zipcode, ad.ad_city," 
            . "       trat.trat_packingpieces, trat.trat_remark, trat.trat_weight,"
            . "       gdc.gdc_content, gdc.gdc_context, gdc_tr_finished.gdc_content AS gdc_tr_finished_content,"
            . "       gdc_info_0.gdc_content AS gdc_info_0_content, gdc_info_1.gdc_content AS gdc_info_1_content, gdc_info_2.gdc_content AS gdc_info_2_content,"
            . "       gdc_info_3.gdc_content AS gdc_info_3_content, gdc_info_4.gdc_content AS gdc_info_4_content"
            . " FROM job AS jb,"
            . "      tour AS tr LEFT JOIN address AS ad ON tr.ad_id = ad.ad_id" 
            . "                 LEFT JOIN tourarticle AS trat ON trat.tr_id = tr.tr_id"
            . "                 LEFT JOIN genericdatacontainer AS gdc ON gdc.gdc_obj_id = tr.tr_id AND gdc.gdc_obj_type = 'tr' AND gdc.gdc_gen_fieldname = 'auto_export'"
            . "                 LEFT JOIN genericdatacontainer AS gdc_info_0 ON gdc_info_0.gdc_obj_id = tr.tr_id AND gdc_info_0.gdc_obj_type = 'tr' AND gdc_info_0.gdc_gen_fieldname = 'info_0'"
            . "                 LEFT JOIN genericdatacontainer AS gdc_info_1 ON gdc_info_1.gdc_obj_id = tr.tr_id AND gdc_info_1.gdc_obj_type = 'tr' AND gdc_info_1.gdc_gen_fieldname = 'info_1'"
            . "                 LEFT JOIN genericdatacontainer AS gdc_info_2 ON gdc_info_2.gdc_obj_id = tr.tr_id AND gdc_info_2.gdc_obj_type = 'tr' AND gdc_info_2.gdc_gen_fieldname = 'info_2'"
            . "                 LEFT JOIN genericdatacontainer AS gdc_info_3 ON gdc_info_3.gdc_obj_id = tr.tr_id AND gdc_info_3.gdc_obj_type = 'tr' AND gdc_info_3.gdc_gen_fieldname = 'info_3'"
            . "                 LEFT JOIN genericdatacontainer AS gdc_info_4 ON gdc_info_4.gdc_obj_id = tr.tr_id AND gdc_info_4.gdc_obj_type = 'tr' AND gdc_info_4.gdc_gen_fieldname = 'info_4',"
            . "      costcenter AS csc, customer AS cs, employee AS emp, user AS usr, genericdatacontainer AS gdc_tr_finished"
            . " WHERE (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1') AND"
            . "       jb.jb_status IN ('1', '2')                     AND"
            . "       jb.jb_offer = '0'                              AND"
            . "       jb.csc_id_payer = csc.csc_id                   AND"
            . "       csc.cs_id = cs.cs_id                           AND"
            . "       cs.cs_id = '" . $csId . "'                     AND"
            . "       cs.cs_admin = emp.emp_id                       AND"
            . "       emp.usr_id = usr.usr_id                        AND"
            . "       jb.jb_id = tr.jb_id                            AND"
            . "       tr.tr_finishtime >= '" . $startTime . "'       AND"
            . "       tr.tr_finishtime <= '" . $endTime . "'         AND"
            . "       tr.tr_status = '1'                             AND"
            . "       gdc_tr_finished.gdc_obj_id = tr.tr_id          AND"
            . "       gdc_tr_finished.gdc_obj_type = 'tr'            AND"
            . "       gdc_tr_finished.gdc_gen_fieldname = 'del_code' AND"
            . "       gdc_tr_finished.gdc_content != '0'"
            . " ORDER BY tr.jb_id, tr.tr_sort";
// echo $sqlquery . "\n"; die();


  $result = $db->query($sqlquery);
  if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
  while ($row = $result->fetch_assoc()):
        if ($row["tr_sort"] >= "2" && $row["gdc_context"] != "JOB_EXPORTED") :
           $retArray[$row["tr_id"]]["jb_id"]                   = $row["jb_id"];
           $retArray[$row["tr_id"]]["jb_status"]               = $row["jb_status"];
           $retArray[$row["tr_id"]]["jb_ordertime"]            = $row["jb_ordertime"];
           $retArray[$row["tr_id"]]["jb_finishtime"]           = $row["jb_finishtime"];
           $retArray[$row["tr_id"]]["jb_tourname"]             = $row["jb_tourname"];
           $retArray[$row["tr_id"]]["cr_id"]                   = $row["cr_id"];
           $retArray[$row["tr_id"]]["cr_sid"]                  = $row["cr_sid"];
           $retArray[$row["tr_id"]]["hq_id"]                   = $row["hq_id"];
           $retArray[$row["tr_id"]]["gdc_content"]             = $row["gdc_content"];
           $retArray[$row["tr_id"]]["gdc_context"]             = $row["gdc_context"];
           $retArray[$row["tr_id"]]["gdc_tr_finished_content"] = $row["gdc_tr_finished_content"];
           $retArray[$row["tr_id"]]["gdc_info_0_content"]      = $row["gdc_info_0_content"];
           $retArray[$row["tr_id"]]["gdc_info_1_content"]      = $row["gdc_info_1_content"];
           $retArray[$row["tr_id"]]["gdc_info_2_content"]      = $row["gdc_info_2_content"];
           $retArray[$row["tr_id"]]["gdc_info_3_content"]      = $row["gdc_info_3_content"];
           $retArray[$row["tr_id"]]["gdc_info_4_content"]      = $row["gdc_info_4_content"];
           $retArray[$row["tr_id"]]["tr_id"]                   = $row["tr_id"];
           $retArray[$row["tr_id"]]["tr_sort"]                 = $row["tr_sort"];
           $retArray[$row["tr_id"]]["tr_status"]               = $row["tr_status"];
           $retArray[$row["tr_id"]]["tr_finishtime"]           = $row["tr_finishtime"];
           $retArray[$row["tr_id"]]["tr_commission_no"]        = $row["tr_commission_no"];
           $retArray[$row["tr_id"]]["tr_comp"]                 = $row["tr_comp"];
           $retArray[$row["tr_id"]]["tr_comp2"]                = $row["tr_comp2"];
           $retArray[$row["tr_id"]]["tr_person"]               = $row["tr_person"];
           $retArray[$row["tr_id"]]["tr_phone"]                = $row["tr_phone"];
           $retArray[$row["tr_id"]]["tr_hsno"]                 = $row["tr_hsno"];
           $retArray[$row["tr_id"]]["tr_signname"]             = $row["tr_signname"];
           $retArray[$row["tr_id"]]["tr_sign"]                 = $row["tr_sign"];
           $retArray[$row["tr_id"]]["tr_cs_freetext"]          = $row["tr_cs_freetext"];
           $retArray[$row["tr_id"]]["ad_street"]               = $row["ad_street"];
           $retArray[$row["tr_id"]]["ad_zipcode"]              = $row["ad_zipcode"];
           $retArray[$row["tr_id"]]["ad_city"]                 = $row["ad_city"];
           $retArray[$row["tr_id"]]["trat_packingpieces"]      = $row["trat_packingpieces"];
           $retArray[$row["tr_id"]]["trat_remark"]             = $row["trat_remark"];
           $retArray[$row["tr_id"]]["trat_weight"]             = $row["trat_weight"];
        endif;

        // Define pick up data (address, etc.)
        if ($row["tr_sort"] == "1") :
           $pickUpArray[$row["jb_id"]]["jb_id"]              = $row["jb_id"];
           $pickUpArray[$row["jb_id"]]["jb_status"]          = $row["jb_status"];
           $pickUpArray[$row["jb_id"]]["jb_ordertime"]       = $row["jb_ordertime"];
           $pickUpArray[$row["jb_id"]]["jb_finishtime"]      = $row["jb_finishtime"];
           $pickUpArray[$row["jb_id"]]["jb_tourname"]        = $row["jb_tourname"];
           $pickUpArray[$row["jb_id"]]["cr_id"]              = $row["cr_id"];
           $pickUpArray[$row["jb_id"]]["cr_sid"]             = $row["cr_sid"];
           $pickUpArray[$row["jb_id"]]["hq_id"]              = $row["hq_id"];
           $pickUpArray[$row["jb_id"]]["gdc_content"]        = $row["gdc_content"];
           $pickUpArray[$row["jb_id"]]["gdc_context"]        = $row["gdc_context"];
           $pickUpArray[$row["jb_id"]]["gdc_info_0_content"] = $row["gdc_info_0_content"];
           $pickUpArray[$row["jb_id"]]["gdc_info_1_content"] = $row["gdc_info_1_content"];
           $pickUpArray[$row["jb_id"]]["gdc_info_2_content"] = $row["gdc_info_2_content"];
           $pickUpArray[$row["jb_id"]]["gdc_info_3_content"] = $row["gdc_info_3_content"];
           $pickUpArray[$row["jb_id"]]["gdc_info_4_content"] = $row["gdc_info_4_content"];
           $pickUpArray[$row["jb_id"]]["tr_sort"]            = $row["tr_sort"];
           $pickUpArray[$row["jb_id"]]["tr_status"]          = $row["tr_status"];
           $pickUpArray[$row["jb_id"]]["tr_finishtime"]      = $row["tr_finishtime"];
           $pickUpArray[$row["jb_id"]]["tr_commission_no"]   = $row["tr_commission_no"];
           $pickUpArray[$row["jb_id"]]["tr_comp"]            = $row["tr_comp"];
           $pickUpArray[$row["jb_id"]]["tr_comp2"]           = $row["tr_comp2"];
           $pickUpArray[$row["jb_id"]]["tr_person"]          = $row["tr_person"];
           $pickUpArray[$row["jb_id"]]["tr_phone"]           = $row["tr_phone"];
           $pickUpArray[$row["jb_id"]]["tr_hsno"]            = $row["tr_hsno"];
           $pickUpArray[$row["jb_id"]]["tr_signname"]        = $row["tr_signname"];
           $pickUpArray[$row["jb_id"]]["tr_sign"]            = $row["tr_sign"];
           $pickUpArray[$row["jb_id"]]["tr_cs_freetext"]     = $row["tr_cs_freetext"];
           $pickUpArray[$row["jb_id"]]["ad_street"]          = $row["ad_street"];
           $pickUpArray[$row["jb_id"]]["ad_zipcode"]         = $row["ad_zipcode"];
           $pickUpArray[$row["jb_id"]]["ad_city"]            = $row["ad_city"];
        endif;
  endwhile;
  $result->free();
  return $retArray;
} 



// **** MAIN ****

// Get script name of the requested customer
if ($csId != "" && is_numeric($csId) && $csId > "0") :
   
   // Set execution time for keepalive
   $currentTime = getDateTime("0");

   // Get invoice address of the current customer
   // $csInvAddress = getAddress($csId, "costcenteraddress", "2");

   $currentHqId = getFieldValueFromId("customer","cs_id",$csId,"hq_id");
   $hqMnemonic = getFieldValueFromId("headquarters","hq_id",$currentHqId,"hq_mnemonic");
   $hqName = getFieldValueFromId("headquarters","hq_id",$currentHqId,"hq_name");

   // **************************
   // *** Send automatically ***
   // **************************

   // Check global state of export being active
   // $constAutoExportEnabled = getParameterValue("0", "AUTO_EXPORT_ENABLED_LYRECO", "0");
   // if ($constAutoExportEnabled == "") :
      $constAutoExportEnabled = "1";
   // endif;
 

   // Start export      
   if ($constAutoExportEnabled == '1') :

      $dayExport = getDateTime("1");  // "Ymd"

      $jbArr = getDoneJobsOfCustomer($csId);
      $jbkArr = array_keys($jbArr);
      $jbkArrLen = count($jbkArr);

      $filename = $localPath . $currentTime . ".lyreco_nap.csv";
// echo $filename . "\n"; die();
      $matrix = array();

      // Remove local files
      $filesToBeRemoved = glob($localPath . "*.lyreco_nap.csv");
      foreach($filesToBeRemoved as $fileRemoved) {
        if (is_file($fileRemoved)) :
           unlink($fileRemoved);
        endif;
      }

      if ($jbkArrLen > 0) :

         // [1.] Iterate jobs for generating export file
         for ($i = 0; $i < $jbkArrLen; $i++) :

             $aKey = $jbkArr[$i];  // $aKey =!= $trId !!!!
             $trId = $jbArr[$aKey]["tr_id"];
             $jbId = $jbArr[$aKey]["jb_id"];
             $trSort = $jbArr[$aKey]["tr_sort"];

             // The remote order no has to have no "0" at the beginning
             if ($jbArr[$aKey]["gdc_info_0_content"] != "") :
                while (substr($jbArr[$aKey]["gdc_info_0_content"],0,1) == "0"):
                      $jbArr[$aKey]["gdc_info_0_content"] = substr($jbArr[$aKey]["gdc_info_0_content"],1);
                endwhile;
             endif;

             $matrix[$i][0] = "ESSEN-SUB";
             $matrix[$i][1] = $pickUpArray[$jbId]["jb_tourname"];
             $matrix[$i][2] = "HANSETRANS HANSEATISCHE";
             $matrix[$i][3] = $jbArr[$aKey]["gdc_info_2_content"];
             $matrix[$i][4] = substr($jbArr[$aKey]["jb_ordertime"],8,2) . "." . substr($jbArr[$aKey]["jb_ordertime"],5,2) . "." . substr($jbArr[$aKey]["jb_ordertime"],0,4);
             $matrix[$i][5] = $jbArr[$aKey]["tr_comp"];
             $matrix[$i][6] = $jbArr[$aKey]["gdc_tr_finished_content"];
             $matrix[$i][7] = "";  // FEHLPAKETE
             $matrix[$i][8] = $scanMsgArray[$jbArr[$aKey]["gdc_tr_finished_content"]];

         endfor;  // Loop all jobs


         // [2.] Generate csv 
         $lineArray = convertMatrixToCsv ($matrix, "RDC;Tour;Unternehmer;LS-Nr.;Versand-Datum;Kunde;Grund;Fehlpakete;Beschreibung");
         $lineArrayLen = count($lineArray);
         for ($i = 0; $i < $lineArrayLen; $i++) :
              writeToFile($filename, $lineArray[$i]);
         endfor;


         // [3.] Send mail
         if ($sendMode == "MAIL") :

            $mailObj = new htmlMimeMail();
            $mailCssFontType = "Verdana, Arial, Helvetica, sans-serif";

            $mailtext  = "<html><head><meta text/html>";
            $mailtext .= "</head><body><h4>";
            $mailtext .= $output;
            $mailtext .= "</h4></body></html>";

            $mailSubject = "LYRECO NAP-AUFSTELLUNG " . $hqName . " für den " . getDateTime("date_yesterday_currentmonth_currentyear");
            $mailObj->setSubject($mailSubject);

            $mailObj->setHtml($mailtext, null, "./");

            if ($currHqId != "") :
               $mailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currHqId);
            endif;
            if ($mailSenderAddress == "" || !checkEmailFormat($mailSenderAddress)) :
               $mailSenderAddress = "hh.transport@hansetrans.de";
            endif;            
            $mailObj->setFrom($mailSenderAddress);

            $mailCcAddress = getParameterValue("0", "MAIL_CC_ADDRESS", "0");
            if ($mailCcAddress != "" && checkEmailFormat($mailCcAddress)) :
               $mailObj->setCc($mailCcAddress);
            endif;

            $mailBccAddress = getParameterValue("0", "MAIL_BCC_ADDRESS", "0");
            if ($mailBccAddress != "" && checkEmailFormat($mailBccAddress)) :
               $mailObj->setBcc($mailBccAddress);
            endif;            

            if (file_exists($filename)) :
               $attachment = $mailObj->getFile($filename);
               $mailObj->addAttachment($attachment, $filename, 'text/csv');
            endif;

            $mailResult = $mailObj->send(array("mail-cron@assecutor.de","rainer.westphal@hansetrans.de"), 'smtp');
// $mailResult = $mailObj->send(array("mv@assecutor.de"), 'smtp');

            if ($mailResult) :
               // $mailsendStatus = getLngt("Die Nachricht wurde versandt!");
               // Write logdata into log database
               // writeToLogDB("22",$currentHqId,$job_id,$currentSessionUsrId,"","","",$f_email . "|STATION");
            else :
               // $mailsendStatus = getLngt("Die Nachricht konnte nicht gesendet werden!");
               // Write logdata into log database
               // writeToLogDB("23",$currentHqId,$job_id,$currentSessionUsrId,"","","",$f_email . "|STATION");
            endif;

            $mailObj = NULL;
            if (file_exists($filename)) :
               unlink($filename);
            endif;

         endif;
      else :
         echo "NO JOB FOUND!\n";
      endif;

   else :
      writeToFile($logFile, $currentTime . " - ERR: EXPORT DISABLED BY DATABASE PARAMETER!" . " " . $csId);
      writeToFile($logFile, "-------------------------------------------------------------------------------------------------------------------");
      if ($debug) : echo "EXPORT DISABLED BY DATABASE PARAMETER! \n\r"; endif;
   endif;  // AUTO_EXPORT_ENABLED
else :
     writeToFile($logFile, $currentTime . " - ERR: UNKNOWN CUSTOMER!" . " " . $csId);
     writeToFile($logFile, "-------------------------------------------------------------------------------------------------------------------");
endif;
?>
