<?php
/*=======================================================================
 *
 * import_ARTICLEGROUP.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 ARTIKELGRUPPE");
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;

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 ($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");


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

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

         $rowToImport = array();

         $parImportArticleFieldsGroup == "";
         if ($groupId != "") :
            $parImportArticleFieldsGroup = getParameterValue("0", "IMPORT_ARTICLEGROUP_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_atg_key";         // Articlegroup key/no.
            $rowToImport[1]  = "f_atg_name";        // Articlegroup name
            $rowToImport[2]  = "f_atg_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];
            }

            $f_atg_key = removeFieldSigns($f_atg_key);
            $f_atg_name = removeFieldSigns($f_atg_name);
            $f_hq_id = "0";

            if ($f_atg_key != "") :

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

                  // TA("B");

                  $currAtgId = "";
                  if (existsEntry("articlegroup",array("atg_key",$f_atg_key))) :

                     // Update articlegroup
                     $res = updateStmt("phoenix.articlegroup", "atg_key", $f_atg_key, array("atg_name", $f_atg_name));

                     // Check update for success
                     if ($db->affected_rows > 0) :
                        $executionCount++;
                        $updateCount++;
                        $currAtgId = getFieldValueFromId("phoenix.articlegroup", "atg_key", $f_atg_key, "atg_id");
                        $outText .= getLngt("Update der Artikelgruppe:") . " " . $f_atg_key . " - " . $f_atg_name . "<br>";
                     else :
                        $failedCount++;
                     endif;
                  else :

                     // Insert article
                     if ($f_atg_name != "") :
                        insertStmt("phoenix.articlegroup", array("atg_key", $f_atg_key, "atg_name", $f_atg_name));
                        $currAtgId = getLastInsertId();
                        $executionCount++;
                        $insertCount++;
                     else :
                        $outText .= getLngt("Die Artikelgruppe hat zwar einen Schlüssel, aber keinen Namen:") . " " . $f_atg_key . "<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 != "" && $currAtgId != "" && is_numeric($currAtgId)) :
                     // Update group association
                     $groupsOfcurrArticle = getFieldValueFromId("phoenix.articlegroup", "atg_id", $currAtgId, "atg_group");
                     if ($groupsOfcurrArticle == "") :
                        $res = updateStmt("phoenix.articlegroup", "atg_id", $currAtgId, array("atg_group", "," . $groupId . ","));
                     elseif (strpos($groupsOfcurrArticle, "," . $groupId . ",") === false) :
                        $res = updateStmt("phoenix.articlegroup", "atg_id", $currAtgId, array("atg_group", $groupsOfcurrArticle . $groupId . ","));
                     endif;
                  endif;

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

                  // $closeWindow = "1";
               endif;
            else :
               $outText .= getLngt("Keine Artikelgruppe im Datensatz!") . "<br>";
            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;
   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_ARTICLEGROUP.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>