<?php
/*=======================================================================
 *
 * statistic_ikea.php
 *
 * Autor: Carsten Annacker
 *
 =======================================================================*/

error_reporting(E_ALL ^ (E_DEPRECATED | E_NOTICE));
//include_once("../include/dbconnect.inc.php");
include_once("../include/auth.inc.php");
include_once ("../include/inc_mtf_func.inc.php");
include_once("../include/email/htmlMimeMail.php");

$temp_csv_folder = "../temp/edifact/";
$sender = "support@assecutor.de";
$bcc = "ca@assecutor.de";
//$bcc = "";
$recipients = array("Daniel.Langhann@hansetrans.de", "abrechnung-leonberg@walter-moebeltransport.de");
//$recipients = array("ca@assecutor.de");

// Statistik erstellen
if (date("d") < 16):
  $inv_timestamp = mktime(0, 0, 0, date("m") - 1, 1, date("Y"));
  $inv_timestamp2 = mktime(0, 0, 0, date("m"), 1, date("Y"));
else:
  $inv_timestamp = mktime(0, 0, 0, date("m"), 1, date("Y"));
  $inv_timestamp2 = mktime(0, 0, 0, date("m") + 1, 1, date("Y"));
endif;
$inv_date = date("Y-m-d H:i:s", $inv_timestamp);
$inv_date_to = date("Y-m-d H:i:s", $inv_timestamp2);

$csc_id_relatedArr = array(
  "3506" => "Ludwigsburg",
  "3512" => "Sindelfingen"
);

$serviceLief = $db->getOne("SELECT mt_sort FROM metatype WHERE mt_type = 'service' AND mt_mapped_value = 'LI'");
$serviceMont = $db->getOne("SELECT mt_sort FROM metatype WHERE mt_type = 'service' AND mt_mapped_value = 'MO'");
$serviceNeuMont = $db->getOne("SELECT mt_sort FROM metatype WHERE mt_type = 'service' AND mt_mapped_value = 'NM'");
$serviceKueMont = $db->getOne("SELECT mt_sort FROM metatype WHERE mt_type = 'service' AND mt_mapped_value = 'KU'");
//$serviceAbhol = $db->getOne("SELECT mt_sort FROM metatype WHERE mt_type = 'service' AND mt_mapped_value = 'AB'");
//$serviceAust = $db->getOne("SELECT mt_sort FROM metatype WHERE mt_type = 'service' AND mt_mapped_value = 'AT'");

$typeArr = array(
  "TG" => "Taggleiche Lieferungen",
  "L"  => "Lieferungen",
  "M"  => "Küchenmontagen",
  "MM" => "Möbelmontagen"
);

$csv_file_nameArr = array(
);
$filecnt = 1;

foreach (array("TG", "L", "M", "MM") as $cur_type) {
  foreach (array(3506,3512) as $csc_id_related) {
  	echo "Erstelle Datei " . $filecnt++ . " von 8...<br>\n";
//    flush();
    $csv_contents = "Extra-Statistik für;IKEA " . $csc_id_relatedArr[$csc_id_related] . ":;" . $typeArr[$cur_type] . " \n\n" .
      "Auftragsnummer;Eingang;Terminvereinbarung;Plandatum;Erledigung;offen;ok;nicht ok\n";
    $cntArr = array(0,0,0,0);
    
    $sqlquery = "SELECT DISTINCT jb_id, jb_id_parent, jb_freetext_1, jb_ordertime, jb_finishtime, jb_status, jb_service FROM job " .
      "WHERE jb_finishtime > '$inv_date' AND jb_finishtime < '$inv_date_to' AND csc_id_related = $csc_id_related AND jb_storno IS NULL AND jb_offer = 0 ORDER BY jb_finishtime";
    $res = $db->query($sqlquery);
    if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
    while ($row = $res->fetch_assoc()):
      $jb_service = mcConvertNum2Sel($row["jb_service"]);
      $type_str = "";
      if (in_array($serviceNeuMont, $jb_service)):
        $type_str = "MM";
      endif;
      if (in_array($serviceKueMont, $jb_service)):
        $type_str = "M";
      endif;
      if (in_array($serviceLief, $jb_service)):
        $type_str = "L";      
      endif;
      if ($type_str != "" && $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $row["jb_id"] . " AND gdc_gen_fieldname = 'jb_service_job'") != "1"):
        $log_createtime = $db->getOne("SELECT log_createtime FROM phoenix_log.log WHERE (log.jb_id = '" . $row["jb_id"] . "' OR log.jb_id = '" . $row["jb_id_parent"] . "') AND logo_id = 1");
  //echo substr($log_createtime, 0, 10) . " == " . substr($row["jb_ordertime"], 0, 10) . "?\n";
        if ($type_str == "L" && substr($log_createtime, 0, 10) == substr($row["jb_ordertime"], 0, 10))
          $type_str = "TG";
//        if (($log_createtime == "" || (strtotime($log_createtime) < $inv_timestamp2 && strtotime($log_createtime) > $inv_timestamp)) && $type_str == $cur_type):
        if ($type_str == $cur_type):
           $ok_str = ";;";
           if ($row['jb_finishtime'] == ""):
             $ok_str = "X;;";
             $cntArr[1]++;
           else:
             if (substr($row["jb_freetext_1"], 0, 10) == substr(formDateTime($row['jb_finishtime']), 0, 10)):
               $ok_str = ";X;";
               $cntArr[2]++;
             else:
               $ok_str = ";;X";
               $cntArr[3]++;
             endif;
           endif;
  //echo "$log_createtime\n";
          $csv_contents .= $row['jb_id'] . ";" . formDateTime($log_createtime) . ";" . $row["jb_freetext_1"] . ";" . formDateTime($row['jb_ordertime']) . ";" . formDateTime($row['jb_finishtime']) . ";" . $ok_str  . "\n";
          $cntArr[0]++;
        endif;
      endif;
    endwhile;
    $res->free();
    $csv_contents .= "Summen;" . $cntArr[0] . ";;;;" . $cntArr[1] . ";" . $cntArr[2] . ";" . $cntArr[3] . "\n";

  //  if ($type_str == "Ab" || $type_str == "Au")
  //    $type_str = "L";
    $csv_file_name = substr($inv_date, 0, 7) . "_" . $csc_id_relatedArr[$csc_id_related] . "_" . $cur_type . ".csv";
    $fileHandle = @fopen($temp_csv_folder . $csv_file_name, 'w');
    @fwrite($fileHandle, $csv_contents);
    @fclose($fileHandle);
    $csv_file_nameArr[] = $csv_file_name;
  }
}
$mailObj = new htmlMimeMail();
$mailObj->setFrom($sender);
if (trim($bcc) != "")
  $mailObj->setBcc($bcc);
$mailObj->setSubject("Statistik IKEA");
$mailObj->setText("Im Anhang die Statistiken");
foreach ($csv_file_nameArr as $csv_file_name)  
  $mailObj->addAttachment($mailObj->getFile($temp_csv_folder . $csv_file_name), $csv_file_name);   
$mailResult = $mailObj->send($recipients, 'smtp');
echo "Mail wurde versandt, dieses Fenster kann geschlossen werden.<br>\n";

function formDateTime($sqlDate) {
  if (trim($sqlDate) == "")
    return "";
  return substr($sqlDate, 8, 2) . "." . substr($sqlDate, 5, 2) . "." . substr($sqlDate, 0, 4) . " " . substr($sqlDate, 11, 5);
}
