<?php
/*=======================================================================
 *
 * auto_trigger_vehicletype_report
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/


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

$autoMode = false;
if (!isset($argv[1]) || $argv[1] == "") :
   include_once ("../include/auth.inc.php");
   $autoMode = false;
else :
   if ($argv[1] == "acapella7890") :
       $autoMode = true;
   endif;
endif;

include_once ('../include/email/htmlMimeMail.php');

// DEBUG MODE
$debug = true;

// Gets customer list having a finished job during the specified interval
// PRESENTLY NOT IN USE !!!!
function getCustomersWithJobInInterval ($fromDate = "", $toDate = "") {

  if ($fromDate == "") : $fromDate = getDateTime("date_firstday_lastmonth_currentyear"); endif;
  if ($toDate == "") : $toDate = getDateTime("date_lastday_lastmonth_currentyear"); endif;

  $retArr = getColVectorFromDB2ArrayByClause(
              "job AS jb, costcenter AS csc, customer AS cs, company AS cmp", 
              "cs.cs_id", 
              "jb.jb_status = '2' AND  jb.jb_finishtime >= '" . $fromDate . "' AND jb.jb_finishtime <= '" . $toDate . "' AND csc.csc_id = jb.csc_id_payer AND cs.cs_id = csc.cs_id AND cmp.cmp_id = cs.cmp_id AND cmp.cmp_archived = '0' AND cmp.cmp_authenticated = '1'",
              "", "", "DISTINCT"
            );

  return $retArr;
}

// Returns the statement 
function getVhtList ($fromDate, $toDate, $whereClause = "", $groupByClause = "", $orderByClause = "") {
  global $db, $referHqTable;

  $retArray = array();

  if ($fromDate == "") : $fromDate = getDateTime("date_firstday_lastmonth_currentyear"); endif;
  if ($toDate == "") : $toDate = getDateTime("date_lastday_lastmonth_currentyear"); endif;
  
  if ($groupByClause == "") : $groupByClause = "jb.vht_id_real, jb.vht_id"; endif;
  if ($orderByClause == "") : $orderByClause = "jb.vht_id_real, jb.vht_id"; endif;

  $hqFieldClause = "hq.hq_mnemonic, ";
  $hqFromClause = "LEFT JOIN headquarters AS hq ON jb.hq_id = hq.hq_id";
  $hqGroupClause = "jb.hq_id,";
  $hqOrderClause = "jb.hq_id,";
  if (!$referHqTable) : 
     $hqFieldClause = "";
     $hqFromClause = "";
     $hqGroupClause = "";
     $hqOrderClause = "";
  endif;

  // NACH ERLEDIGUNGSZEIT
  $sqlquery = "SELECT " . $hqFieldClause . "mt_exec.mt_sort AS mt_exec_sort, mt_exec.mt_value AS mt_exec_value, mt_req.mt_sort AS mt_req_sort, mt_req.mt_value AS mt_req_value,"
            . "       COUNT(jb.jb_id) AS count_jobs, SUM(jb.jb_totalprice) AS business_volume"
            . " FROM job AS jb " . $hqFromClause
            . "                LEFT JOIN metatype AS mt_req ON jb.vht_id = mt_req.mt_sort AND mt_req.mt_type = 'vehicletype'"
            . "                LEFT JOIN metatype AS mt_exec ON jb.vht_id_real = mt_exec.mt_sort AND mt_exec.mt_type = 'vehicletype',"
            . "      costcenter AS csc, company AS cmp, customer AS cs"
            . " WHERE jb.jb_status = '2' AND jb.jb_finishtime >= '" . $fromDate . " 00:00:00' AND jb.jb_finishtime <= '" . $toDate . " 23:59:59' AND jb.vht_id_real > '1' AND jb.vht_id_real < '999' AND"
            . "       (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1' OR jb.jb_storno = '3') AND"
            . "       csc.csc_id = jb.csc_id_payer AND cs.cs_id = csc.cs_id AND cmp.cmp_id = cs.cmp_id AND cmp.cmp_archived = '0' AND cmp.cmp_authenticated = '1' " . $whereClause
            . " GROUP BY " . $hqGroupClause . $groupByClause
            . " ORDER BY " . $hqOrderClause . $orderByClause;

echo $sqlquery . " \n\n<br><br>";
die();
  $result = $db->query($sqlquery);   
  if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
  // while ($row = $result->fetchRow()):
  while ($row = $result->fetch_assoc()):
        $retArray[] = array($row["mt_exec_sort"], $row["mt_exec_value"], $row["mt_req_sort"], $row["mt_req_value"], $row["count_jobs"], $row["business_volume"]);
  endwhile;
  $result->free();  
  
  return $retArray;
}


$objType = trim ($argv[2]);
$objId = trim ($argv[3]);
$intervalSendReport = trim ($argv[4]);

if ($debug) :
   $autoMode = true;
   $objType = "hq";
   // $objType = "hq_all";
   $objId = "1";
   // $objId = "0";
   $intervalSendReport = "0";
endif;

if ($intervalSendReport == "" || !is_numeric($intervalSendReport) || $intervalSendReport < 0 || $intervalSendReport > 2) :
   $intervalSendReport = 0;  // monthly per default
endif;


if ($objId != "" && (is_numeric($objId) && ($objType == "cs" || $objType == "cs_meta" || $objType == "cs_grp" || $objType == "hq" || $objType == "hq_all"))) :

   $referHqTable = true;
   if ($objType == "hq_all") : 
      $referHqTable = false;
   endif;

   if ($autoMode || $usr_id == "00000") :
     
      // Get user
      $usrName = "";
      $usrFirstname = "";
      if (!$autoMode) :
         $usrName = getFieldValueFromId("user","usr_id",$usr_id,"usr_name");
         $usrFirstname = getFieldValueFromId("user","usr_id",$usr_id,"usr_firstname");
      endif;

      // Get headquarters
      $hqId = "0";
      $hqName = "";
      if ($objType == "hq_all") :
         $hqName = "[ALLE]";
      elseif ($objType == "hq") :
         if (is_numeric($objId) && $objId > "0") :
            $hqId = $objId;
            $hqName = getFieldValueFromId("headquarters","hq_id",$objId,"hq_name");
         endif;
      endif;

      // Init
      $currentDateTime = getDateTime("0");
      if ($intervalSendReport == 0) :
         // Monthly
         $fromDate = getDateTime("date_firstday_lastmonth_currentyear");
         $toDate = getDateTime("date_lastday_lastmonth_currentyear");
      elseif ($intervalSendReport == 1) :
         // Quarterly
         $curMonth = date("n");
         $curYear = date("Y");
         $quartals = array(1 => 1,2 => 1,3 => 1,4 => 2,5 => 2,6 => 2,7 => 3,8 => 3,9 => 3,10 => 4,11 => 4,12 => 4);
         $currentQuartal = $quartals[$curMonth];
         switch ($currentQuartal) {
             case 1:
                 $lastYear = getDateTime("lastyear");
                 $fromDate = $lastYear . "-10-01 00:00:00";
                 $toDate = $lastYear . "-12-31 23:59:59";
                 break;
             case 2:
                 $fromDate = $curYear . "-01-01 00:00:00";
                 $toDate = $curYear . "-03-31 23:59:59";
                 break;
             case 3:
                 $fromDate = $curYear . "-04-01 00:00:00";
                 $toDate = $curYear . "-06-30 23:59:59";
                 break;
             case 4:
                 $fromDate = $curYear . "-07-01 00:00:00";
                 $toDate = $curYear . "-09-30 23:59:59";
                 break;
         }
      elseif ($intervalSendReport == 2) :
         // Yearly
         $fromDate = getDateTime("date_firstday_firstmonth_lastyear");
         $toDate = getDateTime("date_lastday_lastmonth_lastyear");
      else :
         // Default monthly
         $fromDate = getDateTime("date_firstday_lastmonth_currentyear");
         $toDate = getDateTime("date_lastday_lastmonth_currentyear");
      endif;

      // Get customes WITH jobs during the specified interval
      // $csWithJobArr = getCustomersWithJobInInterval($fromDate);
// echo "\n\n"; print_r($csWithJobArr); echo "\n\n"; die();

      $sendPerMail = false;
      $path = "../temp/download/";
      $f_secretFileName = "VHT_REPORT_" . getDateTime("6") . "_" . $objId . ".csv";

if ($debug) :
   $fromDate = getDateTime("date_firstday_lastmonth_lastyear");
   $toDate = getDateTime("date_lastday_lastmonth_lastyear");
endif;

      // List of all vehicles with special fields
      if (true) :

         $typeArr = defineOutputFormats();
         // Special extensions
         // $typeArr["jb_totalprice"] = "float_rounded_2";
         // $typeArr["jb_km"] = "float_rounded_2";
         // $typeArr["jb_co2"] = "float_rounded_2";

// sendInternalMail("Mindestens einer der Parameter JB_CR_PRICE_THRESHOLD bzw. JB_CR_PRICE_BLOCK existiert nicht!"); die();

         $triggerArray = array();
         $csvArray = array();
         $matrixArr = array();
         $whereClause = "";
// $retArray[] = array($vht_id_field, $row["hq_mnemonic"], $row["mt_req_sort"], $row["mt_req_value"], $row["mt_exec_sort"], $row["mt_exec_value"], $row["count_jobs"], 0, $row["business_volume"]);
         // Insert header
         $headerArray = array("NL", "Angeforderter Fahrzeugtyp",  "Ausführender Fahrzeugtyp", "Anzahl Aufträge", "Nettoumsatz");
         $fieldArray =  array("hq_mnemonic", "mt_req_value", "mt_exec_value", "count_jobs", "business_volume");
         $triggerArray[] = $headerArray;
         $csvArray[] = str_replace("&nbsp;"," ",str_replace("</br>","",implode(";", $headerArray)));

         // HEADQUARTERS
         if ($objType == "hq" && $hqId > "0") :
            $whereClause .= " AND jb.hq_id = '" . $hqId . "'";
         endif;

         // Get values of last month
         $vhtIdArr = getVhtList($fromDate, $toDate, $whereClause);
print_r($vhtIdArr); echo "<br><br>";

         // Sort array by headquarters
         


         // Iterate customer list, check total prices regarding 10T € and percent value:
/*
         $matrixKeysArr = array_keys($matrixArr);
         $matrixKeysArrLen = count($matrixKeysArr);
         for ($j = 0; $j < $matrixKeysArrLen; $j++) :
             $key = $matrixKeysArr[$j];             
             // Cases:
             // 1. & 2.: When looking at the last and penultimate month, one of the two is 0 and one is >0
             // 3.: <  10 TEU total price last Monat and  alle Kunden mit Veränderungen +/- 50%
             // 4.: >= 10 TEU Umsatz/aktueller Monat, alle Kunden mit Veränderungen +/- 25%
             if ($matrixArr[$key][6] == 0 && $matrixArr[$key][7] > 0 ||
                 $matrixArr[$key][6] > 0 && $matrixArr[$key][7] == 0 ||
                 $matrixArr[$key][6] < 10000 && ($matrixArr[$key][9] < 0.5 || $matrixArr[$key][9] > 1.5) ||
                 $matrixArr[$key][6] >= 10000 && ($matrixArr[$key][9] < 0.25 || $matrixArr[$key][9] > 1.25)) :

             	  $triggerArray[] = $matrixArr[$key];
             endif;
         endfor;
*/
// print_r($triggerArray); die();

         $triggerArrayLen = count($triggerArray);
         $triggerOut = "";
         // 66CCFF, FF0000, FF0044, FF6633, FFCC33, FFFF33
         if ($triggerArrayLen > 1) :

            $sendPerMail = true;  // At least one event to be mailed

            // HTML output
            $triggerOut .= "<html>\n";
            $triggerOut .= "<body>\n";
            $triggerOut .= "<br><br>";
            $triggerOut .= "<table>\n";
            // Headline
            $triggerOut .= "<tr>\n";

            $tmpArray = $triggerArray[0];
            $tmpArrayLen = count($tmpArray);
            // $rowColor = $tmpArray[0];
            $rowColor = "66CCFF";  // Here a static value
            for ($j = 0; $j < $tmpArrayLen; $j++) :
                $triggerOut .= "<td style=\"background-color: #" . $rowColor . ";\">&nbsp;" . $tmpArray[$j] . "&nbsp;&nbsp;&nbsp;</td>\n";
            endfor;
            $triggerOut .= "</tr>\n";
            // Body
            for ($i = 1; $i < $triggerArrayLen; $i++) :
                $tmpArray = $triggerArray[$i];
                $tmpArrayLen = count($tmpArray);
                $tmpArrayLen--; // Do not show last field(s) [factor, ....]

                // Color
                // $rowColor = $tmpArray[0];
                $rowColor = "66CCFF";  // Here a static value
                /*
                if ($percentValue <= (100 - ($crPriceThresholdValue + $crPriceMarginValue))) :
                   $rowColor = "FFCC33";
                endif;
                if ($percentValue <= (100 - $crPriceBlockValue)) :
                   $rowColor = "FF6633";
                endif;
                */

                $triggerOut .= "<tr>\n";
                $csvLineArray = array();
                for ($j = 0; $j < $tmpArrayLen; $j++) :

                    if ($fieldArray[$j] == "count_jobs" || $fieldArray[$j] == "count_jobs2") : 
                       $formattedOutput = formatOutput($tmpArray[$j], "number", "1", "0");
                       $textAlign = "right";
                    elseif ($fieldArray[$j] == "business_volume" || $fieldArray[$j] == "business_volume2") : 
                       $formattedOutput = formatOutput($tmpArray[$j], "number", "1", "2");
                       if ($formattedOutput == "0") : 
                          $formattedOutput = "0.00";
                       endif;
                       $textAlign = "right";
                    elseif ($fieldArray[$j] == "percentValue") :                       
                       $formattedOutput = formatOutput($tmpArray[$j], "number", "1", "2");
                       if ($tmpArray[$j] == 0 && $tmpArray[5] == 0) :
                          $formattedOutput = "";
                       endif;
                       $textAlign = "right";
                    else :
                       $formattedOutput = formatOutput($tmpArray[$j]);
                       $textAlign = "left";
                    endif;

                    $triggerOut .= "<td style=\"text-align: " . $textAlign . "; background-color: #" . $rowColor . ";\">&nbsp;" . $formattedOutput . ($rowColor == "FF0000" && $j == "6" ? "&nbsp;[überschritten]" : "") . "&nbsp;&nbsp;&nbsp;</td>\n";                    
                    $csvLineArray[] = $formattedOutput;
                endfor;
                $triggerOut .= "</tr>\n";
                $csvArray[] = str_replace("&nbsp;","",implode(";", $csvLineArray));
            endfor;
            $triggerOut .= "</table>\n";

            $triggerOut .= "</body>\n";
            $triggerOut .= "</html>\n";
            
            // CSV attachment
            $csvArrayLen = count($csvArray);
            for ($i = 0; $i < $csvArrayLen; $i++) :
                writeToFile($path . $f_secretFileName, $csvArray[$i]);
            endfor;
         endif;


         // Send via email
         if ($sendPerMail) :  

            // Log object IDs
            $logCsId = 0;
            $logCrId = 0;
            $logHqId = 0;

            $mailSenderAddress = "support@assecutor.de";

/*            
            // Init receiver of the mail
            $mailReceiverAddressArray = array("support@assecutor.de");
            if ($objType == "cs" || $objType == "cs_meta") :
               // Get receiver email address
               $csCmpId = getFieldValueFromId("customer","cs_id",$objId,"cmp_id");
               $cmpSustainabilityEmail = getFieldValueFromId("company","cmp_id",$csCmpId,"cmp_sustainability_email");         
               if ($cmpSustainabilityEmail != "") : 
                  $mailReceiverAddressArray = array($cmpSustainabilityEmail);
               endif;
               $logCsId = $objId;
               $logHqId = getFieldValueFromId("customer","cs_id",$objId,"hq_id");
            elseif ($objType == "hq_all" || $objType == "hq") :
               if ($hqId != "" && is_numeric($hqId)) :
                  $mailReceiverAddress = getParameterValue("0", "MAIL_CRON_202_TO_ADDRESS", $hqId);
                  // Check for split regarding vehicle type
                  if ($courierOrTruckOnly == "K" || $courierOrTruckOnly == "L") :
                     if ($courierOrTruckOnly == "K") :
                        $mailReceiverAddress = getParameterValue("0", "MAIL_CRON_202_A_TO_ADDRESS", $hqId);
                     else :
                        $mailReceiverAddress = getParameterValue("0", "MAIL_CRON_202_B_TO_ADDRESS", $hqId);
                     endif;
                  endif;
               endif;
               if ($mailReceiverAddress == "") :
                  $mailReceiverAddress = getParameterValue("0", "MAIL_CRON_202_TO_ADDRESS", "0");
               endif;
               if ($mailReceiverAddress != "") :
                  $mailReceiverAddressArray = spliti(",",$mailReceiverAddress);
               endif;
            endif;
*/
            // Receiver of the mail
            $mailReceiverAddressArray = array("support@assecutor.de");
            if ($hqId != "" && is_numeric($hqId)) :
               $mailReceiverAddress = getParameterValue("0", "MAIL_CRON_108_TO_ADDRESS", $hqId);
            endif;
            if ($mailReceiverAddress == "") :
               $mailReceiverAddress = getParameterValue("0", "MAIL_CRON_108_TO_ADDRESS", "0");
            endif;
            if ($mailReceiverAddress != "") :
               $mailReceiverAddressArray = explode(",",$mailReceiverAddress);
            endif;

            $reportName = "REPORT FAHRZEUGTYP";

            $mailSubject = $reportName . " " . ($hqName != "" ? "[" . $hqName . "]" : "");

            $mailCcAddress = "";
            $mailBccAddress = "";

            $mailtext = $reportName;
            $mailtext .= "<br><br>";
            
            $intervalTextA = "Abfragezeitraum: ";
            $intervalTextB = "Vergleichszeitraum: ";

            $mailtext .= "<table>";
            $mailtext .= "<tr><td>" . $intervalTextA . "</td><td>" . $intervalA . "</td></tr>";
            $mailtext .= "<tr><td>" . $intervalTextB . "</td><td>" . $intervalB . "</td></tr>";
            $mailtext .= "</table>";
            $mailtext .= "<br><br>";

            if (!$autoMode) :
               $mailtext .= "Ausgeführt von: " . $usrFirstname . " " . $usrName;
            endif;
            $mailtext .= $triggerOut;

            $mailObj = new htmlMimeMail();

            // Set From address
            $mailObj->setFrom($mailSenderAddress);

            // Set Cc address
            if ($mailCcAddress != "") :
               $mailObj->setCc($mailCcAddress);
            endif;

            // Set Bcc address
$mailBccAddress = "admin@assecutor.de";
            if ($mailBccAddress != "") :
               $mailObj->setBcc($mailBccAddress);
            endif;

            // Subject of the mail
            $mailObj->setSubject($mailSubject);

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

            // Attachment
            if ($f_secretFileName != "") :
               if (file_exists($path . $f_secretFileName)) :
                  $attachment = $mailObj->getFile($path . $f_secretFileName);
                  // $mailObj->addAttachment($attachment, $f_secretFileName, $f_mimetype . $f_charset);
                  $mailObj->addAttachment($attachment, $f_secretFileName, 'text/csv');
               endif;
            endif;
// echo "mailReceiverAddress = " . $mailReceiverAddress . "\n\n";
// $mailReceiverAddressArray = array("mv@assecutor.de", "ca@assecutor.de");
// $mailReceiverAddressArray = array("mv@assecutor.de", "ca@assecutor.de", "ingo.kublenz@stadtbote.de");
// $mailReceiverAddressArray = array("admin@assecutor.de", "ingo.kublenz@stadtbote.de");
// $mailReceiverAddressArray = array("mv@assecutor.de");
            $mailResult = $mailObj->send($mailReceiverAddressArray, 'smtp');

            if ($mailResult) :
               $sendState = "OK";
            else :
               $sendState = "NOK";
            endif;
            // Write logdata into log database
            writeToLogDB("190",$logHqId,"","",$logCrId,"",$logCsId,"OBJ_TYPE=" . $objType . "|VERSANDSTATUS=" . $sendState . "|EMAIL=" . implode(",", $mailReceiverAddressArray) . "|DATE_FROM=" . $fromDate . "|DATE_TO=" . $toDate . "|INTERVAL=" . $intervalSendReport);

            $mailObj = NULL;
            if (file_exists($path . $f_secretFileName)) :
               unlink($path . $f_secretFileName);
            endif;

            $out = "Der Sendevorgang wurde abgeschlossen! Bitte prüfen Sie Ihren Email-Eingangsordner!";
         endif;
      endif;
   else :   
      $out = "Leider haben Sie zur Ausführung keine Berechtigung!";
   endif;
else :   
   $out = "Die geforderte Auswahlkombination gibt es leider nicht!";
endif;
?>

<?php if (!$autoMode) : ?>

<html>

<head>

</head>
	
	
<body>

<center>
	
<br><br><br>

<b><?php echo $triggerOut ?></b>

</center>

</body>	
	
</html>

<?php endif; ?>