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


include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");
include_once ("../include/image.inc.php");
include_once ("../include/caglobal.inc.php");


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "customerId", "cscIdRoot", "cscIdActual",
                  "day_from", "month_from", "year_from", "day_to", "month_to", "year_to",
                  "g_cs_id", "g_csc_id", "g_csc_name", "initCsSearch", "f_filter", "f_vht_filter",
                  "f_inv_no", "f_inv_datetime_day", "f_inv_datetime_month", "f_inv_datetime_year",
                  "filenameCSV", "statusMessage", "deactivateMenu"));


$pageTitel = "CSV-AUSGABE";
$deactivateMenuStatic = "1";
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");

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

$phpVer56Plus = false;
if (substr(phpversion(), 0, 3) >= "5.6") :
   $phpVer56Plus = true;
endif;

// Get global export path
$globalExportPath = getParameterValue("0", "EXPORT_PATH", "0");
if ($globalExportPath == "") : $globalExportPath = getParameterValue("0", "EXPORT_PATH", "0"); endif;
if ($globalExportPath == "") : $globalExportPath = "../export/download/"; endif;

$path = getAbsoluteSystemPath();

// Check range of date. All fields have to be set
if ($day_from == "" || $month_from == "" || $year_from == "" || 
    $day_to == "" || $month_to == "" || $year_to == "") :
 
    // Initialize date-ranges to the current date
    $fromDateRange = getDateTime("1") . "000000";
    $toDateRange = getDateTime("1") . "235959";
 
    $day_from = getDateTime("day");
    $month_from = getDateTime("month");
    $year_from = getDateTime("year");
    $day_to = getDateTime("day");
    $month_to = getDateTime("month");
    $year_to = getDateTime("year");
else :
    $fromDateRange = $year_from . pad($month_from,2) . pad($day_from,2) . "000000";
    $toDateRange = $year_to . pad($month_to,2) . pad($day_to,2) . "235959";
endif;

// Select user-type for mode of security check 
$userType = getFieldValueFromId("user","usr_id",$usr_id,"usr_type");

// Check authentication verifying emmployee an his/her costcenter- and customer-association
if ( !( ($userType == "1") || authCheck($hq_id,$usr_id,$emp_id,$cscIdRoot,$customerId,$cscIdActual) ) ) : gotoReferer("1"); endif;

// Get the rights of the employee logged in and check the accessibility
authCheckEmployeeRights($emp_id, "7", "1");

getDBNames("0");    // Only use current tables (no history tables)

// Get company data
$g_cmp_id = getFieldValueFromId("customer", "cs_id", $g_cs_id, "cmp_id");
$g_cs_eid = getFieldValueFromId("customer", "cs_id", $g_cs_id, "cs_eid");
$g_cmp_comp = getFieldValueFromId("company", "cmp_id", $g_cmp_id, "cmp_comp");
$g_cmp_comp2 = getFieldValueFromId("company", "cmp_id", $g_cmp_id, "cmp_comp2");

$f_inv_no = trim($f_inv_no);
$f_inv_datetime = "";
if ($f_inv_datetime_month >= "1" && $f_inv_datetime_month <= "12" && $f_inv_datetime_day >= "1" && $f_inv_datetime_day <= "31") :
   $f_inv_datetime = $f_inv_datetime_year . "-" . $f_inv_datetime_month . "-" . $f_inv_datetime_day . " 12:00:00";
endif;


if ($f_filter == "") : $f_filter = "0"; endif;     // Filter (order clause by CSV generation)
if ($f_vht_filter == "") : $f_vht_filter = array(); endif;      // filter for vehicle of the courier for exporting ALL or ONLY the specified vehicle types


// Generate CSV document
if ($f_act == "generateCSV") :
   if ($g_cs_id != "") :

      $passwd = "acapella7890";
      $logFile = $path . "/log/sys_auto_export.log";
      $emptyArgument = "\"\"";
      $fileNameSuffix = substr(getDateTime("6"), 0, 12);  // Format: "YmdHi"

      // Get data for calling customer export functionality
      $g_cs_admin    = getFieldValueFromId("customer", "cs_id", $g_cs_id, "cs_admin");
      $g_hq_id       = getFieldValueFromId("customer", "cs_id", $g_cs_id, "hq_id");
      $g_hq_mnemonic = getFieldValueFromId("headquarters", "hq_id", $g_hq_id, "hq_mnemonic");
      $g_usr_id      = getFieldValueFromId("employee", "emp_id", $g_cs_admin, "usr_id");            

      // t:m special function (!!!!)
      $f_act = "special_export_5";

      // Arguments for calling customer export
      // $hq_id $usr_id $dummy_01 $f_act $f_exp_category $f_delimiter $f_parname $f_parname_export $f_fileName $day_to $month_to $year_to $f_cs_eid_filter $day_from $month_from $year_from $f_jbp_filter $specialJbPayment $jbpc_id

      // Bsp: STHB.t:m: $g_hq_id = "1"; $g_hq_mnemonic = "HB"; $g_cs_id = "832514"; $g_usr_id = "840785"; 

      $exportPars = array();
      $exportPars[] = array($g_hq_id,$g_usr_id,"_",$f_act,$emptyArgument,$emptyArgument,$emptyArgument,$emptyArgument,$g_cs_eid . "_" . $fileNameSuffix . ".csv",$day_to,$month_to,$year_to,$emptyArgument,$day_from,$month_from,$year_from,$g_cs_id);

      $exportParsKeys = array_keys($exportPars);
      $exportParsKeysLen = count($exportParsKeys);
      if ($exportParsKeysLen != "" && is_numeric($exportParsKeysLen)) :

         // Exports
         for ($i = 0; $i < $exportParsKeysLen; $i++) :

             list($hq_id,$usr_id,$dummy_01,$f_act,$f_exp_category,$f_delimiter,$f_parname,$f_parname_export,$f_fileName,
                  $day_to,$month_to,$year_to,$f_cs_eid_filter,$day_from,$month_from,$year_from,$customerId,$f_jbp_filter,$specialJbPayment,$jbpc_id) = $exportPars[$exportParsKeys[$i]];
      
             $cmd = "php " . $path . "/export/export.php " . $passwd . " " . $hq_id . " " . $usr_id . " " . $dummy_01 . " " . $f_act . " " . $f_exp_category . " " . "\"" . $f_delimiter. "\"" . " " 
                                                           . "\"" . $f_parname . "\"" . " " . "\"" . $f_parname_export . "\"" . " " . "\"" . $f_fileName . "\"" . " " . $day_to . " " . $month_to . " " . $year_to . " " 
                                                           . $f_cs_eid_filter . " " . $day_from . " " . $month_from . " " . $year_from . " " . $customerId . " " . $f_jbp_filter . " " . $specialJbPayment . " " . $jbpc_id;  // . " &";
// echo $cmd . "\n\n\n"; die();
             $cmdOutput = null;
             exec($cmd, $cmdOutput);
             // list($errNo, $errDesc) = $cmdOutput;

             $currentTime = getDateTime("0");
             writeToFile($logFile, "OP=AUTO_EXPORT|DATETIME=" . $currentTime . "|CUST=" . $exportParsKeys[$i]);

             $f_act = "loadJobsOfCustomer";

             // sleep(5);  // Avoid too many tasks
         endfor;
      endif;
   else :
      $statusMessage = "Sie haben noch keinen Kunden ausgewählt!";
   endif;
endif;


// *** Output ***
$storedExportFiles = "";
if ($g_cs_id != "" && is_numeric($g_cs_id) && $g_cs_id > "0") :

   // Read all of the local exported filenames for the current customer   

   $sqlquery = "SELECT expf_id, expf_name, expf_cryptname, expf_storetime, expf_ftpupload"
               . " FROM exportfiles"
               . " WHERE cs_id = '" . $g_cs_id . "'"
               . " ORDER BY expf_storetime DESC";
   
   $result = $db->query($sqlquery);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());   
   
   $expfIdArray = array();
   $expfCryptNameArray = array();

   $customerId  = $g_cs_id;
   $cscIdRoot   = getFieldValueFromId("customer", "cs_id", $customerId, "csc_id");
   $cscIdActual = $cscIdRoot;
   
   // Restrictions to display links for FTP upload
   /*
   $parFTPuploadDisabled = getParameterValue("0", "EXPORT_MASK_FTP_UPLOAD_DISABLED", $hq_id);
   if ($parFTPuploadDisabled == "") : $parFTPuploadDisabled = getParameterValue("0", "EXPORT_MASK_FTP_UPLOAD_DISABLED", "0"); endif;
   */

   $storedExportFiles .= "<table>";
   // Define table header
   $storedExportFiles .= "<tr>";
   $storedExportFiles .= "<td>Datum / Uhrzeit</td><td>WEB-Download</td>";
   $storedExportFiles .= "</tr>";
   // Define table body from result set
   while ($row = $result->fetch_assoc()):            
         $expfIdArray[] = $row["expf_id"];
         $expfCryptNameArray[] = $row["expf_cryptname"];
         $storedExportFiles .= "<tr>";
         $storedExportFiles .= "<td>" . formatOutput($row["expf_storetime"],"timestamp") . "&nbsp;&nbsp;&nbsp;&nbsp;</td>";

         $storedExportFiles .= "<td><a href=\"../export/exportdata.php?customerId=" . ec($customerId) . "&cscIdRoot=" . ec($cscIdRoot) . 
                                                           "&cscIdActual=" . ec($cscIdActual) . "&f_fileName=" . $row["expf_name"] . "\" target=\"_blank\">" . 
                                     $row["expf_name"] . "</a>&nbsp;&nbsp;&nbsp;&nbsp;</td>";
         // Enable FTP upload option only for headquarter
         /*
         if ($userTypeName == "hq" && $parFTPuploadDisabled != "1") :
            if ($row["expf_ftpupload"] != "1") :
               $storedExportFiles .= "<td><a href=\"exportdata_ftp.php?f_fileName=" . $row["expf_name"] . "&customerId=" . ec($customerId) . 
                                           "&cscIdRoot=" . ec($cscIdRoot) . "&cscIdActual=" . ec($cscIdActual) . "\" target=\"_blank\">" . 
                                           $row["expf_name"] . "</a></td>";
            else :
               $storedExportFiles .= "<td>" . $row["expf_name"] . "</td>";
            endif;
         endif;
         */
         $storedExportFiles .= "</tr>";
   endwhile;
   $storedExportFiles .= "</table>";
   $result->free();

   // Init, because script works in headquarters mode only
   $customerId  = "";
   $cscIdRoot   = "";
   $cscIdActual = "";

   // Automatical deletion of more than 10 files
   $maxEntries = getParameterValue("0", "EXPORT_FILES_ON_SERVER_CUSTOMER", "0");
   if ($maxEntries == "" || !is_numeric($maxEntries)) : $maxEntries = "10"; endif;
   $expfIdArrayLen = count($expfIdArray);
   if ($expfIdArrayLen >= $maxEntries) :
      
      for ($j = $maxEntries - 1; $j < $expfIdArrayLen; $j++) :
          
          unlink($globalExportPath . $expfCryptNameArray[$j]);               // delete file
          deleteStmt("exportfiles","expf_id = " . $expfIdArray[$j]);   // delete corresponding db-entry
      endfor;   
   endif;
endif;


$currentFrameName = "";  // Empty string for "main frame"

// Date-ranges 
$filter_dateranges .= "<td><span class=\"f12bp1_blue\">Auftragsdatum:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>";
$filter_dateranges .= "Von:\n";
$filter_dateranges .= "<select name=\"day_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'jb_exp_csv', 'day_from', 'day_from', 'month_from', 'year_from', '', '', '')\"></select>\n";
$filter_dateranges .= "<select name=\"month_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'jb_exp_csv', 'month_from', 'day_from', 'month_from', 'year_from', '', '', '')\"></select>\n";
$filter_dateranges .= "<select name=\"year_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'jb_exp_csv', 'year_from', 'day_from', 'month_from', 'year_from', '', '', '')\"></select>\n";
$filter_dateranges .= "</td><td>&nbsp;&nbsp;bis:\n";
$filter_dateranges .= "<select name=\"day_to\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'jb_exp_csv', 'day_to', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
$filter_dateranges .= "<select name=\"month_to\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'jb_exp_csv', 'month_to', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
$filter_dateranges .= "<select name=\"year_to\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'jb_exp_csv', 'year_to', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
$filter_dateranges .= "</td>";   

// Javascript-function as template only for
$js_date = "<script type=\"text/javascript\">\n";
$js_date .= "<!--\n";
$js_date .= "function initForm() {\n";
$js_date .= "  fillDateFields(1,\"" . $currentFrameName . "\",\"jb_exp_csv\",\"\",\"day_from\",\"month_from\",\"year_from\",\"\",\"\",\"\");\n";
$js_date .= "  setDateTimeFields(\"" . $currentFrameName . "\",\"jb_exp_csv\",".$day_from.",".$month_from.",".$year_from.", \"\", \"\", \"day_from\", \"month_from\", \"year_from\", \"\", \"\", \"\");\n";
$js_date .= "  fillDateFields(1,\"" . $currentFrameName . "\",\"jb_exp_csv\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
$js_date .= "  setDateTimeFields(\"" . $currentFrameName . "\",\"jb_exp_csv\",".$day_to.",".$month_to.",".$year_to.", \"\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
$js_date .= "}\n";
$js_date .= "-->\n";
$js_date .= "</script>\n";   
?>

<html>

<head>
<title>CSV-AUSGABE</title>

<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
  <?php include_once ("../css/navigation.css.php"); ?>
</style>

<?php include_once ("../include/js_framework.inc.php"); ?>

<script src="../include/searchLists.js" type="text/javascript"></script>
<script src="../include/checkFormTags.js" type="text/javascript"></script>
<script src="../include/lib_global.js" type="text/javascript"></script>

<?php echo $js_date ?>

<script type="text/javascript">
<!--
// NAVIGATION
<?php echo $jsMenuOut; ?>

function searchCs() {
  searchCsCscGeneric('111000000000111');
};

function finishPage(mode) {
  if (mode == 'generateCSV') {
     if (document.forms[0].g_cs_id.value != '') {
        if (confirm('Möchten Sie die CSV-Datei über den angegebenen Zeitraum generieren?')) {
  	        document.forms[0].f_act.value = mode;
   	        document.forms[0].action.disabled = true;
            document.forms[0].submit();
        }
     } else {
       alert('Sie müssen zuvor bitte einen Kunden wählen!');
     }
  }
  if (mode == 'clearPageAndCustomerSearch') {
     if (document.forms[0].g_cs_id.value != '') {
        if (confirm('Möchten Sie einen neuen Kunden wählen? Die Seiteninformationen gehen verloren!')) {
           document.location.href = "jb_exp_csv_meta.php?initCsSearch=1";
        }
     } else {
     	searchCs();
     };
  }
};

function checkDate(checkObj,mode) {
  var resetValue = checkDateFields(checkObj,mode);
  if (resetValue) {
  	 checkObj.value = '';
     checkObj.focus();
  }
}

function showPageStatus() {
  alert('g_cs_id: ' + document.forms[0].g_cs_id.value);
  alert('g_csc_id: ' + document.forms[0].g_csc_id.value);
  alert('g_csc_name: ' + document.forms[0].g_csc_name.value);
}

function jbCheckAll(numOfRows) {
  for (i = 0; i < numOfRows; i++) {
	  document.getElementsByName('f_jobs[]')[i].checked = true;
	}
}

function jbUncheckAll(numOfRows) {
  for (i = 0; i < numOfRows; i++) {
	  document.getElementsByName('f_jobs[]')[i].checked = false;
  }
}
-->
</script>

</head>

<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?>initForm();displayStatusMessage(); <?php if ($initCsSearch == "1") : echo "searchCs();" ; endif; ?>">

<?php echo $phpMenuOut ?>
<?php echo $phpReducedMenuOut ?>
<?php echo $phpPageTitelOut ?>

<div class="maincontent" name="maincontent" id="maincontent">

  <form name="jb_exp_csv" action="jb_exp_csv_meta.php" method="post">
  
  <input type="hidden" name="f_act" value="">
  <input type="hidden" name="g_cs_id" value="<?php echo $g_cs_id ?>">
  <input type="hidden" name="g_csc_id" value="<?php echo $g_csc_id ?>">
  <input type="hidden" name="filenameCSV" value="">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">

  <?php echo htmlDivLineSpacer("5px"); ?>

  <!- Date-ranges -->
  <div class="f12bp1_blue">
    <table cellspacing="0" cellpadding="0" vspace="0" hspace="0">
      <tr>
         <?php echo $filter_dateranges ?>
      </tr>
    </table>
  </div>
  <?php echo htmlDivLineSpacer("40px", "", "left"); ?>

  <div class="f12bp1_blue">
    <div style="float:left">
      Kunde:&nbsp;&nbsp;
      <input type="text" name="g_cmp_comp" value="<?php echo $g_cmp_comp ?>" size="30" readonly >
      <input type="text" name="g_cmp_comp2" value="<?php echo $g_cmp_comp2 ?>" size="30" readonly >
      <input type="text" name="g_cs_eid" value="<?php echo $g_cs_eid ?>" size="10" readonly >
      <input type="text" name="g_csc_name" value="<?php echo $g_csc_name ?>" size="25" readonly >
      &nbsp;&nbsp;
      <!-- <input type="button" value="!!!" onClick="showPageStatus();"> -->
    </div>
    <?php echo defineButtonType10("Suchen", "action_search", "finishPage('clearPageAndCustomerSearch');", "120", "left", "5"); ?>
  </div>
  <?php echo htmlDivLineSpacer("30px", "", "left"); ?>

  <!-- Search, reset and store -->
  <div>
    <?php echo defineButtonType10("CSV&nbsp;erzeugen", "action_create", "finishPage('generateCSV');", "220", "left", "10"); ?>
  </div>
  <?php echo htmlDivLineSpacer("30px", "", "left"); ?>
  
  <!-- Filenames of the selected interval to generate CSV documents -->
  <div>
    <table class="f8np1" border="0" cellpadding="0">
      <tr>
        <td>
          <?php echo $storedExportFiles ?>
        </td>
      </tr>
    </table>
  </div>
  <?php echo htmlDivLineSpacer("30px", "", "left"); ?>

  </form>
</div>

</body>

</html>