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

include_once ("../import/import.php");

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


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "statusMessage", "importFile", "executeImportProcess", "deactivateMenu", "objType", "objId"));


getLanguage(__FILE__);

$deactivateMenuStatic = "1";
$pageTitel = getLngt("IMPORT ARTIKEL");
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
getCurrentScript(__FILE__);

// Check for authentication access
$usrAccessArray["hq"] = "1";
authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
if (!(authCheckEmployeeRights($emp_id, "22"))) : gotoReferer("1"); endif;

$empHasAdminRights = false;
$empIdRootAdmin = getEmpIdOfRootAdmin($userTypeName);
if ($empIdRootAdmin != "" && $emp_id == $empIdRootAdmin) : 
   $empHasAdminRights = true;
endif;
$debug = false;
if ($empIdRootAdmin == $emp_id) :
   $debug = false;
endif;
$showRawData = true;

if ($f_act != "executeImport" || $executeImportProcess != "1") : $executeImportProcess = ""; endif;    // Execute import after check run
$showExecutionProcessButton = true;
$outText = "";
$closeWindow = "0";
$delimiter = ";";
$fire = true;

// Customer and headquarters references have to exist
$hqId = "";
$csEid = "";
$objType = trim($objType);
$objId = trim($objId);
if ($objType == "CS" && is_numeric($objId)) :
   $csId = getFieldValueFromId("phoenix.customer", "cs_id", $objId, "cs_id");
endif;
if ($csId != "") :
   $hqId = getFieldValueFromId("phoenix.customer", "cs_id", $csId, "hq_id");
   $csEid = getFieldValueFromId("phoenix.customer", "cs_id", $csId, "cs_eid");
else :
   $csId = "0";
endif;
if ($hqId == "") :
   $hqId = $hq_id;
endif;
$hqMnemonic = getFieldValueFromId("phoenix.headquarters", "hq_id", $hqId, "hq_mnemonic");

if ($debug) :
   echo "f_act : " . $f_act . "<br>";
   echo "objType : " . $objType . "<br>";
   echo "objId : " . $objId . "<br>";
   echo "hqId : " . $hqId . "<br>";
   echo "csId : " . $csId . "<br>";
endif;


// Current file to be imported
$importFile = urldecode($importFile);
$posLastSlash = strripos($importFile, "/");
$posLastSlash++;
$pathname = substr($importFile, 0, $posLastSlash);
$filename = substr($importFile, $posLastSlash);
$outText = "<span class=\"f10bp1_blue\">" . getLngt("IMPORTDATEI:") . "</span>&nbsp;" . $filename . "<br><br>";

// Check group names for accessing the script !!!!
$groupId = "";
$groupName = "";
$tmpPosForGrpName = strrpos($filename, "_");
if (!($tmpPosForGrpName === false)) :
   $groupName = substr($filename, $tmpPosForGrpName + 1);
   // Remove extension if does exist
   $tmpPosForGrpName = strrpos($groupName, ".");
   if (!($tmpPosForGrpName === false)) :
      $groupName = substr($groupName, 0, $tmpPosForGrpName);
   endif;
   $groupId = getFieldValueFromId("phoenix.groups", "grp_name", $groupName, "grp_id");
endif;
if ($debug) :
   echo "groupName : " . $groupName . "<br>";
   echo "groupId : " . $groupId . "<br>";
   echo "<br>";
endif;


if ($importFile != "" && (($csId != "" && $csId != "0") || $groupId != "")) :

   if (file_exists($importFile)) :

      $currentTime = getDateTime("0");

      // Activate buffering
      ob_start();

      // ***********************
      // * IMPORT FILE article *
      // ***********************
      if (!(strpos($filename, "import_ARTICLE_") === false)) :

         $executionCount = 0;
         $insertCount = 0;
         $updateCount = 0;
         $failedCount = 0;

         $rowToImport = array();
         
         $parImportArticleFieldsGroup == "";
         if ($groupId != "") :
            $parImportArticleFieldsGroup = getParameterValue("0", "IMPORT_ARTICLE_FIELDS_GROUP_" . $groupId, "0");
         endif;
         if ($parImportArticleFieldsGroup != "") :
            /*
            $parImportArticleFieldsGroupArray = spliti(",", $parImportArticleFieldsGroup);
            $parImportArticleFieldsGroupArrayLen = count($parImportArticleFieldsGroupArray);
            for ($k = 0; $k < $parImportArticleFieldsGroupArrayLen; $k++) :
                $rowToImport[$k] = $parImportArticleFieldsGroupArray[$k];
            endfor;
            */
            $rowToImport = spliti(",", $parImportArticleFieldsGroup);
         else :
            // Default 
            $rowToImport[0]  = "f_at_name";         // Article number
            $rowToImport[1]  = "f_at_description";  // Article name
            $rowToImport[2]  = "f_at_totalweight";
            $rowToImport[3]  = "f_at_price";
            $rowToImport[4]  = "f_at_price2";       // Family price
            $rowToImport[5]  = "f_at_no_packages";  // Number of packages
            $rowToImport[6]  = "f_at_dummy";
         endif;

         $rowToImportLen = count($rowToImport);

         // Read file to import
         $data = importCSV($importFile, $delimiter);
         $dataLen = count($data);

         // Loop all rows (EXCEPT header row [$j = 1])
         for ($j = 0; $j < $dataLen; $j++) {

            // Loop for all fields of $fields of the row
            for ($i = 0; $i < $rowToImportLen; $i++) {
                ${$rowToImport[$i]} = $data[$j][$i];
            }

            if ($f_at_match == "") : $f_at_match = $groupName; endif;
            $f_at_name = removeFieldSigns($f_at_name);
            $f_at_description = removeFieldSigns($f_at_description);
            $f_at_match = removeFieldSigns($f_at_match);
            $f_at_barcode = removeFieldSigns($f_at_barcode);
            $f_atg_id = removeFieldSigns($f_atg_id);
            $f_at_bundlequantity = removeFieldSigns($f_at_bundlequantity);
            $f_at_bundlecode = removeFieldSigns($f_at_bundlecode);
            $f_at_stk_itemquantity = removeFieldSigns($f_at_stk_itemquantity);
            $f_at_stk_areaquantity = removeFieldSigns($f_at_stk_areaquantity);
            $f_at_serialno = removeFieldSigns($f_at_serialno);
            $f_at_totalweight = removeFieldSigns($f_at_totalweight);
            $f_at_no_packages = removeFieldSigns($f_at_no_packages);
            $f_at_price = removeFieldSigns($f_at_price);
            $f_at_price2 = removeFieldSigns($f_at_price2);
            $f_at_price3 = removeFieldSigns($f_at_price3);
            $f_at_price4 = removeFieldSigns($f_at_price4);
            $f_at_price5 = removeFieldSigns($f_at_price5);
            $f_at_price6 = removeFieldSigns($f_at_price6);          
            

            $f_at_totalweight = str_replace (",", ".", $f_at_totalweight);
            $f_at_totalweight = $f_at_totalweight / 1000;  // Gram => Kilo
            // $f_at_totalweight = $f_at_totalweight * 100;  // Kilo => Gram
            
            $f_at_no_packages = str_replace (",", ".", $f_at_no_packages);
            if ($f_at_no_packages == "" || !is_numeric($f_at_no_packages)) : $f_at_no_packages = "1"; endif;

            $f_at_price = str_replace (",", ".", $f_at_price);   // Has to be the standard price
            $f_at_prices_mt_sort = array();
            $f_at_prices_mt_sort[0] = str_replace (",", ".", $f_at_price2);  // First mt_sort entry (== "0") for this customer (e.g. "Familycard")
            $f_at_prices_mt_sort[1] = str_replace (",", ".", $f_at_price3);  // mt_sort == "1"
            $f_at_prices_mt_sort[2] = str_replace (",", ".", $f_at_price4);  // mt_sort == "2"
            $f_at_prices_mt_sort[3] = str_replace (",", ".", $f_at_price5);  // mt_sort == "3"
            $f_at_prices_mt_sort[4] = str_replace (",", ".", $f_at_price6);  // mt_sort == "4"

            if ($f_at_bundlequantity == "") : $f_at_bundlequantity = "1"; endif;
            if ($f_at_stk_itemquantity == "") : $f_at_stk_itemquantity = "1"; endif;
            if ($f_at_stk_areaquantity == "") : $f_at_stk_areaquantity = "1"; endif;
            // $f_atg_id  // Article group

            if ($showRawData) :
               if ($j == 0) :
                  echo "<b>f_at_name" . $delimiter . "f_at_description" . $delimiter . "f_at_totalweight" . $delimiter . "f_at_price" . $delimiter . "f_at_price2" . $delimiter . "f_at_no_packages </b><br>";
               endif;
               echo $f_at_name . $delimiter . $f_at_description . $delimiter . $f_at_totalweight . $delimiter . $f_at_price . $delimiter . $f_at_price2 . $delimiter . $f_at_no_packages . "<br>";
               ob_flush(); flush();
            endif;

            if ($f_at_name != "") :

               // Insert new article
               if ($fire && $executeImportProcess == "1") :

                  // TA("B");

                  $currAtId = "";
                  if (existsEntry("article",array("at_name", $f_at_name, "hq_id", $hqId))) :  // ,"at_match",$f_at_match????

                     // Get field data for the current article. If imported data of some fields are empty because of delta import (subset, some fields only), the do NOT overwrite existing informations
                     $atFieldsCurrent = getFieldsValueFromId("phoenix.article", "at_name", $f_at_name, array("at_match","at_description","at_barcode","at_bundlequantity","at_bundlecode","at_stk_itemquantity","at_stk_areaquantity","at_serialno","at_totalweight","at_packingpieces"));
                     if ($atFieldsCurrent[0] != "" && $f_at_match == "") : $f_at_match = $atFieldsCurrent[0]; endif;                                           // at_match
                     if ($atFieldsCurrent[1] != "" && $f_at_description == "") : $f_at_description = $atFieldsCurrent[1]; endif;                               // at_description
                     if ($atFieldsCurrent[2] != "" && $f_at_barcode == "") : $f_at_barcode = $atFieldsCurrent[2]; endif;                                       // at_barcode
                     if ($f_at_barcode == "") : $f_at_barcode = $f_at_name; endif;                                                                             // at_barcode <- at_name
                     if ($atFieldsCurrent[3] != "" && $f_at_bundlequantity != $atFieldsCurrent[3]) : $f_at_bundlequantity = $atFieldsCurrent[3]; endif;        // at_bundlequantity
                     if ($atFieldsCurrent[4] != "" && $f_at_bundlecode == "") : $f_at_bundlecode = $atFieldsCurrent[4]; endif;                                 // at_bundlecode
                     if ($atFieldsCurrent[5] != "" && $f_at_stk_itemquantity != $atFieldsCurrent[5]) : $f_at_stk_itemquantity = $atFieldsCurrent[5]; endif;    // at_stk_itemquantity
                     if ($atFieldsCurrent[6] != "" && $f_at_stk_areaquantity != $atFieldsCurrent[6]) : $f_at_stk_areaquantity = $atFieldsCurrent[5]; endif;    // at_stk_areaquantity
                     if ($atFieldsCurrent[7] != "" && $f_at_serialno == "") : $f_at_serialno = $atFieldsCurrent[7]; endif;                                     // at_serialno
                     if ($atFieldsCurrent[8] != "" && $f_at_totalweight == "") : $f_at_totalweight = $atFieldsCurrent[8]; endif;                               // at_totalweight
                     if ($atFieldsCurrent[9] != "" && $f_at_no_packages == "") : $f_at_no_packages = $atFieldsCurrent[9]; endif;                               // at_no_packages

                     // Update article
                     // $defaultFields = array("at_match", $f_at_match, "at_description", $f_at_description, "at_barcode", $f_at_barcode, "at_bundlequantity", $f_at_bundlequantity, "at_bundlecode", $f_at_bundlecode, "at_stk_itemquantity", $f_at_stk_itemquantity, "at_stk_areaquantity", $f_at_stk_areaquantity, "at_serialno", $f_at_serialno, "at_totalweight", $f_at_totalweight, "at_packingpieces", $f_at_no_packages);
// ATTENTION: ARTICLE DESCRIPTION PRESENTLY WILL NOT BE UPDATED !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                     $defaultFields = array("at_match", $f_at_match, "at_barcode", $f_at_barcode, "at_bundlequantity", $f_at_bundlequantity, "at_bundlecode", $f_at_bundlecode, "at_stk_itemquantity", $f_at_stk_itemquantity, "at_stk_areaquantity", $f_at_stk_areaquantity, "at_serialno", $f_at_serialno, "at_totalweight", $f_at_totalweight, "at_packingpieces", $f_at_no_packages);
                     $res = updateStmt("phoenix.article", "at_name", $f_at_name, $defaultFields, "hq_id = '" . $hqId . "'");

                     // Check update for success
                     if ($db->affected_rows > 0) :
                        $executionCount++;
                        $updateCount++;
                        $currAtId = getFieldValueFromClause("phoenix.article","at_id","at_name = '" . $f_at_name . "' AND hq_id = '" . $hqId . "'");
                        $outText .= getLngt("Update des Artikels:") . " " . $f_at_name . " [" . getLngt("NL") . " " . $hqMnemonic . "]<br>";
                     else :
                        $failedCount++;
                     endif;
                  else :
                     // Set special fields
                     if ($f_at_barcode == "") : $f_at_barcode = $f_at_name; endif;    // at_barcode <- at_name

                     // Get max-value of the EID of the current article for inserting a new row
                     // The constant value "AT_EID_GENERATION" contains the prefix of the SID [SPECIAL TREATMENT]
                     // Get EID prefix and reset EID only if equals prefix
                     $constAtEidPrefix = getParameterValue("0", "AT_EID_PREFIX", $hqId);
                     if ($constAtEidPrefix == "") : $constAtEidPrefix = getParameterValue("0", "AT_EID_PREFIX", "0"); endif;
                     $constAtEidGeneration = getParameterValue("0", "AT_EID_GENERATION", $hqId);
                     if ($constAtEidGeneration == "") : $constAtEidGeneration = getParameterValue("0", "AT_EID_GENERATION", "0"); endif;
                     $f_eid_maxval = "";
                     if ($constAtEidGeneration != "") :
                        $f_eid_maxval = getMaxOfField("article", "at_eid", "at_eid < '" . $constAtEidGeneration . "'");
                     endif;
                     // Check existence of at least one EID with requested prefix
                     if ($f_eid_maxval == "" || substr($f_eid_maxval, 0, strlen($constAtEidPrefix)) != $constAtEidPrefix) :
                        $f_eid_maxval = $constAtEidPrefix . "100000";
                     endif;
                     if (is_numeric($f_eid_maxval)) :
                        ++$f_eid_maxval;   // Increment because of the next free EID (Attention: Not TA-safe!)
                     else :
                       // Remove alphanumeric chars (e.g "HTHB123456" => "123456")
                       $prefixChars = ereg_replace("[^[:alpha:]+]","",$f_eid_maxval);
                       $f_eid_maxval = ereg_replace("[^[:digit:]+]","",$f_eid_maxval);
                       ++$f_eid_maxval;
                       $f_eid_maxval = $prefixChars . $f_eid_maxval;
                     endif;

                     // Insert article
                     if ($f_eid_maxval != "") :

                        insertStmt("article", array("at_eid", $f_eid_maxval, "at_name", $f_at_name, "hq_id", $hqId, "at_match", $f_at_match, "at_description", $f_at_description, "at_barcode", $f_at_barcode, "at_createtime", $currentTime,
                                                    "atg_id", $f_atg_id, "at_bundlequantity", $f_at_bundlequantity, "at_bundlecode", $f_at_bundlecode, "at_stk_itemquantity", $f_at_stk_itemquantity, "at_stk_areaquantity", $f_at_stk_areaquantity, 
                                                    "at_serialno", $f_at_serialno, "at_totalweight", $f_at_totalweight, "at_packingpieces", $f_at_no_packages));
                        $currAtId = getLastInsertId();
                        $executionCount++;
                        $insertCount++;
                     else :
                        $outText .= getLngt("Die EID des folgenden Artikels konnte nicht generiert werden:") . " " . $f_at_name . "<br>";
                        $failedCount++;
                     endif;
                  endif;

                  // Update group information if a group has to be associated ($groupId != "") and the article does exist or has been inserted
                  if ($groupId != "" && $currAtId != "" && is_numeric($currAtId)) :
                     // Update group association
                     $groupsOfcurrArticle = getFieldValueFromId("phoenix.article", "at_id", $currAtId, "at_group");
                     if ($groupsOfcurrArticle == "") :
                        $res = updateStmt("phoenix.article", "at_id", $currAtId, array("at_group", "," . $groupId . ","));
                     elseif (strpos($groupsOfcurrArticle, "," . $groupId . ",") === false) :
                        $res = updateStmt("phoenix.article", "at_id", $currAtId, array("at_group", $groupsOfcurrArticle . $groupId . ","));
                     endif;
                  endif;

                  // Insert new prices if have been changed
                  if ($groupId != "" || $csId != "") :
                     // Check for $currAtId being set or not by modification or insertion of the article by itself
                     if ($currAtId == "") :
                        $currAtId = getFieldValueFromClause("phoenix.article","at_id","at_name = '" . $f_at_name . "' AND hq_id = '" . $hqId . "'");
                     endif;

                     // Insert article prices
                     if ($currAtId != "") : 
                        // Check standard price
                        $oldPrice = getFieldValueFromClause("articleprice","atp_price","at_id = '" . $currAtId . "' AND cs_id = '" . $csId . "' AND grp_id = '" . $groupId . "' AND mt_sort = ''");
                        if ($f_at_price != "" && is_numeric($f_at_price) && ($oldPrice == "" || $oldPrice != $f_at_price)) :
                           insertStmt("articleprice", array("at_id", $currAtId, "cs_id", $csId, "grp_id", $groupId, "mt_sort", "", "atp_price", $f_at_price, "atp_validfrom", $currentTime));  // Insert standard price
                        endif;
                        
                        // Iterate and check special prices
                        $f_at_prices_mt_sort_len = count($f_at_prices_mt_sort);
                        for ($k = 0; $k < $f_at_prices_mt_sort_len; $k++) :
                             if ($f_at_prices_mt_sort[$k] != "" && is_numeric($f_at_prices_mt_sort[$k])) :
                                $oldPrice = getFieldValueFromClause("articleprice","atp_price","at_id = '" . $currAtId . "' AND cs_id = '" . $csId . "' AND grp_id = '" . $groupId . "' AND mt_sort = '" . $k . "'");
                                if ($oldPrice == "" || $oldPrice != $f_at_prices_mt_sort[$k]) :
                                   insertStmt("articleprice", array("at_id", $currAtId, "cs_id", $csId, "grp_id", $groupId, "mt_sort", $k, "atp_price", $f_at_prices_mt_sort[$k], "atp_validfrom", $currentTime));  // Insert special prices
                                endif;
                             endif;
                        endfor;
                     endif;
                  endif;

                  // TA("C");
                  // TA("E");

                  // $closeWindow = "1";
               endif;
            else :
               $outText .= getLngt("Kein Artikel im Datensatz!") . "<br>";
            endif;


            // Reset all parameters corresponding with database fields fields! This is necessary because the imported fields can be a subset from all table fields defined for "article" in the database !!!!
            $f_at_name = "";
            $f_at_match = "";
            $f_at_description = "";
            $f_at_barcode = "";
            $f_atg_id = "";
            $f_at_bundlequantity = "";
            $f_at_bundlecode = "";
            $f_at_stk_itemquantity = "";
            $f_at_stk_areaquantity = "";
            $f_at_serialno = "";
            $f_at_totalweight = "";
            $f_at_no_packages = "";
            $f_at_price = "";
            $f_at_price2 = "";
            $f_at_price3 = "";
            $f_at_price4 = "";
            $f_at_price5 = "";
            $f_at_price6 = "";

            // Feedback for browser
            $m = $j;
            if ($executeImportProcess == "1") :
               if (($m % 100) == 0) :
                  echo "<br>";
                  echo round((($m / $dataLen) * 100), 2) . "%";
                  if ($showRawData) : echo "<br>"; endif;
                  ob_flush(); flush();
               endif;
            endif;
         }

         $outText .= getLngt("Einträge in der Importdatei: " . $dataLen . "<br>");
         $outText .= getLngt("Verarbeitete Einträge: " . $executionCount . "<br>");
         $outText .= getLngt("Neue Einträge: " . $insertCount . "<br>");
         $outText .= getLngt("Modifizierte Einträge: " . $updateCount . "<br>");
         $outText .= getLngt("INSERT oder UPDATE final nicht durchgeführt: " . $failedCount . "<br>");
      else :
         $statusMessage .= getLngt("Die angegebene Datei scheint nicht kompatibel zur angeforderten Importfunktionalität!");
      endif;
      
      // Deactivate buffering and flush data
      ob_end_flush();
   else :
      $statusMessage .= getLngt("Die angegebene Datei existiert nicht!");
   endif;
else :
   $statusMessage .= getLngt("Es wurde keine Datei spezifiziert!");
endif;
?>

<html>
<head>
<title><?php echo $pageTitel ?></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 type="text/javascript">
<!--
// NAVIGATION
<?php echo $jsMenuOut; ?>

function finishPageExecuteImportProcess(f_act) {  
  document.forms[0].f_act.value=f_act;
  document.forms[0].executeImportProcess.value = '1';
  document.forms[0].submit();
};

function onBodyLoad() {
	displayStatusMessage();
	var closeWindow = '<?php echo $closeWindow ?>';
	if (closeWindow == '1') {
     opener.document.forms[0].submit();
     window.close();
  };
};
-->
</script>

</head>

<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?>onBodyLoad();">

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

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

  <div>
    <form name="import_form" action="../import/import_ARTICLE.php" method="post">
      <input type="hidden" name="f_act" value="">
      <?php echo $phpCurrentNavigationInputHidden ?>
      <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">
      <input type="hidden" name="importFile" value="<?php echo $importFile; ?>">
      <input type="hidden" name="executeImportProcess" value="<?php echo $executeImportProcess; ?>">
      <input type="hidden" name="objType" value="<?php echo $objType; ?>">
      <input type="hidden" name="objId" value="<?php echo $objId; ?>">

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

      <?php
        if ($showExecutionProcessButton && $executeImportProcess != "1") :
           echo defineButtonType10(getLngt("Import starten"), "action_import", "finishPageExecuteImportProcess('executeImport');", "200");
           echo htmlDivLineSpacer("5px");
           echo defineButtonType10(getLngt("Schließen"), "action_close", "window.close();", "200");
           echo htmlDivLineSpacer("5px");
        endif;
      ?>

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

      <div>
        <table border="1" margin="10" padding="10">
        	<tr>
        		<td style="vertical-align:top;">
              <?php echo $outText; ?>
            </td>
          </tr>
        </table>    
      </div>
    </form>
  </div>

</div>

</body>

</html>