<?php
/*=======================================================================
 *
 * auto_trigger_jobs_sustainability_customer_report.php
 *
 * 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');
// include_once ('../include/inc_vehicle.inc.php');


// Returns the statement for a vehicle list
function getStmtJbSustainabilityList ($whereClause = "", $orderByClause = "", $fieldClause = "", $fromClause = "", $forceIndexClause = "") {

  $retStmt = "";
  if ($fieldClause != "") : $fieldClause = ", " . $fieldClause; endif;
  if ($fromClause != "") : $fromClause = ", " . $fromClause; endif;
  if ($forceIndexClause != "") : $fromClause .= " " . $forceIndexClause; endif;
  if ($whereClause != "") : $whereClause = " AND " . $whereClause; endif;
  if ($orderByClause != "") : $orderByClause = " ORDER BY " . $orderByClause; endif;

  /*
    EXTRA-FIELDS
             . "     crvh.crvh_partner_commission, ROUND(jb.jb_cr_price * (1 + (crvh.crvh_partner_commission / 100)), 2) AS payout,"
             . "     ROUND(jb.jb_totalprice - (jb.jb_cr_price * (1 + (crvh.crvh_partner_commission / 100))), 2) AS eau,"
             . "     ROUND(((jb.jb_totalprice - (jb.jb_cr_price * (1 + (crvh.crvh_partner_commission / 100)))) / jb.jb_totalprice) * 100, 2) AS bsg"
  */
  $retStmt = "SELECT jb.jb_id, jb.jb_weight, cs.cs_eid, cmp.cmp_comp, jb.jb_ordertime, jb.jb_finishtime, jb.cr_id, jb.vht_id, mt.mt_value, jb.vht_id_real, mt_real.mt_value AS mt_value_real, cr.cr_eid, jb.cr_sid, jb_tourdata,"
             . "     jb.jb_totalprice, jb.jb_cr_price, ROUND(100 - ((jb.jb_cr_price / jb.jb_totalprice) * 100), 2) AS jb_percent,"
             . "     jb.jb_totalprice, jbprc_km.jbprc_price AS jb_km, jbprc_co2.jbprc_price AS jb_co2,"
             . "     REPLACE(SUBSTRING_INDEX(SUBSTRING(jb.jb_tourdata, 1, (INSTR(jb.jb_tourdata, '|') - 1)), ';', -1), ';', ',') AS jb_lastzipcode,"
             . "     REPLACE(SUBSTRING(jb.jb_tourdata, 1, (INSTR(jb.jb_tourdata, '|') - 1)), ';', ',') AS tr_zipcodes,"
             . "     REPLACE(SUBSTRING_INDEX(SUBSTRING(jb.jb_tourdata, (INSTR(jb.jb_tourdata, '|') + 1 )), '|', 1), ';', ',') AS tr_cities,"
             . "     tr.tr_comp, tr.tr_comp2, tr.tr_hsno, ad.ad_street, ad.ad_zipcode, ad.ad_city, CONCAT(ad.ad_street,' ',tr.tr_hsno) AS tr_street_hsno, crvh.crvh_payload"
             .       $fieldClause
             . " FROM job AS jb LEFT JOIN jobprice AS jbprc_km ON jb.jb_id = jbprc_km.jb_id AND jbprc_km.mt_sort = '11'"
             . "                LEFT JOIN jobprice AS jbprc_co2 ON jb.jb_id = jbprc_co2.jb_id AND jbprc_co2.mt_sort = '12'"
             . "                LEFT JOIN metatype AS mt ON jb.vht_id = mt.mt_sort AND mt.mt_type = 'vehicletype' AND mt.mt_sort > '0'"
             . "                LEFT JOIN metatype AS mt_real ON jb.vht_id_real = mt_real.mt_sort AND mt_real.mt_type = 'vehicletype' AND mt_real.mt_sort > '0'"
             . "                LEFT JOIN courier AS cr ON jb.cr_id = cr.cr_id"
             . "                LEFT JOIN couriervehicle AS crvh ON jb.cr_id = crvh.cr_id AND jb.cr_sid = crvh.crvh_sid,"
             . "      tour AS tr, address AS ad,"
             . "      costcenter AS csc, customer AS cs, company AS cmp" . $fromClause
             . " WHERE tr.jb_id = jb.jb_id AND tr.tr_sort = '1' AND tr.ad_id = ad.ad_id AND"
             . "       jb.csc_id_payer = csc.csc_id AND cs.cs_id = csc.cs_id AND cmp.cmp_id = cs.cmp_id" . $whereClause
             .   $orderByClause;
  return $retStmt;
}


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

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"))) :

   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;


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

      // 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";
         $typeArr["jb_ordertime"] = "datetime";
         $typeArr["jb_finishtime"] = "datetime";
         // $typeArr["jb_percent"] = "float";
         // $typeArr["crvh_partner_commission"] = "float";
         // $typeArr["payout"] = "float";
         // $typeArr["eau"] = "float";
         // $typeArr["bsg"] = "float";        

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

         $triggerArray = array();
         $csvArray = array();

         // Insert header
         $headerArray = array("Kunde",  "Auftrag", "Preis",         "Firma",   "Startadresse",   "Fahrzeug",      "kg",           "Auftragszeit", "PLZen",       "Orte",      "Erledigungszeit", "km",    "CO2äq/kg");
         $fieldArray =  array("cs_eid", "jb_id",   "jb_totalprice", "tr_comp", "tr_street_hsno", "mt_value_real", "crvh_payload", "jb_ordertime", "tr_zipcodes", "tr_cities", "jb_finishtime",   "jb_km", "jb_co2");
         $triggerArray[] = $headerArray;
         $csvArray[] = implode(";", $headerArray);

         // Force Index Clause
         $forceIndexClause = "";
         // $forceIndexClause = "FORCE INDEX (jb_status_3)";

         // Special clauses
         $fieldClause = "";
         $fromClause = "";
         $whereClause = "";
         $orderByClause = "cs.cs_eid, jb.jb_id";  // Default
         
         // Special WHERE clause
         $whereClause .= "jb.jb_finishtime >= '" . $fromDate . " 00:00:00" . "' AND jb.jb_finishtime <= '" . $toDate . " 23:59:59" . "' AND "
                       . "jb.jb_status = '2' AND "
                       . "jb.jb_incomplete = '0' AND "
                       . "(NOT isnull(jb.jb_export_time)) AND jb.jb_export_time != '0000-00-00 00:00:00' AND jb.jb_export_time != '9999-12-31 23:59:59' ";
                       // . "(isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1') "

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

         // CUSTOMER
         if ($objType == "cs") :
            // $fieldClause .= "";
            // $fromClause .= "";
            $whereClause .= " AND cs.cs_id = '" . $objId . "'";
         endif;

         // META CUSTOMER
         if ($objType == "cs_meta") :
            // $fieldClause .= "";
            $fromClause .= "customer AS cs2";
            $whereClause .= " AND cs2.cs_id = '" . $objId . "' AND cs.cs_id_parent = cs2.cs_id";
         endif;

         $sqlquery = getStmtJbSustainabilityList($whereClause, $orderByClause, $fieldClause, $fromClause, $forceIndexClause);
// echo $sqlquery . "\n\n"; die();
         $result = $db->query($sqlquery);   
         if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
         while ($row = $result->fetchRow()):

               $lineArr = array($row[$fieldArray[0]], 
                                $row[$fieldArray[1]], 
                                number_format(round($row[$fieldArray[2]],2), 2, ",", "."), 
                                $row[$fieldArray[3]], 
                                $row[$fieldArray[4]], 
                                ($row["vht_id_real"] == 0 ? $row["mt_value"] : $row[$fieldArray[5]]), 
                                number_format(round(($row["jb_weight"] > 0 ? $row["jb_weight"] : ($row[$fieldArray[6]] / 2)),0), 0, ",", "."), 
                                $row[$fieldArray[7]], 
                                $row[$fieldArray[8]], 
                                $row[$fieldArray[9]], 
                                $row[$fieldArray[10]], 
                                number_format(round($row[$fieldArray[11]],2), 2, ",", "."), 
                                number_format(round($row[$fieldArray[12]],2), 2, ",", "."));
               $triggerArray[] = $lineArr;
               $csvArray[] = implode(";", $lineArr);
         endwhile;
         $result->free();

// 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>";
            $triggerOut .= "<table>\n";
            $triggerOut .= "<tr>\n";
            $triggerOut .= "<td style=\"background-color: #66CCFF;\">&nbsp;&nbsp;KEIN EINTRAG&nbsp;&nbsp;</td>";
            $triggerOut .= "<td style=\"background-color: #FFFF33;\">&nbsp;&nbsp;&nbsp;< 6 Monate&nbsp;&nbsp;&nbsp;</td>";
            $triggerOut .= "<td style=\"background-color: #FFCC33;\">&nbsp;&nbsp;&nbsp;< 3 Monate&nbsp;&nbsp;&nbsp;</td>";
            $triggerOut .= "<td style=\"background-color: #FF6633;\">&nbsp;&nbsp;&nbsp;< 2 Monate&nbsp;&nbsp;&nbsp;</td>";
            $triggerOut .= "<td style=\"background-color: #FF0033;\">&nbsp;&nbsp;&nbsp;< 1 Monat&nbsp;&nbsp;&nbsp;&nbsp;</td>";
            $triggerOut .= "</tr>\n";
            $triggerOut .= "</table>\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);
                // $percentValue = $triggerArray[$i][9];

                // 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";
                for ($j = 0; $j < $tmpArrayLen; $j++) :
                    if ($typeArr[$fieldArray[$j]] == "float") : 
                       $formattedOutput = formatOutput($tmpArray[$j], $typeArr[$fieldArray[$j]], "2");
                       $textAlign = "right";
                    elseif ($typeArr[$fieldArray[$j]] == "float_rounded_2") :
                       $formattedOutput = $tmpArray[$j];
                       $textAlign = "right";
                    elseif ($typeArr[$fieldArray[$j]] == "datetime") :
                       $formattedOutput = formatOutput($tmpArray[$j], $typeArr[$fieldArray[$j]], "4");
                       $textAlign = "center";
                    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";
                endfor;
                $triggerOut .= "</tr>\n";
            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;

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

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

            $mailtext = "NACHHALTIGKEITSAUFSTELLUNG";
            $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("179",$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; ?>