<?php
  function startsWith($haystack, $needle) {
    // search backwards starting from haystack length characters from the end
    return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false;
  }
  switch($Etape)
  {
    case 0:
      echo "<form method='POST' ENCTYPE='multipart/form-data'><input type='hidden' name='Type' value=$Type><input type='hidden' name='Sous_Type' value=$Sous_Type><input type='hidden' name='Etape' value=1>";
	  echo "Enregistrer dans excel \"fichier texte séparateur tabulation\" ";
/*      echo "<table border=1>";
      echo "<tr><th>Groupe</th><th>rabais</th></tr>";
      echo "<tr><th>A</th><td><input name=RA value='25'></td></tr>";
      echo "<tr><th>B</th><td><input name=RB value='35'></td></tr>";
      echo "<tr><th>C</th><td><input name=RC value='45'></td></tr>";
      echo "<tr><th>D</th><td><input name=RD value='10'></td></tr>";
      echo "<tr><th>E</th><td><input name=RE value='50'></td></tr>";
      echo "<tr><th>H</th><td><input name=RH value='30'></td></tr>";
      echo "<tr><th>I</th><td><input name=RI value='35'></td></tr>";
      echo "<tr><th>L</th><td><input name=RL value='20'></td></tr>";
      echo "<tr><th>R</th><td><input name=RR value='45'></td></tr>";
      echo "<tr><th>S</th><td><input name=RS value='60'></td></tr>";
      echo "<tr><th>M</th><td><input name=RM value='15'></td></tr>";
      echo "<tr><th>N</th><td><input name=RN value='35'></td></tr>";
      echo "<tr><th>P</th><td><input name=RP value='40'></td></tr>";
      echo "<tr><th>Q</th><td><input name=RQ value='35'></td></tr>";
      echo "<tr><th>X</th><td><input name=RX value='30'></td></tr>";
      echo "<tr><th>Y</th><td><input name=RY value='25'></td></tr>";
      echo "</table>";*/
      echo "<INPUT TYPE='file' name='liste'><button type='submit'>Importer</button></form>\n";
    break;
    case 1:
      set_time_limit ( 3600 );
      $file=fopen($liste["tmp_name"],'r');
      //echo "salut ".print_r($liste)."<BR>";
      //echo "<BIG>Veuillez patienter svp</BIG><BR>";
      $nbart=0;
      $nbinc=0;
      $poscpt=0;
	  $ligne=mb_convert_encoding(fgets($file,300), "UTF-8");
	  //$test = "Materiel\tInspection text (Description materiel)\tEtat par cat. de distrib.\tQuantite minimum splitting (Quantite emballage)\tEnsemble materiaux (Classe de reduction)\tHierarchie produits\tMateriel (De substitution)\tMontant condition (Prix au public taxes exclues)\tValeur condition\r\n";
	  $test = "Art.Nr.:\tBezeichnung:\tVP exkl. MWST\tVP inkl. MWST\tRC\tWGR\r\n";
	  //echo $ligne."<br>\n";
	  //echo $test."<br>\n";;
	  //echo "".strlen($ligne)."-".strlen($test);
	  if ($ligne == $test)
	  {
      while($ligne=fgets($file,300))
      {
	    $ligne=mb_convert_encoding($ligne, "UTF-8");
	    $arrLigne = explode("\t", $ligne);
        $poscpt++;
        if(($poscpt%10000)==0)
        {
          //echo "en cours<BR>\n";
        }
        $NoArticle=$arrLigne[0];
        $NoArticleRR=str_replace(" ", "", $NoArticle);
        $NoArticleRR=str_replace("-", "", $NoArticleRR);
        //$EditCode=substr($ligne,15,1);
		if (startsWith($arrLigne[1], "= "))
		{
		  $Description=substr($arrLigne[1],5);
          $Description=str_replace(" ", "", $Description);
          $Description=str_replace("-", "", $Description);
		}
		else
		{
		  $Description=$arrLigne[1];
		}
		//echo $PrixHT."<br/>";
        $Tax=Config::getTVA();
        $PrixTTC=substr($arrLigne[3],4);
		$PrixTTC=ceil($PrixTTC);
		//echo $PrixTTC."<br/>";
        $CodeRabais=$arrLigne[4];
        $Rabais=0;
        $GroupeMarchandise=$arrLigne[5];
		$GroupeMarchandise=str_replace("Z1", "31", $GroupeMarchandise);
		$GroupeMarchandise=str_replace("Z0", "32", $GroupeMarchandise);
/*		$GroupeMarchandise=str_replace("R", "", $GroupeMarchandise);
        switch ($CodeRabais)
        {
          case "A":
            $Rabais=$RA;
          break;
          case "B":
            $Rabais=$RB;
          break;
          case "C":
            $Rabais=$RC;
          break;
          case "D":
            $Rabais=$RD;
          break;
          case "E":
            $Rabais=$RE;
          break;
          case "H":
            $Rabais=$RH;
          break;
          case "I":
            $Rabais=$RI;
          break;
          case "L":
            $Rabais=$RL;
          break;
          case "R":
            $Rabais=$RR;
          break;
          case "S":
            $Rabais=$RS;
          break;
          case "M":
            $Rabais=$RM;
          break;
          case "N":
            $Rabais=$RN;
          break;
          case "P":
            $Rabais=$RP;
          break;
          case "Q":
            $Rabais=$RQ;
          break;
          case "X":
            $Rabais=$RX;
          break;
          case "Y":
            $Rabais=$RY;
          break;
        }*/
        //$QuantiteOpt=$arrLigne[3];
        $resultat=Article::getArticleByNoArticleRR(addslashes($NoArticleRR));
        $nb_resultats=count($resultat);
        $requette2="";
        if ($nb_resultats==0)
        {
          $requette2="INSERT INTO articles (NoArticle, NoArticleRR, Description, Type, PrixImportateur, Rabais, CodeRabais, GroupeMarchandise, TVA, DateModif, QuantiteMinimum, DateSaisie, PersonneModif) VALUES ";
          $requette2.="(".
                      "'".addslashes($NoArticle)."'".
                      ", '".addslashes($NoArticleRR)."'".
                      ", '".addslashes($Description)."'".
                      ", 'KAWASAKI'".
                      ", $PrixTTC".
                      ", $Rabais".
                      ", '".addslashes($CodeRabais)."'".
                      ", $GroupeMarchandise".
                      ", -$Tax".
                      ", '".date("Y-m-d")."'".
                      ", 1".
                      ", '".date("Y-m-d")."'".
                      ", 'import'".
                      ")";
          $requette3="INSERT INTO articlesfournisseurs (NoArticleRR, IdFournisseur) VALUES ('".addslashes($NoArticleRR)."', 1)";
        }
        else if ($nb_resultats==1)
        {
          $requette2="UPDATE articles SET ".
                     "NoArticle='".addslashes($NoArticle)."'".
               ", Description='".addslashes($Description)."'".
               ", Type='KAWASAKI'".
               ", PrixImportateur=$PrixTTC".
               ", Rabais=$Rabais".
               ", CodeRabais='".addslashes($CodeRabais)."'".
               ", GroupeMarchandise=$GroupeMarchandise".
               ", TVA=-$Tax".
               ", DateModif='".date("Y-m-d")."'".
               ", QuantiteMinimum=1".
               ", PersonneModif='import'".
               " WHERE NoArticleRR='".addslashes($NoArticleRR)."'";
          $requette3="INSERT INTO articlesfournisseurs (NoArticleRR, IdFournisseur) VALUES ('".addslashes($NoArticleRR)."', 1)";
        }
        else
        {
          $create=1;
          foreach($resultat as $ligner)
          {
            if($ligner['NoArticle']==$NoArticle)
            {
              $create=0;
            }
            else
            {
              Connection::executeRawQuery("DELETE FROM articles WHERE NoArticle='".addslashes($NoArticle)."'");
            }
          }
          if($create==1)
          {
          $requette2="INSERT INTO articles (NoArticle, NoArticleRR, Description, Type, PrixImportateur, Rabais, CodeRabais, GroupeMarchandise, TVA, DateModif, QuantiteMinimum, DateSaisie, PersonneModif) VALUES ";
          $requette2.="(".
                      "'".addslashes($NoArticle)."'".
                      ", '".addslashes($NoArticleRR)."'".
                      ", '".addslashes($Description)."'".
                      ", 'KAWASAKI'".
                      ", $PrixTTC".
                      ", $Rabais".
                      ", '".addslashes($CodeRabais)."'".
                      ", $GroupeMarchandise".
                      ", -$Tax".
                      ", '".date("Y-m-d")."'".
                      ", 1".
                      ", '".date("Y-m-d")."'".
                      ", 'import'".
                      ")";
          }
          else
          {
            $requette2="UPDATE articles SET ".
                       "NoArticle='".addslashes($NoArticle)."'".
                 ", Description='".addslashes($Description)."'".
                 ", Type='KAWASAKI'".
                 ", PrixImportateur=$PrixHT".
                 ", Rabais=$Rabais".
                 ", CodeRabais='".addslashes($CodeRabais)."'".
                 ", GroupeMarchandise=$GroupeMarchandise".
                 ", TVA=$Tax".
                 ", DateModif='".date("Y-m-d")."'".
                 ", QuantiteMinimum=1".
                 ", PersonneModif='import'".
                 " WHERE NoArticleRR='".addslashes($NoArticleRR)."'";
          }
        }
		if($GroupeMarchandise==0)
		{
		  $nbinc++;
		  echo $ligne."<br/>\n";
		  echo $requette2."<br/>\n";
		}
		else
		{
		  $nbart++;
		  Connection::executeRawQuery($requette2);
		  Connection::executeRawQuery($requette3);
		}
      }
      echo $nbart . " articles<BR>";
      echo $nbinc . " erreurs<BR>";
      echo "<BIG>OK c'est fini</BIG><BR>";
	  }
	  else
	  {
	    echo "Fichier mal formaté";
	  }
    break;
  }
?>
