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

include_once ("../include/mcglobal.inc.php");
// include_once ("../include/image.inc.php");
include_once ('../include/email/htmlMimeMail.php');


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


// Get jobs for autoembargo
function getDPFData($limit = 0) {
  global $db, $logFile;

  // Try to connect request server because of performance
  global $db2;
  getDb2Connection();

  $retArray = array();

  // Limit    
  if (is_numeric($limit) && $limit > 0) :
     $limit = "LIMIT 0," . $limit;
  else :
     $limit = ""; 
  endif;

  $whereClauseStartTime = "";
  $constDPFChecktimeEnabled = getParameterValue("0", "DPF_CHECKTIME_ENABLED", "0");  // "Meta-Global" <=> hq_id = 0
  if ($constDPFChecktimeEnabled == "1") :   
     $constDPFChecktimeInDays = getParameterValue("0", "DPF_CHECKTIME_IN_DAYS", "0");
     if ($constDPFChecktimeInDays == "") : $constDPFChecktimeInDays = 0; endif;
     $startTime = getDateTime("datetime_plus_offset", array(0,0,0,0,-($constDPFChecktimeInDays),0), "Y-m-d H:i:s");
     $whereClauseStartTime = "       cmp.cmp_dpf_datetime > '" . $startTime . "' AND";
  endif;

  $sqlquery = "SELECT cmp.cmp_id, cmp.cmp_type, cmp.cmp_comp, cmp.cmp_comp2, cmp.cmp_iln, cmp.cmp_tax_idno,"
               . "    cmp.cmp_bank, cmp.cmp_bankno, cmp.cmp_bankacc, cmp.cmp_authenticated,"
               . "    cmp.cmp_match, cmp.cmp_cashmode, cmp.cmp_hsno, cmp.cmp_dpf_checksum,"
               . "    cs.hq_id, cs.cs_id, cs.cs_eid, cs.hq_id, cs.csc_id,"
               . "    usr.usr_name, usr.usr_firstname, usr.usr_email, usr.usr_phone,"
               . "    usr.usr_phone2, usr.usr_fax, ad.ad_street, ad.ad_zipcode, ad.ad_city"
               . " FROM company AS cmp, customer AS cs, employee AS emp, user AS usr, address AS ad"
               . " WHERE cmp.cmp_dpf_state = '0' AND"
               .         $whereClauseStartTime
               . "       cmp.cmp_authenticated = '1' AND"
               . "       cmp.cmp_id = cs.cmp_id   AND"
               . "       cmp.ad_id = ad.ad_id     AND"
               . "       cs.cs_admin = emp.emp_id AND"
               . "       emp.usr_id = usr.usr_id"
               . " ORDER BY cmp.cmp_comp"
               . " " . $limit;
// echo $sqlquery . "<br>";
  $result = $db2->query($sqlquery);
  if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

  while ($row = $result->fetch_assoc()):
        $retArray[] = array($row["cmp_id"], $row["cmp_comp"], $row["cmp_comp2"], $row["cmp_iln"], $row["cmp_tax_idno"], 
                            $row["usr_name"], $row["usr_firstname"], $row["usr_email"], $row["usr_phone"], 
                            $row["ad_street"], $row["cmp_hsno"], $row["ad_zipcode"], $row["ad_city"], $row["hq_id"], 
                            $row["cs_eid"], $row["cmp_dpf_checksum"]);
  endwhile;
  $result->free();
  return $retArray;
}  



// START SCRIPT

// $path = getParameterValue("0", "PATH_DOCROOT", "0");
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);


// Endless loop
// while (TRUE):

  // Set execution time for keepalive
  $currentTime = getDateTime("0");
  // updateStmt("keepalive", "ka_process", "dpf", array("ka_lastexecutiontime", $currentTime),"");
  
    
  // ********************************
  // *** Send mails automatically ***
  // ********************************

  $constDPFCustomerEnabled = getParameterValue("0", "DPF_CS_ENABLED", "0");  // "Meta-Global" <=> hq_id = 0
  if ($constDPFCustomerEnabled == '1') :

     // Log file
     $logFile = getParameterValue("0", "DPF_LOGFILE", "0");

     // Get data of the customers to be checked
     $dataArray = getDPFData(1);

     // Loop all entries
     $lenDataArray = count($dataArray);

     // Mark all rows selected for embargo check
     // Do this here to avoid multiple rows
     for ($i = 0; $i < $lenDataArray; $i++) :
         updateStmt("company", "cmp_id", $dataArray[$i][0], array("cmp_dpf_state", "99"), "");
     endfor;

     for ($i = 0; $i < $lenDataArray; $i++) :

         // Current data to be checked
         $cmpId = $dataArray[$i][0];
         $cmpComp = $dataArray[$i][1];
         $cmpComp2 = $dataArray[$i][2];
         $cmpILN = $dataArray[$i][3];
         $cmpTaxIdno = $dataArray[$i][4];
         $usrName = $dataArray[$i][5];
         $usrFirstname = $dataArray[$i][6];
         $usrEmail = $dataArray[$i][7];
         $usrPhone = $dataArray[$i][8];
         $adStreet = $dataArray[$i][9];
         $cmpHsno = $dataArray[$i][10];
         $adZipcode = $dataArray[$i][11];
         $adCity = $dataArray[$i][12];
         $hqId = $dataArray[$i][13];
         $eid = $dataArray[$i][14];
         $cmpDpfChecksum = $dataArray[$i][15];

         // Define type to be checked (needed in the following INCLUDE)
         $autoembargo = "1";
         $DPFTypeToBeChecked = "cs";

         if ($cmpId != "") :

            // Start to generate the request
            include_once ("../include/dpf.php");

            // Handling according to the result
            /*
            if ($dfpErrCode == "0") :
               $currentTime = getDateTime("0");
               if ($dfpMatchlevel == "1" || $dfpMatchlevel == "2") :
                  updateStmt("company","cmp_id",$cmpId,array("cmp_dpf_state", $dfpMatchlevel, "cmp_dpf_datetime", $currentTime);
               endif;
            endif;
            */

            // Write logdata into log file
            // writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . $f_email . "] [SID: " . $job_crSid . "] [Erledigung] [Status: " . $statusSent . "]");
         endif;
         
         $cmpId = "";

     endfor;  // Loop all rows
  endif;

//   sleep(30);

// endwhile;  // Endless loop
?>
