<?php
  function cherche_no_article_chaine($NoArticle)
  {
    $resultat = Article::getArticleChainByNoArticle($NoArticle);
    if (count($resultat) > 0)
    {
      $ligne = $resultat[0];
      return cherche_no_article_chaine($ligne['NoArticle']);
    }
    else
    {
      return $NoArticle;
    }
  }
  echo "<big>Commande stock</big><br>\n";
  switch($Etape)
  {
    case 0:
      echo "<form name='info'>\n";
      echo "<input type='hidden' name='Type' value=$Type>";
      echo "<input type='hidden' name='Sous_Type' value=$Sous_Type>";
      echo "<input type='hidden' name='Etape' value='1'>\n";
      echo "Fournisseur <select name='Fournisseur'>\n";
      $resultat = Fournisseur::getFournisseur();
      foreach($resultat as $ligne)
      {
        echo "<option value='".$ligne["Id"]."'>".$ligne["Description"]."</option>\n";
      }
      echo "</select>\n";
      echo "<input type='submit' value='Selection'>\n";
      echo "</form>\n";
      unset($_SESSION['commande']);
    break;
    case 1:
      if (isset($_REQUEST['Fournisseur']))
      {
        $_SESSION['commande'] = array('fournisseur' => $_REQUEST['Fournisseur'], 'memoire' => array());
      }
      echo "<form name='info'>\n";
      echo "<input type='hidden' name='Type' value=$Type>";
      echo "<input type='hidden' name='Sous_Type' value=$Sous_Type>";
      echo "<input type='hidden' name='Etape' value='2'>\n";
      echo "<table>\n";
      echo "<tr><td>Lieux stoquage</td><td><select name='LieuxStoquage'>\n";
      echo "<option value='0'>-</option>\n";
      $resultat = LieuxStockage::getLieuxStockage();
      foreach ($resultat as $ligne)
      {
        echo "<option value='".$ligne["Id"]."'>".$ligne["Description"]."</option>\n";
      }
      echo "</select></td></tr>\n";
      echo "<tr><td>Groupe marchandise</td><td><select name='GroupeMarchandise'>\n";
      echo "<option value='0'>-</option>\n";
      $resultat = GroupeMarchandise::getGroupeMarchandiseByFournisseur($_SESSION['commande']['fournisseur']);
      foreach ($resultat as $ligne )
      {
        echo "<option value='".$ligne["No"]."'>(".$ligne["No"].") ".$ligne["Description"]."</option>\n";
      }
      echo "</select></td></tr>\n";
      echo $requette;
      echo "<tr><td>Durée comptage</td><td><select name='DureeComptage'>\n";
      echo "<option value='1'>1</option>\n";
      echo "<option value='3'>3</option>\n";
      echo "<option value='6'>6</option>\n";
      echo "<option selected='selected' value='12'>12</option>\n";
      echo "<option value='24'>24</option>\n";
      echo "</select></td></tr>\n";
      echo "<tr><td>Durée stoquage</td><td><select name='DureeStoquage'>\n";
      echo "<option value='1'>1</option>\n";
      echo "<option value='2'>2</option>\n";
      echo "<option selected='selected' value='3'>3</option>\n";
      echo "<option value='6'>6</option>\n";
      echo "<option value='12'>12</option>\n";
      echo "</select></td></tr>\n";
      echo "<tr><td>No article</td><td><input type='text' name='NoArticle' />";
      echo "</td></tr></table>\n";
      echo "<input type='submit' value='Selection'>\n";
      echo "</form>\n";
      echo "<form name='valid'>\n";
      echo "<input type='hidden' name='Type' value=$Type>";
      echo "<input type='hidden' name='Sous_Type' value=$Sous_Type>";
      echo "<input type='hidden' name='Etape' value='4'>\n";
      echo "<input type='submit' value='Passer la commande'>\n";
      echo "</form>\n";
      break;
    case 2:
      echo "<form name='info'>\n";
      echo "<input type='hidden' name='Type' value=$Type>";
      echo "<input type='hidden' name='Sous_Type' value=$Sous_Type>";
      echo "<input type='hidden' name='Etape' value='3'>\n";
      if ($_REQUEST['LieuxStoquage'] != "0")
      {
        $requette = "SELECT ca.NoArticle, ca.Quantite, c.Genre FROM commande".ID_GARAGE." c, commandearticles".ID_GARAGE." ca, articles a, articlesfournisseurs af, stock".ID_GARAGE." s WHERE c.DateCommande >= DATE_SUB(CURDATE(),INTERVAL ".$_REQUEST['DureeComptage']." MONTH) AND c.Type IN ('FD', 'FV', 'FO', 'GF', 'GG', 'FL', 'BP', 'FI', 'ND', 'NB', 'NV', 'NO', 'NL') AND c.NoCommande = ca.NoCommande AND ca.NoArticle = a.NoArticle AND a.NoArticleRR = af.NoArticleRR AND af.IdFournisseur = ".$_SESSION['commande']['fournisseur'];
        $requette .= " AND a.NoArticleRR = s.NoArticleRR AND s.LieuxStock = '".$_REQUEST['LieuxStoquage']."'";
      }
	  else
	  {
        $requette = "SELECT ca.NoArticle, ca.Quantite, c.Genre FROM commande".ID_GARAGE." c, commandearticles".ID_GARAGE." ca, articles a, articlesfournisseurs af WHERE c.DateCommande >= DATE_SUB(CURDATE(),INTERVAL ".$_REQUEST['DureeComptage']." MONTH) AND c.Type IN ('FD', 'FV', 'FO', 'GF', 'GG', 'FL', 'BP', 'FI', 'ND', 'NB', 'NV', 'NO', 'NL') AND c.NoCommande = ca.NoCommande AND ca.NoArticle = a.NoArticle AND a.NoArticleRR = af.NoArticleRR AND af.IdFournisseur = ".$_SESSION['commande']['fournisseur'];
	  }	
      if ($_REQUEST['GroupeMarchandise'] != 0)
      {
        $requette .= " AND a.GroupeMarchandise = ".$_REQUEST['GroupeMarchandise'];
      }
	  if ($_REQUEST['NoArticle']!="")
	  {
	    $requette .= " AND a.NoArticle LIKE ".Connection::getConnection()->quote($_REQUEST['NoArticle']);
	  }
      echo $requette;
      $ventes = array();
      $resultat = Connection::executeRawQueryWithfetchAll($requette);
      //echo "<table><tr><th>NoArticle</th><th>Quantité</th><th>Genre</th></tr>";
      foreach ($resultat as $ligne)
      {
        if (array_key_exists($ligne['NoArticle'], $ventes))
        {
          if ($ligne['Genre'] == 'N')
          {
            $ventes[$ligne['NoArticle']] -= $ligne['Quantite'];
          }
          else
          {
            $ventes[$ligne['NoArticle']] += $ligne['Quantite'];
          }
        }
        else
        {
          if ($ligne['Genre'] == 'N')
          {
            $ventes[$ligne['NoArticle']] = -$ligne['Quantite'];
          }
          else
          {
            $ventes[$ligne['NoArticle']] = $ligne['Quantite'];
          }
        }
        //echo "<tr><td>".$ligne['NoArticle']."</td><td>".$ligne['Quantite']."</td><td>".$ligne['Genre']."</td></tr>";
      }
      //echo "</table>";
      $anciens = array();
      $ventes2 = array();
      //echo "<table><tr><th>NoArticle</th><th>Quantité</th><th>Stock</th><th>Transfert</th></tr>";
      foreach ($ventes as $article => $quantite)
      {
        $NoArticleChaine = cherche_no_article_chaine($article);
        $resultat = Article::getArticleStockByNoArticle($article);
        if ($ligne = $resultat[0])
        {
          if ($NoArticleChaine != $article && $ligne['EnStock'] != 0)
          {
            $anciens[$article] = array('Stock' => $ligne['EnStock'] + $ligne['EnTransfert'], 'Nouveau' => $NoArticleChaine);
          }
          if (array_key_exists($NoArticleChaine, $ventes2))
          {
            //echo "<tr><td>???</td><td>???</td><td>???</td><td>$article</td></tr>";
            $ventes2[$NoArticleChaine]['Quantite'] += $quantite;
            $ventes2[$NoArticleChaine]['Stock'] += $ligne['EnStock'] + $ligne['EnTransfert'];
            $ventes2[$NoArticleChaine]['Packages'] = $ligne['Packages']; 
          }
          else
          {
            $ventes2[$NoArticleChaine] = array('Quantite' => $quantite, 'Stock' => ($ligne['EnStock'] + $ligne['EnTransfert']), 'Packages' => $ligne['Packages']);
          }
          //echo "<tr><td>$article</td><td>$quantite</td><td>".$ligne["EnStock"]."</td><td>".$ligne["EnTransfert"]."</td></tr>";
        }
      }
      //echo "</table>";
      echo "<table border='1'><tr><th>NoArticle</th><th>Besoin</th><th>Stock</th><th>Proposition</th><th>&nbsp;</th><th>Packages</th></tr>";
      $pos = 0;
      foreach ($ventes2 as $article => $data)
      {
        $besoin = round($_REQUEST['DureeStoquage'] / $_REQUEST['DureeComptage'] * $data['Quantite']);
        $proposition = 0;
        if ($besoin > $data['Stock'])
        {
          if (!array_key_exists($article, $_SESSION['commande']['memoire']))
          {
            $proposition = $besoin - $data['Stock'];
            echo "<tr><td><input type='hidden' name='art$pos' value='$article'>$article</td><td>$besoin</td><td>".$data['Stock']."</td><td><input type='text' name='quantite$pos' value='$proposition'></td><td><input name='select$pos' value='1' type='checkbox' checked='checked' /></td><td>".$data['Packages']."&nbsp;</td></tr>";
            $pos++;
          }
        }
      }
      echo "</table>";
      echo "<input type='hidden' name='nb_articles' value='$pos'>";
      //echo "<table border='1'><tr><th>NoArticle</th><th>Quantite</th><th>Nouveau NoArticle</th><th>Quantite totale</th></tr>";
      foreach ($anciens as $article => $data)
      {
        //echo "<tr><td>$article</td><td>".$data['Stock']."</td><td>".$data['Nouveau']."</td><td>".$ventes2[$data['Nouveau']]['Stock']."</td></tr>";
      }
      //echo "</table>";
      echo "<input type='submit' value='Selection'>\n";
      echo "</form>\n";
    break;
    case 3:
      for ($cpt = 0; $cpt < $_REQUEST['nb_articles']; $cpt++)
      {
        if (isset($_REQUEST["select$cpt"]))
        {
          $_SESSION['commande']['memoire'][$_REQUEST["art$cpt"]] = $_REQUEST["quantite$cpt"];
        }
      }
      echo "<pre>";
      print_r($_SESSION['commande']['memoire']);
      echo "</pre>";
      header("Location: ?Etape=1&Type=$Type&Sous_Type=$Sous_Type");
    break;
    case 4:
      echo "<form name='info'>\n";
      echo "<input type='hidden' name='Type' value=$Type>";
      echo "<input type='hidden' name='Sous_Type' value=$Sous_Type>";
      echo "<input type='hidden' name='Etape' value='5'>\n";
      echo "<table border='1'><tr><th>Quantite</th><th>Article</th></tr>";
      foreach ($_SESSION['commande']['memoire'] as $article => $quantite)
      {
      	echo "<tr><td>$quantite</td><td>$article</td></tr>";
      }
      echo "</table>";
      echo "<input type='text' name='destinataire' value='crazy'>";
      echo "<input type='submit' value='Passer la commande'>\n";
      echo "</form>\n";
    break;
    case 5:
      $NoCommande=Trouve_No_Commande_Libre("CP");
      if(isset($NoClient)) {
          $NoClient = "'".$NoClient."'";
      } else {
          $NoClient = 'NULL';
      }
      if(isset($NoClient2)) {
          $NoClient2 = "'".$NoClient2."'";
      } else {
          $NoClient2 = 'NULL';
      }
      if(isset($Vendeur)) {
          $Vendeur = "'".$Vendeur."'";
      } else {
          $Vendeur = 'NULL';
      }
      if(isset($Km)) {
          $Km = "'".$Km."'";
      } else {
          $Km = 'NULL';
      }
      $requette="INSERT INTO commande".ID_GARAGE." (NoCommande, Titre, NoFourniseur, IPClient, Type,Genre,PersonneModif,NoClient,NoClient2,Vendeur,Vehicule,KmVhc,NoPlaque,DateCommande,DateSaisie,DateModification,DateDelaisPayement, Recu) VALUES " .
                  "($NoCommande, '', '', '', 'CP', 'C', '$lg_user', $NoClient, $NoClient2, $Vendeur,'" . addslashes($NoChasis) . "', $Km, '$NoPlaque', '" . date("Y-m-d") . "', '" . date("Y-m-d") . "', '" . date("Y-m-d") . "', '".date("Y-m-d",mktime(0,0,0,date("m"),date("d")+30,date("Y")))."', 'N')";
	    echo $requette."<br/>";
      Connection::executeRawQuery($requette);
      $pos = 1;
      $total = 0;
      foreach ($_SESSION['commande']['memoire'] as $article => $quantite)
      {
	    $requette="SELECT * FROM articles WHERE NoArticle = '$article'";
      echo $requette."<br/>";
		if ($ligne=Article::getArticleByNoArticle($article))
		{
		  $noArticleRR = Texte_Sans_Espace($article);
		  $resultat_existe_stock = Stock::getStockByNoArticleRR(addslashes($noArticleRR));
		  if ($resultat_existe_stock)
		  { // UPDATE
            $requette="UPDATE stock".ID_GARAGE." SET EnTransfert = EnTransfert + $quantite WHERE NoArticleRR='".addslashes($noArticleRR)."'";
		  }
		  else
		  { // INSERT
			$requette="INSERT INTO stock".ID_GARAGE." (`NoArticleRR` ,`LieuxStock` ,`EnStock` ,`EnTransfert`) VALUES ('".addslashes($noArticleRR)."', NULL , 0, $quantite);";
		  }
		  //$requette = "UPDATE stock".ID_GARAGE." SET EnTransfert = EnTransfert + $quantite WHERE NoArticle = '$article'";
		  Connection::executeRawQuery($requette);
	      $prix_multi = $quantite * $ligne["PrixImportateur"] * ((100 - $ligne['Rabais'])/100);
          if ($ligne["TVA"]>0)
	      {
            $prix_multi = $prix_multi * ((100 + $ligne["TVA"])/100);
          }
          $prix_multi = Arrondi_1_ct($prix_multi);
		  $total+=$prix_multi;
	      $requette="INSERT INTO commandearticles".ID_GARAGE." (NoCommande, Position, TypeData, NoArticle, Description, TVA, GM, Quantite, PrixBase, Rabais, PrixMulti, NbRecu, DateRecu, Dest) VALUES ";
		  $requette.="($NoCommande, $pos, 0, '$article', '".Connection::getConnection()->quote($ligne["Description"])."', ".$ligne["TVA"].", ".$ligne["GroupeMarchandise"].", $quantite, ".$ligne["PrixImportateur"].", -".$ligne['Rabais'].", $prix_multi, 0, '', '".Connection::getConnection()->quote($_REQUEST["destinataire"])."')"; 
      Connection::executeRawQuery($requette);
		  //echo Connection::getConnection()->errorInfo();
          echo $requette."<br/>";
		  $pos++;
		}
	  }
      $total = Arrondi_5_ct($total);
      $requette = "UPDATE commande".ID_GARAGE." SET MontantTotal=$total, APayer=$total WHERE NoCommande=$NoCommande";
      Connection::executeRawQuery($requette);
	  echo $requette."<br/>";
	  header("Location: ?Type=4&Sous_Type=1&Etape=2&NoCommande=$NoCommande&NoClient=0&NoClient2=0");
    break;
    
  }  
?>