<?php
function Trouve_No_Commande_Libre($type)
{
  $requette = "SELECT * FROM config" . ID_GARAGE . " WHERE champ='LAST_$type'";
  $statement = Connection::getStatement($requette);
  $statement->execute();
  if ($ligne = $statement->fetch()) {
    $last = $ligne['valeur'];
    if ($last > 0) {
      $last++;
      $requette = "UPDATE config" . ID_GARAGE . " SET valeur='$last' WHERE champ='LAST_$type'";
      $statement = Connection::getStatement($requette);
      $statement->execute();
      return $last;
    }
  }
  $requette = "SELECT * FROM config" . ID_GARAGE . " WHERE champ=:type";
  $statement = Connection::getStatement($requette);
  $statement->bindParam(":type", $type);
  $statement->execute();
  if ($ligne = $statement->fetch()) {
    $start = $ligne['valeur'];
    $requette2 = "SELECT NoCommande FROM commande" . ID_GARAGE . " WHERE NoCommande=:start";
    $statement = Connection::getStatement($requette2);
    $statement->bindParam(":start", $start);
    $statement->execute();
    while ($statement->fetch()) {
      $start++;
    }
    $requette = "UPDATE config" . ID_GARAGE . " SET valeur='$start' WHERE champ='LAST_$type'";
    $statement = Connection::getStatement($requette);
    $statement->execute();
    return $start;
  }
  return 0;
}

function Select_Etape_Facture($no_commande, $no_client, $no_client2, $mode = 255)
{
  // Mode 1       Nom + vhc
  // Mode 2       Facture
  // Mode 4       Impression
  // Mode 8       Encaissement
  // Mode 16      reserve
  global $Type, $Sous_Type, $Etape;
  echo "<table class='table_etape_facture'><tr>\n";
  if ($mode & 1) {
    echo "<td class='td_coordonnees";
    if ($Etape == 2) {
      echo " bt_actif";
    }
    echo "'><form><input type='hidden' name='Type' value=$Type><input type='hidden' name='Sous_Type' value=$Sous_Type><input type='hidden' name='Etape' value=2><input type='hidden' name='NoCommande' value=$no_commande><input type='hidden' name='NoClient' value=$no_client><input type='hidden' name='NoClient2' value=$no_client2><input type='button' class='button' onClick='test_change(this.form);' value='Coordonnées' /></form></td>\n";
  }
  if ($mode & 2) {
    echo "<td class='td_facture";
    if ($Etape == 3) {
      echo " bt_actif";
    }
    echo "'><form><input type='hidden' name='Type' value=$Type><input type='hidden' name='Sous_Type' value=$Sous_Type><input type='hidden' name='Etape' value=3><input type='hidden' name='NoCommande' value=$no_commande><input type='hidden' name='NoClient' value=$no_client><input type='hidden' name='NoClient2' value=$no_client2><input type='button' class='button facture' onClick='test_change(this.form);' value='Facture' /></form></td>\n";
  }
  if ($mode & 4) {
    echo "<td class='td_imprimer";
    if ($Etape == 4) {
      echo " bt_actif";
    }
    echo "'><form><input type='hidden' name='Type' value=$Type><input type='hidden' name='Sous_Type' value=$Sous_Type><input type='hidden' name='Etape' value=4><input type='hidden' name='NoCommande' value=$no_commande><input type='hidden' name='NoClient' value=$no_client><input type='hidden' name='NoClient2' value=$no_client2><input type='button' class='button imprimer' onClick='test_change(this.form);' value='Imprimer' /></form></td>\n";
  }
  if ($mode & 8) {
    echo "<td class='td_encaissement";
    if ($Etape == 5) {
      echo " bt_actif";
    }
    echo "'><form><input type='hidden' name='Type' value=$Type><input type='hidden' name='Sous_Type' value=$Sous_Type><input type='hidden' name='Etape' value=5><input type='hidden' name='NoCommande' value=$no_commande><input type='hidden' name='NoClient' value=$no_client><input type='hidden' name='NoClient2' value=$no_client2><input type='button' class='button encaissement' onClick='test_change(this.form);' value='Encaissement' /></form></td>\n";
  }
  echo "</tr></table>\n";
  if ($no_commande != 0) {
    $Version = Commande::getVersionByNoCommande($no_commande);
    // TODO check where REMOTE_ADDR should have been defined
    $requette1 = "UPDATE commande" . ID_GARAGE . " SET IPClient='" . $_SERVER["REMOTE_ADDR"] . "' WHERE NoCommande=$no_commande";
    $statement = Connection::getStatement($requette1);
    $statement->execute();

?>
    <script type="text/javascript" charset="utf-8">
      var commande_version = "<?php echo $Version; ?>";
      var my_ip = "<?php echo $_SERVER["REMOTE_ADDR"]; ?>";
      var version_error = 0;
      //alert("<?php echo $Version; ?>");
      setInterval("checkServerVersion()", 3000);
      //setTimeout ( "checkServerVersion()", 2000 );
      function checkServerVersion() {
        //alert("checkServerVersion");
        if (version_error != 2) {
          var js_reponse = commande_ajax("check_version.php?no_commande=<?php echo $no_commande; ?>");
          var array_reponse = js_reponse.split(';');
          if (array_reponse.length == 3) {
            actual_version = array_reponse[0];
            if (commande_version != actual_version) {
              //alert(commande_version.charCodeAt(0));
              //alert(actual_version.charCodeAt(0));
              //alert("Version changée");
              document.getElementById("version_err").innerHTML = "Version changée depuis " + array_reponse[2] + ", impossible de sauver les changements " + commande_version + (typeof commande_version) + "-" + actual_version + (typeof actual_version);
              document.getElementById("version_err").style.display = "block";
              version_error = 2;
            } else if (my_ip != array_reponse[1]) {
              if (version_error != 1) {
                //alert("Autre personne sur la commande");
                document.getElementById("version_err").innerHTML = "Autre personne sur la commande sur le poste " + array_reponse[2];
                document.getElementById("version_err").style.display = "block";
                version_error = 1;
              }
            } else {
              if (version_error == 1) {
                document.getElementById("version_err").innerHTML = "";
                document.getElementById("version_err").style.display = "none";
                version_error = 0;
              }
              //alert("OK");
            }
          }
        }
      }
    </script>
    <div id="version_err" style="display:none;font-size:20px;color:red;background-color:yellow;width:100%;text-align:center;font-weight:bold;padding: 5px 0px;margin: 5px 0px;"></div>
<?php
  }
}

function Create_Client_Vehicule_Facture($New, $Mode, $NoCommande = 0, $sous_mode = 255)
{
  global $Type, $Sous_Type;
  if ($New == 1) {
    echo "<form name='info'>\n";
    echo "<input type='hidden' name='Type' value='$Type'>\n";
    echo "<input type='hidden' name='Sous_Type' value='$Sous_Type'>\n";
    echo "<input type='hidden' name='Etape' value='3'>\n";
    echo "<input type='hidden' name='Modif' value='1'>\n";
    echo "<input type='hidden' name='New' value='1'>\n";
    echo "<input type='hidden' name='NewType' value='" . $GLOBALS['NewType'] . "'>\n";
    if ($Mode & 1) {
      if ($Mode & 2) {
        $tmp = 4;
      } else {
        $tmp = 3;
      }
      echo "<BIG>Client</BIG><BR>\n";
      echo "<TABLE border=1>\n";
      echo "<TR><TH>Numéro client</TH><TD><input type='texte' name='NoClient' value='' onchange='trouve_nom(0);'></TD></TR>\n";
      echo "<TR><TH>Nom</TH><TD><input type='texte' name='Nom' value='' onkeydown='test_return_client($tmp);'></TD></TR>\n";
      echo "<script language=JavaScript>\n";
      echo "this.document.forms['info'].elements['Nom'].focus();\n";
      echo "</script>\n";
      echo "<TR><TH>Prénom</TH><TD><input type='texte' name='Prenom' value='' onkeydown='test_return_client($tmp);'></TD></TR>\n";
      echo "</TABLE>\n";
      echo "<input type='button' value='Recherche' onclick='recherche_client_ajax(";
      if ($Mode & 2) {
        echo "4";
      } else {
        echo "3";
      }
      echo ");'><input type='button' value='Effacer' onclick='efface_client(1);'><BR><BR>\n";
    } else {
      echo "<input type='hidden' name='NoClient' value=''>\n";
      echo "<input type='hidden' name='Nom' value=''>\n";
      echo "<input type='hidden' name='Prenom' value=''>\n";
    }
    if ($Mode & 2) {
      echo "<BIG>Vehicule</BIG><BR>\n";
      echo "<TABLE border=1>\n";
      echo "<TR><TH>Numéro Chasis</TH><TD><input type='texte' name='NoChasis' value='' readonly></TD></TR>\n";
      echo "<TR><TH>Marque</TH><TD><input type='texte' name='Marque' value='' readonly></TD></TR>\n";
      echo "<TR><TH>Model</TH><TD><input type='texte' name='Model' value='' readonly></TD></TR>\n";
      echo "<TR><TH>Km</TH><TD><input type='texte' name='Km' value=''></TD></TR>\n";
      echo "<TR><TH>Numéro de plaques</TH><TD><input type='texte' name='NoPlaque' value=''></TD></TR>\n";
      echo "</TABLE>\n";
      echo "<input type='button' value='Recherche' onclick='recherche_vhc_ajax(1,1);'><input type='button' value='Effacer' onclick='efface_vhc();'><BR><BR>\n";
    } else {
      echo "<input type='hidden' name='NoChasis' value=''>\n";
      echo "<input type='hidden' name='Marque' value=''>\n";
      echo "<input type='hidden' name='Model' value=''>\n";
      echo "<input type='hidden' name='Km' value=''>\n";
      echo "<input type='hidden' name='NoPlaque' value=''>\n";
    }
    if ($Mode & 4) {
      switch ($Mode & 24) {
        case 0:
          $NomClient2 = "Assurance";
          break;
        case 8:
          $NomClient2 = "Banque";
          break;
        case 16:
          $NomClient2 = "Fournisseur";
          break;
      }
      echo "<BIG>$NomClient2</BIG><BR>\n";
      echo "<TABLE border=1>\n";
      echo "<TR><TH>Numéro client</TH><TD><input type='texte' name='NoClient2' value='' onchange='trouve_nom(1);'></TD></TR>\n";
      echo "<TR><TH>Nom</TH><TD><input type='texte' name='Nom2' value=''></TD></TR>\n";
      echo "<TR><TH>Prénom</TH><TD><input type='texte' name='Prenom2' value='' onchange='recherche_client_ajax(5);'></TD></TR>\n";
      echo "</TABLE>\n";
      echo "<input type='button' value='Recherche' onclick='recherche_client_ajax(5);'><input type='button' value='Effacer' onclick='efface_client(2);'><BR><BR>\n";
    } else {
      echo "<input type='hidden' name='NoClient2' value=''>\n";
      echo "<input type='hidden' name='Nom2' value=''>\n";
      echo "<input type='hidden' name='Prenom2' value=''>\n";
    }
    if ($Mode & 256) {
      echo "<BIG>Nom modèle</BIG><BR>\n";
      echo "<TABLE border=1>\n";
      echo "<TR><TH>Titre</TH><TD><input type='texte' name='Titre' value=''></TD></TR>\n";
      echo "<script language=JavaScript>\n";
      echo "this.document.forms['info'].elements['Titre'].focus();\n";
      echo "</script>\n";
      echo "</TABLE>\n";
    } else {
      echo "<input type='hidden' name='Titre' value=''>\n";
    }
    if ($Mode & 512) {
      echo "<BIG>Facture associée</BIG><BR>\n";
      echo "<TABLE border=1>\n";
      echo "<TR><TH>Facture associée</TH><TD><input type='texte' name='FactureAssociee' value=''></TD></TR>\n";
      echo "</TABLE>\n";
    } else {
      echo "<input type='hidden' name='FactureAssociee' value=''>\n";
    }
    if ($Mode & 128) {
      echo "<BIG>Facture sans texte TVA pour leasing</BIG> <input type='checkbox' name='FactureSansTexteTVA'><br/><br/>\n";
    }
    if ($Mode & 32) {
      echo "<BIG>Vendeur</BIG><BR>\n";
      $requette2 = "SELECT * FROM employes" . ID_GARAGE . " WHERE Actif=1";
      $statement = Connection::getStatement($requette2);
      $statement->execute();
      echo "<SELECT name='Vendeur'>\n";
      echo "<option value='0'>-</option>\n";
      while ($ligne2 = $statement->fetch()) {
        if ($ligne3 = Client::getClientByNoClient($ligne2['NoClient'])) {
          echo "<option value='" . $ligne3['NoClient'] . "'";
          echo ">" . $ligne3['Prenom'] . " " . $ligne3['Nom'] . "</option>\n";
        }
      }
      echo "</SELECT><BR>\n";
      echo "<button type='button' onclick='test_vendeur();'>Suite</button>";
    } else {
      echo "<input type='hidden' name='Vendeur' value=''>";
      echo "<button name='Valider' type='submit'>Valider</button>";
    }
    echo "</form>\n";
  } else {
    $ligne = Commande::getCommandeByNoCommande($NoCommande);
    if ($ligne) {
      Select_Etape_Facture($NoCommande, $ligne['NoClient'], $ligne['NoClient2'], $sous_mode);
      echo "<form name='info'>\n";
      echo "<input type='hidden' name='Type' value='$Type'>\n";
      echo "<input type='hidden' name='Sous_Type' value='$Sous_Type'>\n";
      echo "<input type='hidden' name='Etape' value='3'>\n";
      echo "<input type='hidden' name='NoCommande' value='$NoCommande'>\n";
      echo "<input type='hidden' name='Modif' value='1'>\n";
      echo "<input type='hidden' name='DateCommande' value='" . $ligne['DateCommande'] . "'>";
      if ($Mode & 1) {
        echo "<BIG>Client</BIG><BR>\n";
        echo "<TABLE border=1>\n";
        echo "<TR><TH>Numéro client</TH><TD><input type='texte' name='NoClient' value='" . $ligne['NoClient'] . "' onchange='trouve_nom(0);'></TD></TR>\n";
        if ($ligne['NoClient'] != 0) {
          if ($Mode & 2) {
            $tmp = "4";
          } else {
            $tmp = "3";
          }
          $ligne2 = Client::getClientByNoClient($ligne['NoClient']);
          echo "<TR><TH>Nom</TH><TD><input type='texte' name='Nom' value='" . $ligne2['Nom'] . "'  onkeydown='test_return_client($tmp);'></TD></TR>\n";
          echo "<script language=JavaScript>\n";
          echo "this.document.forms['info'].elements['Nom'].focus();\n";
          echo "</script>\n";
          echo "<TR><TH>Prenom</TH><TD><input type='texte' name='Prenom' value='" . $ligne2['Prenom'] . "'  onkeydown='test_return_client($tmp);'></TD></TR>\n";
        } else {
          echo "<TR><TH>Nom</TH><TD><input type='texte' name='Nom' value=''></TD></TR>\n";
          echo "<TR><TH>Prénom</TH><TD><input type='texte' name='Prenom' value='' onchange='recherche_client_ajax(";
          if ($Mode & 2) {
            echo "4";
          } else {
            echo "3";
          }
          echo ");'></TD></TR>\n";
        }
        echo "</TABLE>\n";
        if ($ligne['Paye'] != 'O') {
          echo "<input type='button' value='Recherche' onclick='recherche_client_ajax(";
          if ($Mode & 2) {
            echo "4";
          } else {
            echo "3";
          }
          echo ");'><input type='button' value='Effacer' onclick='efface_client(1);'><BR><BR>\n";
        }
      } else {
        echo "<input type='hidden' name='NoClient' value=''>\n";
        echo "<input type='hidden' name='Nom' value=''>\n";
        echo "<input type='hidden' name='Prenom' value=''>\n";
      }
      if ($Mode & 2) {
        echo "<BIG>Vehicule</BIG><BR>\n";
        echo "<TABLE border=1>\n";
        echo "<TR><TH>Numéro Chasis</TH><TD><input type='texte' name='NoChasis' value='" . $ligne['Vehicule'] . "' readonly></TD></TR>\n";
        if (!empty($ligne['Vehicule'])) {
          $ligne2 = Vehicule::getVehiculeByNoChassis($ligne['Vehicule']);
          echo "<TR><TH>Marque</TH><TD><input type='texte' name='Marque' value='" . $ligne2['MarqueModel'] . "' readonly></TD></TR>\n";
          echo "<TR><TH>Model</TH><TD><input type='texte' name='Model' value='" . $ligne2['Model'] . "' readonly></TD></TR>\n";
        } else {
          echo "<TR><TH>Marque</TH><TD><input type='texte' name='Marque' value='' readonly></TD></TR>\n";
          echo "<TR><TH>Model</TH><TD><input type='texte' name='Model' value='' readonly></TD></TR>\n";
        }
        echo "<TR><TH>Km</TH><TD><input type='texte' name='Km' value='" . $ligne['KmVhc'] . "'";
        if ($ligne['Paye'] == 'O') {
          echo " readonly";
        }
        echo "></TD></TR>\n";
        echo "<TR><TH>Numéro de plaques</TH><TD><input type='texte' name='NoPlaque' value='" . $ligne['NoPlaque'] . "'";
        if ($ligne['Paye'] == 'O') {
          echo " readonly";
        }
        echo "></TD></TR>\n";
        echo "</TABLE>\n";
        if ($ligne['Paye'] != 'O') {
          echo "<input type='button' value='Recherche' onclick='recherche_vhc(1);'><input type='button' value='Effacer' onclick='efface_vhc();'><BR><BR>\n";
        }
      } else {
        echo "<input type='hidden' name='NoChasis' value=''>\n";
        echo "<input type='hidden' name='Marque' value=''>\n";
        echo "<input type='hidden' name='Model' value=''>\n";
        echo "<input type='hidden' name='Km' value=''>\n";
        echo "<input type='hidden' name='NoPlaque' value=''>\n";
      }
      if ($Mode & 64) {
        echo "<BIG>Vehicule</BIG><BR>\n";
        echo "<TABLE border=1>\n";
        echo "<TR><TH>Numéro Chasis</TH><TD><input type='texte' name='NoChasis' value='" . $ligne['Vehicule'] . "' readonly></TD></TR>\n";
        if (!empty($ligne['Vehicule'])) {
          $ligne2 = Vehicule::getVehiculeByNoChassis($ligne['Vehicule']);
          echo "<TR><TH>Marque</TH><TD><input type='texte' name='Marque' value='" . $ligne2['MarqueModel'] . "' readonly></TD></TR>\n";
          echo "<TR><TH>Model</TH><TD><input type='texte' name='Model' value='" . $ligne2['Model'] . "' readonly></TD></TR>\n";
        } else {
          echo "<TR><TH>Marque</TH><TD><input type='texte' name='MarqueBidon' value='' readonly></TD></TR>\n";
          echo "<TR><TH>Model</TH><TD><input type='texte' name='ModelBidon' value='' readonly></TD></TR>\n";
        }
        echo "</TABLE>\n";
      }
      if ($Mode & 4) {
        switch ($Mode & 24) {
          case 0:
            $NomClient2 = "Assurance";
            break;
          case 8:
            $NomClient2 = "Banque";
            break;
          case 16:
            $NomClient2 = "Fournisseur";
            break;
        }
        echo "<BIG>$NomClient2</BIG><BR>\n";
        echo "<TABLE border=1>\n";
        echo "<TR><TH>Numéro client</TH><TD><input type='texte' name='NoClient2' value='" . $ligne['NoClient2'] . "' onchange='trouve_nom(1);'></TD></TR>\n";
        if ($ligne['NoClient2'] != 0) {
          $ligne2 = Client::getClientByNoClient($ligne['NoClient2']);
          echo "<TR><TH>Nom</TH><TD><input type='texte' name='Nom2' value='" . $ligne2['Nom'] . "'></TD></TR>\n";
          echo "<TR><TH>Prénom</TH><TD><input type='texte' name='Prenom2' value='" . $ligne2['Prenom'] . "' onchange='recherche_client_ajax(5);'></TD></TR>\n";
        } else {
          echo "<TR><TH>Nom</TH><TD><input type='texte' name='Nom2' value=''></TD></TR>\n";
          echo "<TR><TH>Prénom</TH><TD><input type='texte' name='Prenom2' value='' onchange='recherche_client_ajax(5);'></TD></TR>\n";
        }
        echo "</TABLE>\n";
        echo "<input type='button' value='Recherche' onclick='recherche_client_ajax(5);'><input type='button' value='Effacer' onclick='efface_client(2);'><BR><BR>\n";
      } else {
        echo "<input type='hidden' name='NoClient2' value=''>\n";
        echo "<input type='hidden' name='Nom2' value=''>\n";
        echo "<input type='hidden' name='Prenom2' value=''>\n";
      }
      if ($Mode & 128) {
        echo "<BIG>Facture sans texte TVA pour leasing</BIG> <input type='checkbox'";
        if ($ligne['FactureSansTexteTVA'] == 1) {
          echo " checked='checked'";
        }
        echo " name='FactureSansTexteTVA'><br/><br/>\n";
      }
      if ($Mode & 32) {
        echo "<BIG>Vendeur</BIG><BR>\n";
        $result = Employee::getEmployee();
        echo "<SELECT name='Vendeur'>\n";
        foreach ($result as $ligne2) {
          if ($ligne3 = Client::getClientByNoClient($ligne2['NoClient'])) {
            echo "<option value='" . $ligne3['NoClient'] . "'";
            if ($ligne3['NoClient'] == $ligne['Vendeur'])
              echo " selected";
            echo ">" . $ligne3['Prenom'] . " " . $ligne3['Nom'] . "</option>\n";
          }
        }
        echo "</SELECT><BR>\n";
      } else {
        echo "<input type='hidden' name='Vendeur' value=''>";
      }
      if ($Mode & 256) {
        echo "<BIG>Nom modèle</BIG><BR>\n";
        echo "<TABLE border=1>\n";
        echo "<TR><TH>Titre</TH><TD><input type='texte' name='Titre' value='" . $ligne["Titre"] . "'></TD></TR>\n";
        echo "<script language=JavaScript>\n";
        echo "this.document.forms['info'].elements['Titre'].focus();\n";
        echo "</script>\n";
        echo "</TABLE>\n";
      } else {
        echo "<input type='hidden' name='Titre' value='" . $ligne["Titre"] . "'>\n";
      }
      if ($Mode & 512) {
        echo "<BIG>Facture associée</BIG><BR>\n";
        echo "<TABLE border=1>\n";
        echo "<TR><TH>Facture associée</TH><TD><input type='texte' name='FactureAssociee' value='" . $ligne["NoCommandeAssocie"] . "'></TD></TR>\n";
        echo "</TABLE>\n";
      } else {
        echo "<input type='hidden' name='FactureAssociee' value='" . $ligne["NoCommandeAssocie"] . "'>\n";
      }
      if ($ligne['Paye'] != 'O') {
        echo "<button type='submit'>Valider</button>";
      }
      echo "</form>\n";
      if (As_Right_Fonction(6, 35))
        echo "<BR><button type='button' onclick='valide_supprimer($NoCommande);'>Supprimer</button>";
    }
  }
}

function Affiche_Client_Vehicule($Mode, $Menu)
{
  if (!isset($GLOBALS['New'])) {
    $New = 0;
  } else {
    $New = $GLOBALS['New'];
  }
  if ($New == 1)
    Create_Client_Vehicule_Facture($New, $Mode);
  else
    Create_Client_Vehicule_Facture($New, $Mode, $GLOBALS['NoCommande'], $Menu);
}

function Create_Articles_Facture_Corps(array $resultat, $Mode, $Paye)
{
  echo "<script type=\"text/javascript\">
  // When the document is ready set up our sortable with it's inherant function(s)
  jQuery(document).ready(function() {sort_table();});
";
  if (As_Right_Groupe(6)) {
    echo "var readonlytva = false;\n";
  } else {
    echo "var readonlytva = true;\n";
  }
  echo "</script>
";
  //echo "Mode = $Mode, Paye = $Paye";
  $rd_only = "";
  $rd_only_tva = " readonly=\"readonly\"";
  $edit_cell = "";
  if ($Mode & 512) {
    echo "tarif concessionaire <input type=\"checkbox\" onchange=\"affiche_prix(this);\" /><br/>";
  }
  echo "<table id=\"table_articles\" class=\"table_articles";
  if ($Mode & 512) {
    echo " hide_prix";
  }
  echo "\">\n";
  echo "  <thead>\n";
  echo "    <tr>\n";
  //NotRecep is undefined
  if ((($Paye != 'O') && ($Mode & 4)) || ($Mode & 256 && $Paye != 'O')) {
    echo "      <th class=\"edit\"></th>\n";
    if (As_Right_Groupe(6)) {
      $rd_only_tva = "";
    }
  } else {
    $rd_only = " readonly=\"readonly\"";
  }
  echo "      <th class=\"no_article\">No Article</th>\n";
  echo "      <th class=\"description\">Description</th>\n";
  echo "      <th class=\"prix_unit\">Prix unit</th>\n";
  echo "      <th class=\"rabais\">Rabais</th>\n";
  echo "      <th class=\"tva\">TVA</th>\n";
  echo "      <th class=\"gm\">GM</th>\n";
  echo "      <th class=\"quantite\">Quantité</th>\n";
  echo "      <th class=\"prix\">Prix</th>\n";
  echo "      <th class=\"stock\">Stock</th>\n";
  if ($Mode & 512) {
    echo "      <th class=\"destinataire\">Destinataire</th>\n";
    echo "      <th class=\"nb_recu\">Reçu</th>\n";
    echo "      <th class=\"date\">Date</th>\n";
  }
  echo "    </tr>\n";
  echo "  </thead>\n";
  echo "  <tbody id=\"tblBody\">\n";
  $cpt = 1;
  $total = 0;
  $NotRecep = false;
  $nb_lignes_tot = count($resultat);
  $idx = 0;
  $ligne = $resultat[$idx];
  while ($ligne) {
    switch ($ligne['TypeData']) {
      case 0:
        $specialarticle = "";
        $specialdestinataire = "";
        if ($_GET["Search"]) {
          $search = strtolower($_GET["Search"]);
          if (stripos($ligne['NoArticle'], $search) !== false) {
            $specialarticle = " style=\"background-color : yellow;\"";
          }
          if (stripos($ligne['Dest'], $search) !== false) {
            $specialdestinataire = " style=\"background-color : yellow;\"";
          }
        }
        echo "    <tr type=\"article\" id=\"el$cpt\">\n";
        if ((($Paye != 'O' || $NotRecep) && ($Mode & 4)) || ($Mode & 256 && $Paye != 'O')) {
          echo "      <td class=\"edit\"><img src=\"images/up_down.png\" class=\"handle\" /><a href=\"javascript:del('el$cpt');\"><img src=\"images/b_drop.png\" border=\"0\" /></a><input type=\"hidden\" id=\"pos$cpt\" name=\"pos$cpt\" value=\"$cpt\" /><input type=\"hidden\" id=\"type$cpt\" name=\"type$cpt\" value=\"article\" /></td>\n";
        }
        echo "      <td class=\"no_article\"><input type=\"text\"$specialarticle name=\"NoArticle$cpt\" id=\"NoArticle$cpt\" readonly=\"readonly\" value=\"" . $ligne['NoArticle'] . "\" /></td>\n";
        echo "      <td class=\"description\"><input type=\"text\" name=\"Description$cpt\" id=\"Description$cpt\"$rd_only maxlength=\"40\" size=\"40\" value=\"" . $ligne['Description'] . "\" /></td>\n";
        echo "      <td class=\"prix_unit\"><input type=\"text\" name=\"Prix$cpt\" id=\"Prix$cpt\"$rd_only onchange=\"maj_article_fact($cpt)\" maxlength=\"10\" size=\"10\" value=\"" . $ligne['PrixBase'] . "\" /></td>\n";
        echo "      <td class=\"rabais\"><input type=\"text\" class=\"rabais\" name=\"Rabais$cpt\" id=\"Rabais$cpt\"$rd_only onchange=\"maj_article_fact($cpt)\" maxlength=\"7\" size=\"7\" value=\"" . $ligne['Rabais'] . "\" /></td>\n";
        echo "      <td class=\"tva\"><input type=\"text\" name=\"TVA$cpt\" id=\"TVA$cpt\"$rd_only_tva onchange=\"maj_article_fact($cpt)\" maxlength=\"6\" size=\"6\" value=\"" . $ligne['TVA'] . "\" /></td>\n";
        echo "      <td class=\"gm\"><input type=\"text\" name=\"GM$cpt\" id=\"GM$cpt\" readonly=\"readonly\" maxlength=\"3\" size=\"3\" value=\"" . $ligne['GM'] . "\" /></td>\n";
        echo "      <td class=\"quantite\"><input type=\"text\" name=\"Quantite$cpt\" id=\"Quantite$cpt\"$rd_only onchange=\"maj_article_fact($cpt)\" maxlength=\"7\" size=\"7\" value=\"" . $ligne['Quantite'] . "\" /></td>\n";
        echo "      <td id=\"tot$cpt\" class=\"prix\">" . $ligne['PrixMulti'] . "</td>\n";
        $total += $ligne['PrixMulti'];
        // migration: undefined variables
        if (!isset($partiel)) {
          $partiel = 0;
        }
        if (!isset($partiel2)) {
          $partiel2 = 0;
        }
        $partiel += $ligne['PrixMulti'];
        $partiel2 += $ligne['PrixMulti'];
        $requette2 = "SELECT EnStock, LieuxStock FROM stock" . ID_GARAGE . " WHERE NoArticleRR='" . addslashes(Texte_Sans_Espace($ligne['NoArticle'])) . "'";
        $statement = Connection::getStatement($requette2);
        $statement->execute();
        if ($ligne2 = $statement->fetch()) {
          $tmp = round($ligne2[0]);
          if (strlen($ligne2["LieuxStock"]) == 0) {
            $tmp2 = "";
          } else {
            $tmp2 = " (" . $ligne2["LieuxStock"] . ")";
          }
        } else {
          $tmp = "0";
          $tmp2 = "";
        }
        echo "      <td class=\"stock\"><span id=\"Stock$cpt\">$tmp</span><span id=\"LieuxStock$cpt\">$tmp2</span></td>\n";
        if ($Mode & 512) {
          echo "      <td class=\"destinataire\"><input type=\"text\"$specialdestinataire id=\"Destinataire$cpt\" name=\"Destinataire$cpt\"$rd_only maxlength=\"50\" size=\"50\" value=\"" . $ligne['Dest'] . "\" /></td>\n";
          echo "      <td class=\"nb_recu\"><input type=\"text\" name=\"NbRecu$cpt\" id=\"NbRecu$cpt\"$rd_only maxlength=\"7\" size=\"7\" value=\"" . $ligne['NbRecu'] . "\" onchange=\"change_recu($cpt);\" /><input type=\"hidden\" name=\"DateRecu$cpt\" id=\"DateRecu$cpt\" value=\"" . $ligne['DateRecu'] . "\" /></td>\n";
          echo "      <td class=\"date\" id=\"DateRecuStr$cpt\">";
          if ($ligne['NbRecu'] > 0)
            echo Cree_Entree_Type("", 2, 0, $ligne['DateRecu'], AFFICHAGE);
          echo "</td>\n";
        }
        echo "      <input type=\"hidden\" name=\"Total$cpt\" value=\"" . $ligne['PrixMulti'] . "\" />\n";
        echo "    </tr>\n";
        $idx++;
        $ligne = $resultat[$idx];
        $cpt++;
        break;
      case 1:
        $tmp = $ligne['Description'];
        $nb_lignes = 1;
        $idx++;
        $ligne = $resultat[$idx];;
        while ($ligne && ($ligne['TypeData'] == 1)) {
          $tmp .= "\n" . $ligne['Description'];
          $idx++;
          $ligne = $resultat[$idx];
          $nb_lignes++;
        }
        echo "    <tr type=\"text\" id=\"el$cpt\">\n";
        if ((($Paye != 'O' || $NotRecep) && ($Mode & 4)) || ($Mode & 256 && $Paye != 'O')) {
          echo "      <td class=\"edit\"><img src=\"images/up_down.png\" class=\"handle\" /><a href=\"javascript:del('el$cpt');\"><img src=\"images/b_drop.png\" border=\"0\" /></a><input type=\"hidden\" id=\"pos$cpt\" name=\"pos$cpt\" value=\"$cpt\" /><input type=\"hidden\" id=\"type$cpt\" name=\"type$cpt\" value=\"texte\" /></td>\n";
        }
        echo "      <td class=\"texte\" colspan=\"9\">\n";
        echo "        <textarea name=\"Texte$cpt\"$rd_only onkeyup=\"update_free_text(this);\" cols=\"92\" rows=\"$nb_lignes\" wrap=\"hard\">$tmp</textarea> <b>gras</b> <input type=\"checkbox\" name=\"Gras$cpt\"/>\n";
        echo "      </td>\n";
        echo "    </tr>\n";
        $cpt++;
        break;
      case 2:
        echo "    <tr type=\"inter\" id=\"el$cpt\">\n";
        if ((($Paye != 'O' || $NotRecep) && ($Mode & 4)) || ($Mode & 256 && $Paye != 'O')) {
          echo "      <td class=\"edit\"><img src=\"images/up_down.png\" class=\"handle\" /><a href=\"javascript:del('el$cpt');\"><img src=\"images/b_drop.png\" border=\"0\" /></a><input type=\"hidden\" id=\"pos$cpt\" name=\"pos$cpt\" value=\"$cpt\" /><input type=\"hidden\" id=\"type$cpt\" name=\"type$cpt\" value=\"inter\" /></td>\n";
        }
        echo "      <td class=\"total_intermediaire_visu\" colspan=\"7\"><input type=\"text\" name=\"Description$cpt\" id=\"Description$cpt\"$rd_only maxlength=\"40\" size=\"40\" value=\"" . $ligne['Description'] . "\" /></td>\n";
        echo "      <td class=\"total_intermediaire\" id=\"inter$cpt\">" . Arrondi_5_ct($total) . "</td>\n";
        echo "      <td></td>\n";
        echo "    </tr>\n";
        $idx++;
        $ligne = $resultat[$idx];
        $cpt++;
        break;
      case 3:
        echo "    <tr class=\"tvamarges\" type=\"tvamarges\" id=\"el$cpt\">\n";
        if ((($Paye != 'O' || $NotRecep) && ($Mode & 4)) || ($Mode & 256 && $Paye != 'O')) {
          echo "      <td class=\"edit\"><img src=\"images/up_down.png\" class=\"handle\" /><a href=\"javascript:del('el$cpt');\"><img src=\"images/b_drop.png\" border=\"0\" /></a><input type=\"hidden\" id=\"pos$cpt\" name=\"pos$cpt\" value=\"$cpt\" /><input type=\"hidden\" id=\"type$cpt\" name=\"type$cpt\" value=\"tvamarges\" /></td>\n";
        }
        echo "      <td class=\"no_article\"><input type=\"text\" name=\"NoArticle$cpt\" readonly=\"readonly\" value=\"" . $ligne['NoArticle'] . "\" /></td>\n";
        echo "      <td class=\"description\"><input type=\"text\" name=\"Description$cpt\"$rd_only maxlength=\"40\" size=\"40\" value=\"" . $ligne['Description'] . "\" /></td>\n";
        echo "      <td class=\"prix_unit\"><input type=\"text\" name=\"Prix$cpt\"$rd_only onchange=\"maj_article_fact($cpt)\" maxlength=\"10\" size=\"10\" value=\"" . $ligne['PrixBase'] . "\" /></td>\n";
        echo "      <td class=\"rabais\"><input type=\"text\" name=\"Rabais$cpt\"$rd_only onchange=\"maj_article_fact($cpt)\" maxlength=\"7\" size=\"7\" value=\"" . $ligne['Rabais'] . "\" /></td>\n";
        echo "      <td class=\"tva\"><input type=\"text\" name=\"TVA$cpt\"$rd_only_tva onchange=\"maj_article_fact($cpt)\" maxlength=\"6\" size=\"6\" value=\"" . $ligne['TVA'] . "\" /></td>\n";
        echo "      <td class=\"gm\"><input type=\"text\" name=\"GM$cpt\" readonly=\"readonly\" maxlength=\"2\" size=\"2\" value=\"" . $ligne['GM'] . "\" /></td>\n";
        echo "      <td class=\"quantite\"><input type=\"text\" name=\"Quantite$cpt\"$rd_only onchange=\"maj_article_fact($cpt)\" maxlength=\"7\" size=\"7\" value=\"" . $ligne['Quantite'] . "\" /></td>\n";
        echo "      <td id=\"tot$cpt\" class=\"prix\">" . $ligne['PrixMulti'] . "</td>\n";
        $total += $ligne['PrixMulti'];
        $requette2 = "SELECT EnStock FROM stock" . ID_GARAGE . " WHERE NoArticleRR='" . addslashes(Texte_Sans_Espace($ligne['NoArticle'])) . "'";
        $statement = Connection::getStatement($requette2);
        $statement->execute();
        if ($ligne2 = $statement->fetch()) {
          $tmp = $ligne2[0];
        } else {
          $tmp = "0.00";
        }
        echo "      <td class=\"stock\">$tmp</td>\n";
        echo "      <input type=\"hidden\" name=\"Total$cpt\" value=\"" . $ligne['PrixMulti'] . "\" />\n";
        echo "    </tr>\n";
        $idx++;
        $ligne = $resultat[$idx];
        $cpt++;
        break;
      case 4:
        echo "    <tr class=\"ajouttva\" type=\"ajouttva\" id=\"el$cpt\">\n";
        if ((($Paye != 'O' || $NotRecep) && ($Mode & 4)) || ($Mode & 256 && $Paye != 'O')) {
          echo "      <td class=\"edit\"><img src=\"images/up_down.png\" class=\"handle\" /><a href=\"javascript:del('el$cpt');\"><img src=\"images/b_drop.png\" border=\"0\" /></a><input type=\"hidden\" id=\"pos$cpt\" name=\"pos$cpt\" value=\"$cpt\" /><input type=\"hidden\" id=\"type$cpt\" name=\"type$cpt\" value=\"ajouttva\" /></td>\n";
        }
        echo "      <td class=\"no_article\"><input type=\"text\" name=\"NoArticle$cpt\" readonly=\"readonly\" value=\"" . $ligne['NoArticle'] . "\" /></td>\n";
        echo "      <td class=\"description\"><input type=\"text\" name=\"Description$cpt\"$rd_only maxlength=\"40\" size=\"40\" value=\"" . $ligne['Description'] . "\" /></td>\n";
        echo "      <td class=\"prix_unit\"><input type=\"text\" name=\"Prix$cpt\"$rd_only onchange=\"maj_article_fact($cpt)\" maxlength=\"10\" size=\"10\" value=\"" . $ligne['PrixBase'] . "\" /></td>\n";
        echo "      <td class=\"rabais\"><input type=\"text\" name=\"Rabais$cpt\"$rd_only onchange=\"maj_article_fact($cpt)\" maxlength=\"7\" size=\"7\" value=\"" . $ligne['Rabais'] . "\" /></td>\n";
        echo "      <td class=\"tva\"><input type=\"text\" name=\"TVA$cpt\"$rd_only_tva onchange=\"maj_article_fact($cpt)\" maxlength=\"6\" size=\"6\" value=\"" . $ligne['TVA'] . "\" /></td>\n";
        echo "      <td class=\"gm\"><input type=\"text\" name=\"GM$cpt\" readonly=\"readonly\" maxlength=\"2\" size=\"2\" value=\"" . $ligne['GM'] . "\" /></td>\n";
        echo "      <td class=\"quantite\"><input type=\"text\" name=\"Quantite$cpt\"$rd_only onchange=\"maj_article_fact($cpt)\" maxlength=\"7\" size=\"7\" value=\"" . $ligne['Quantite'] . "\" /></td>\n";
        echo "      <td id=\"tot$cpt\" class=\"prix\">" . $ligne['PrixMulti'] . "</td>\n";
        $total += $ligne['PrixMulti'];
        $requette2 = "SELECT EnStock FROM stock" . ID_GARAGE . " WHERE NoArticleRR='" . addslashes(Texte_Sans_Espace($ligne['NoArticle'])) . "'";
        $statement = Connection::getStatement($requette2);
        $statement->execute();
        if ($ligne2 = $statement->fetch()) {
          $tmp = $ligne2[0];
        } else {
          $tmp = "0.00";
        }
        echo "      <td class=\"stock\">$tmp</td>\n";
        echo "      <input type=\"hidden\" name=\"Total$cpt\" value=\"" . $ligne['PrixMulti'] . "\" />\n";
        echo "    </tr>\n";
        $idx++;
        $ligne = $resultat[$idx];
        $cpt++;
        break;
      case 5:
        echo "    <tr type=\"partiel\" id=\"el$cpt\">\n";
        if ((($Paye != 'O' || $NotRecep) && ($Mode & 4)) || ($Mode & 256 && $Paye != 'O')) {
          echo "      <td class=\"edit\"><img src=\"images/up_down.png\" class=\"handle\" /><a href=\"javascript:del('el$cpt');\"><img src=\"images/b_drop.png\" border=\"0\" /></a><input type=\"hidden\" id=\"pos$cpt\" name=\"pos$cpt\" value=\"$cpt\" /><input type=\"hidden\" id=\"type$cpt\" name=\"type$cpt\" value=\"partiel\" /></td>\n";
        }
        echo "      <td class=\"total_partiel_visu\" colspan=\"7\"><input type=\"text\" name=\"Description$cpt\" id=\"Description$cpt\"$rd_only maxlength=\"40\" size=\"40\" value=\"" . $ligne['Description'] . "\" /></td>\n";
        echo "      <td class=\"total_partiel\" id=\"partiel$cpt\">" . Arrondi_5_ct($partiel) . "</td>\n";
        echo "      <td></td>\n";
        echo "    </tr>\n";
        $idx++;
        $ligne = $resultat[$idx];
        $partiel = 0;
        $cpt++;
        break;
      case 6:
        $tmp = $ligne['Description'];
        $nb_lignes = 1;
        $idx++;
        $ligne = $resultat[$idx];
        while ($ligne && ($ligne['TypeData'] == 6)) {
          $tmp .= "\n" . $ligne['Description'];
          $idx++;
          $ligne = $resultat[$idx];
          $nb_lignes++;
        }
        echo "    <tr type=\"text\" id=\"el$cpt\">\n";
        if ((($Paye != 'O' || $NotRecep) && ($Mode & 4)) || ($Mode & 256 && $Paye != 'O')) {
          echo "      <td class=\"edit\"><img src=\"images/up_down.png\" class=\"handle\" /><a href=\"javascript:del('el$cpt');\"><img src=\"images/b_drop.png\" border=\"0\" /></a><input type=\"hidden\" id=\"pos$cpt\" name=\"pos$cpt\" value=\"$cpt\" /><input type=\"hidden\" id=\"type$cpt\" name=\"type$cpt\" value=\"texte\" /></td>\n";
        }
        echo "      <td class=\"texte\" colspan=\"9\">\n";
        echo "        <textarea name=\"Texte$cpt\"$rd_only onkeyup=\"update_free_text(this);\" cols=\"92\" rows=\"$nb_lignes\" wrap=\"hard\">$tmp</textarea> <b>gras</b> <input type=\"checkbox\" checked=\"checked\" name=\"Gras$cpt\"/>\n";
        echo "      </td>\n";
        echo "    </tr>\n";
        $cpt++;
        break;
      case 7:
        echo "    <tr type=\"partiel2\" id=\"el$cpt\">\n";
        if ((($Paye != 'O' || $NotRecep) && ($Mode & 4)) || ($Mode & 256 && $Paye != 'O')) {
          echo "      <td class=\"edit\"><img src=\"images/up_down.png\" class=\"handle\" /><a href=\"javascript:del('el$cpt');\"><img src=\"images/b_drop.png\" border=\"0\" /></a><input type=\"hidden\" id=\"pos$cpt\" name=\"pos$cpt\" value=\"$cpt\" /><input type=\"hidden\" id=\"type$cpt\" name=\"type$cpt\" value=\"partiel2\" /></td>\n";
        }
        echo "      <td class=\"total_partiel2_visu\" colspan=\"7\"><input type=\"text\" name=\"Description$cpt\" id=\"Description$cpt\"$rd_only maxlength=\"40\" size=\"40\" value=\"" . $ligne['Description'] . "\" /></td>\n";
        echo "      <td class=\"total_partiel2\" id=\"partiel2_$cpt\">" . Arrondi_5_ct($partiel2) . "</td>\n";
        echo "      <td></td>\n";
        echo "    </tr>\n";
        $idx++;
        $ligne = $resultat[$idx];
        $partiel2 = 0;
        $cpt++;
        break;
      default:
        $idx++;
        $ligne = $resultat[$idx];
        break;
    }
  }
  $str_total = Arrondi_5_ct($total);
  echo "  </tbody>\n";
  echo "  <tfoot>\n";
  if (($Paye != 'O' || $NotRecep) && ($Mode & 4)) {
    echo "    <tr type=\"article\">\n";
    echo "      <td class=\"edit\">add</td>\n";
    echo "      <td class=\"no_article\"><input name=\"NoArticle\" type=\"text\" value=\"\" onchange=\"recherche_article_ajax(0);\" onkeydown=\"test_return(event);\" /></td>\n";
    echo "      <td class=\"description\"><input name=\"Description\" type=\"text\" maxlength=\"40\" size=\"40\" value=\"\" onkeydown=\"test_return(event);\" /></td>\n";
    echo "      <td class=\"prix_unit\"><input name=\"Prix\" type=\"text\" maxlength=\"10\" size=\"10\" value=\"0.00\" onkeydown=\"test_return(event);\" /></td>\n";
    echo "      <td class=\"rabais\"><input name=\"Rabais\" type=\"text\" maxlength=\"7\" size=\"7\" value=\"0.00\" onkeydown=\"test_return(event);\" /></td>\n";
    echo "      <td class=\"tva\"><input name=\"TVA\" type=\"text\"$rd_only_tva maxlength=\"6\" size=\"6\" value=\"-" . get_config('TVA') . "\" onkeydown=\"test_return(event);\" /></td>\n";
    echo "      <td class=\"gm\"><input name=\"GM\" readonly=\"readonly\" type=\"text\" maxlength=\"3\" size=\"3\" value=\"0\" onkeydown=\"test_return(event);\" /></td>\n";
    if ($Mode & 512) {
      echo "      <td class=\"quantite\"><input name=\"Quantite\" type=\"text\" maxlength=\"7\" size=\"7\" value=\"0.00\" onkeydown=\"enter_quantite_commande_newfact(event);\" /></td>\n";
    } else {
      echo "      <td class=\"quantite\"><input name=\"Quantite\" type=\"text\" maxlength=\"7\" size=\"7\" value=\"0.00\" onkeydown=\"enter_quantite_newfact(event);\" /></td>\n";
    }
    echo "      <td class=\"prix\"></td>\n";
    echo "      <td class=\"stock\"><span id=\"Stock\"></span><span id=\"LieuxStock\"></span><input type=\"hidden\" name=\"Stock\" value=\"0\"><input type=\"hidden\" name=\"LieuxStock\" value=\"\"></td>\n";
    if ($Mode & 512) {
      echo "      <td class=\"destinataire\"><input type=\"text\" id=\"Destinataire\" name=\"Destinataire\" maxlength=\"50\" size=\"50\" value=\"STOCK\" onkeydown=\"enter_quantite_newfact(event);\"/></td>\n";
      echo "      <td class=\"recu\">&nbsp;</td>\n";
      echo "      <td class=\"date\">&nbsp;</td>\n";
    }
    echo "    </tr>\n";
    echo "<script language=JavaScript>\nthis.document.info.NoArticle.focus();\n</script>\n";
  }
  echo "    <tr>\n";
  $nb_pages = floor(($nb_lignes_tot - 1) / 35);
  $nb_pages++;
  $style_nb_lignes = "";
  if ($nb_lignes_tot > 35) {
    $style_nb_lignes = "style=\"background-color: orange;\"";
  }
  if (($Paye != 'O' || $NotRecep) && ($Mode & 4)) {
    echo "      <td id=\"info_lignes\" $style_nb_lignes colspan=\"8\">Nb lignes " . $nb_lignes_tot . " Pages " . $nb_pages . "</td>\n";
  } else {
    echo "      <td id=\"info_lignes\" $style_nb_lignes colspan=\"7\">Nb lignes " . $nb_lignes . " Pages " . $nb_pages . "</td>\n";
  }
  echo "      <th id=\"total\" class=\"total\">$str_total</th>\n";
  echo "      <td><input name=\"Total_commande\" type=\"hidden\" readonly=\"readonly\" value=\"$str_total\" /></td>\n";
  echo "    </tr>\n";
  echo "  </tfoot>\n";
  echo "</table>\n";
  if ($Mode & 256 && $Paye != 'O') {
    echo "<input type='hidden' name='NoArticle'>\n";
    echo "<input type='hidden' name='Description'>\n";
    echo "<input type='hidden' name='Prix'>\n";
    echo "<input type='hidden' name='Rabais'>\n";
    echo "<input type='hidden' name='TVA'>\n";
    echo "<input type='hidden' name='GM'>\n";
    echo "<input type='hidden' name='Quantite'>\n";
    echo "<input type='hidden' name='Stock'>\n";
    echo "<input type='hidden' name='LieuxStock'>\n";
  }
  echo "<input type=\"hidden\" name=\"current_cpt\" value=\"$cpt\">\n";
}

function Create_Articles_Facture_newfact($NoCommande, $NoClient, $Mode = 0, $Menu = 0)
{
  // Mode 1       Edition
  // Mode 2       Total intermediaire
  // Mode 4       Article
  // Mode 8       Texte libre
  // Mode 16      Vehicule(neuf)
  // Mode 32      Bulletin livraison
  // Mode 64      Presse papier
  // Mode 128     Vehicule(occasion)
  // Mode 256     Vehicule(reprise)
  // Mode 512     Mode commande
  // Mode 1024   Achat marchandise
  // Mode 2048   Masque rabais + prix
  // Mode 4096   Dupliquer
  // Mode 8192   Titre commande
  // Mode 16384  Modele
  global $Type, $Sous_Type, $NoClient2;
  $requette = "SELECT Paye, NoFourniseur, Type, Titre, Commantaire FROM commande" . ID_GARAGE . " WHERE NoCommande=:nocommande";
  $statement = Connection::getStatement($requette);
  $statement->bindParam(":nocommande", $NoCommande);
  $statement->execute();
  $ligne = $statement->fetch();
  $Paye = $ligne[0];
  $NoFourniseur = $ligne[1];
  $Commantaire = $ligne[4];
  $commandesArticles = CommandeArticle::getCommandeArticleByNoCommande($NoCommande);
  //if ($commandesArticles)
  //{
  echo "<SCRIPT language=JavaScript src=" . '"fonctionscommande.js"' . " type=text/javascript></SCRIPT>\n";
  echo "<form METHOD='POST' name='info' action='default.php?Type=4&Sous_Type=1&Etape=4&NoCommande=$NoCommande&NoClient=$NoClient&NoClient2=$NoClient2' onsubmit='return test_submit();'>\n";
  echo "<div class='div_corps'>\n";
  if ($Mode & 8192) {
    echo "<div class='div_titre'>\n";
    echo "<BIG class='titre_bloc'>Titre</BIG><BR>\n";
    echo "<input type='text' value=\"" . $ligne["Titre"] . "\" name='titre_commande' style='font-size: 20px; width: 100%;'>";
    echo "</div><br/>\n";
  }
  Create_Articles_Facture_Corps($commandesArticles, $Mode, $Paye);
  echo "<input type='hidden' name='Type' value='$Type'>\n";
  echo "<input type='hidden' name='Sous_Type' value='$Sous_Type'>\n";
  echo "<input type='hidden' name='Etape' value='4'>\n";
  echo "<input type='hidden' name='NoCommande' value='$NoCommande'>\n";
  if ($Paye != 'O' || $NotRecep) {
    if ($Mode & 1) {
      echo "<input type='hidden' name='Modif' value='1'>\n";
      //echo "<input class='button bt_modifier' type='button' value='Modifier' onclick='edit_tab();'>\n";
      //echo "<input class='button bt_up' type='button' value='Up' onclick='move_up();'>\n";
      //echo "<input class='button bt_down' type='button' value='Down' onclick='move_down();'>\n";
      //echo "<input class='button bt_supprimer' type='button' value='Supprimer' onclick='delete_select();'>\n";
      echo "<input class='button bt_rechercher' type='button' value='Rechercher' onclick='ouvre_recherche_article(0);' onkeydown='annule_return();'>\n";
    }
    if ($Mode & 2) {
      echo "<input class='button bt_total_inter' type='button' name='total_intermediaire' value='Sous total' onclick='tot_inter_newfact();'>\n";
      echo "<input class='button bt_total_inter' type='button' name='total_intermediaire' value='Total partiel' onclick='tot_partiel_newfact();'>\n";
      echo "<input class='button bt_total_inter' type='button' name='total_intermediaire' value='Total partiel 2' onclick='tot_partiel2_newfact();'>\n";
    }
    echo "</div>\n";
    if ($Mode & 512) {
      echo "<BIG class='titre_bloc'>Réception</BIG><BR/>\n";
      echo "<input class='button bt_recept_article' type='button' value='Récep complète' onclick='recep_comp_newfact();'>\n";
      //echo "<input class='button bt_recept_article' type='button' value='Récep article' onclick='recep_art();'>\n";
      //echo "<input class='button bt_recept_article_partiel' type='button' value='Récep part' onclick='recep_part();'><input type='text' name='NbPart' size=4>\n";
    }
    if ($Mode & 1) {
      echo $tmp_to_add;
    }
    echo "<input type='hidden' name='NoClient' value='$NoClient'>\n";
    echo "<input type='hidden' name='ElementActuel' value='-1'>\n";
    echo "<input type='hidden' name='NbElements' value='$cpt2'>\n";
    echo "<input type='hidden' name='IsCommande' value='";
    if ($Mode & 512)
      echo "1";
    else
      echo "0";
    echo "'>\n";
    echo "<input type='hidden' name='IsAchatMarchandise' value='";
    if ($Mode & 1024)
      echo "1";
    else
      echo "0";
    echo "'>\n";
    /*if (false)
        {
        if ($Mode&4)
        {
          echo "<div class='div_article'>\n";
          echo "<BIG class='titre_bloc'>Article</BIG>\n";
          echo "<input type='hidden' name='Stock' value='0'>\n";
          echo "<TABLE class='table_article' cellspacing='0'>\n";
          echo "<TR class='tr_no_article_description'><TD class='td_label no_article'>Numéro Article</TD><TD class='td_valeur no_article'><input type='texte' name='NoArticle' value='' onkeydown='test_return(event);' onchange='recherche_article_ajax(0);'></TD>\n";
          echo "<script language=JavaScript>\nthis.document.info.NoArticle.focus();\n</script>\n";
          echo "<TD class='td_label description'>Description</TD><TD class='td_valeur description' colspan='3'><input type='texte' size='52' name='Description' value='' onkeydown='test_return();'></TD></TR>\n";
          echo "<TR class='tr_prix_rabais_tva'><TD class='td_label prix'>Prix</TD><TD class='td_valeur prix'><input type='texte' name='Prix' value='' onkeydown='test_return();'></TD>\n";
          echo "<TD class='td_label rabais'>Rabais</TD><TD class='td_valeur rabais'><input type='texte' name='Rabais' value='' onkeydown='test_return();'></TD>\n";
          echo "<TD class='td_label tva'>TVA</TD><TD class='td_valeur tva'><input type='texte' name='TVA' value='' onkeydown='test_return();'></TD></TR>\n";
          echo "<TR class='tr_gm_quantite_dest'><TD class='td_label gm'>Groupe Marchandise</TD><TD class='td_valeur gm'><input type='texte' name='GM' value='' onkeydown='test_return();'></TD>\n";
          echo "<TD class='td_label quantite'>Quantite</TD><TD class='td_valeur quantite'><input type='texte' name='Quantite' value='' onkeydown='enter_quantite(event);'></TD>";
          if($Mode&512)
            echo "<TD class='td_label dest'>Dest</TD><TD class='td_valeur dest'><input type='texte' name='Destinataire' value='Stock' onkeydown='test_return();'></TD>";
          else
            echo "<TD colspan='2'>&nbsp;</TD>";
          echo "</TR>\n</TABLE>\n";
          echo "<input class='button bt_ajouter' type='button' value='Ajouter' onclick='add_new(true);' onkeydown='annule_return();'>\n";
          echo "<input class='button bt_effacer' type='button' value='Effacer' onclick='clear_data();' onkeydown='annule_return();'>\n";
          echo "<input class='button bt_modifier' type='button' name='modif_data' value='Modifier' onclick='modif_select();' onkeydown='annule_return();' disabled>\n";
          echo "<input class='button bt_rechercher' type='button' value='Rechercher' onclick='ouvre_recherche_article(0);' onkeydown='annule_return();'>\n";
          echo "</div>\n";
        }
        else
        {
          echo "<input type='hidden' name='NoArticle'>\n";
          echo "<input type='hidden' name='Description'>\n";
          echo "<input type='hidden' name='Prix'>\n";
          echo "<input type='hidden' name='Rabais'>\n";
          echo "<input type='hidden' name='TVA'>\n";
          echo "<input type='hidden' name='GM'>\n";
          echo "<input type='hidden' name='Quantite'>\n";
          echo "<input type='hidden' name='Stock'>\n";
        }
        }*/
    if ($Mode & 8) {
      echo "<div class='div_texte_libre'>\n";
      echo "<BIG class='titre_bloc'>Texte libre</BIG><BR>\n";

      // check if table exist
      $tableExist = true;
      try {
        $result = Connection::executeRawQuery("SELECT 1 FROM textestypes LIMIT 1");
      } catch (Exception $e) {
        // We got an exception (table not found)
        $tableExist = false;
      }
      $num_tt = 0;
      if ($tableExist) {
        $requette_tt = "SELECT * FROM textestypes WHERE scope = '' OR scope LIKE :type ORDER BY description";
        $statement = Connection::getStatement($requette_tt);
        $statement->bindValue(":type", '%' . $ligne["Type"] . '%');
        $statement->execute();
        $resultat_tt = $statement->fetchAll();


        $num_tt = count($resultat_tt);
      }
      if ($num_tt > 0) {
        echo "Textes types <select name=\"Texte_type\" id=\"Texte_type\">\n";
        foreach ($resultat_tt as $ligne_tt) {
          echo "<option value=\"" . $ligne_tt["id"] . "\">" . $ligne_tt["description"] . "</option>\n";
        }
        echo "</select><input class='button bt_ajouter' type='button' value='ajouter' onclick='add_text_type($NoCommande);'><br>\n";
      }

      echo "<textarea class='ta_texte_libre police_prop' cols=92 rows=";
      if ($GLOBALS['size'] == 2) {
        echo "3";
      } else {
        echo "5";
      }
      echo " name='Texte_libre' onkeydown='annule_return();' wrap='hard'></textarea><BR>\n"; //  style='font-family: Courier, monospace;'
      echo "<input class='button bt_ajouter' type='button' value='Ajouter' onclick='add_new_text_newfact();' onkeydown='annule_return();'>\n";
      //echo "<input class='button bt_effacer' type='button' value='Effacer' onclick='clear_texte();' onkeydown='annule_return();'>\n";
      //echo "<input class='button bt_modifier' type='button' name='modif_text' value='Modifier' onclick='modif_select_text();' onkeydown='annule_return();' disabled>\n";
      echo "</div>\n";
    }
    echo "<div class='div_commentaire'>\n";
    echo "<BIG class='titre_bloc'>Commentaire</BIG><BR>\n";
    echo "<textarea class='ta_texte_libre police_prop' cols=92 rows=3 name='Commantaire' onchange='AsChange=1;' onkeydown='annule_return();' wrap='hard'>$Commantaire</textarea><BR>\n"; //  style='font-family: Courier, monospace;'
    echo "</div>\n";
    if ($Mode & (16 + 128)) {
      echo "<div class='div_vhc_vente'>\n";
      echo "<BIG class='titre_bloc'>Vehicule vente</BIG><BR>\n";
      $requette = "SELECT * FROM vehicules WHERE ";
      if ($Mode & 128)
        $requette .= "Status='O' OR Status='DO'";
      if (($Mode & (16 + 128)) == (16 + 128))
        $requette .= " OR ";
      if ($Mode & 16)
        $requette .= "Status='N' OR Status='DN'";
      $requette .= " ORDER BY MarqueModel, Model, NoChasis";
      $statement = Connection::getStatement($requette);
      $statement->execute();
      $resultat = $statement->fetchAll();
      if (count($resultat) > 0) {
        echo "<SELECT class='select_vhc_vente' name='liste_vhc_vente'>\n"; //  style='font-family: Courier, monospace;'
        $cpt = 0;
        $tmp_no_cha = "";
        foreach ($resultat as $ligne) {
          $tmp_no_cha .= "<input type='hidden' name='Vhc$cpt' value=" . '"' . $ligne['NoChasis'] . '"' . ">\n";
          $tmp_no_cha .= "<input type='hidden' name='VhcType$cpt' value=" . '"';
          if (($ligne['Status'] == "N") || ($ligne['Status'] == "DN")) {
            $tmp_no_cha .= "N";
          } else {
            $tmp_no_cha .= "O";
          }
          $tmp_no_cha .= '"' . ">\n";
          $NoChasis = $ligne['NoChasis'];
          $NoChasis = aligne_gauche_select($NoChasis, 20);
          $Marque = $ligne['MarqueModel'];
          $Marque = aligne_gauche_select($Marque, 10);
          $Model = $ligne['Model'];
          $Model = aligne_gauche_select($Model, 10);
          $Couleur = $ligne['Couleur'];
          $Couleur = aligne_gauche_select($Couleur, 8);
          $Annee = substr($ligne['DateCircul'], 0, 4);
          $Km = $ligne['Km'];
          $Km = aligne_droite_select($Km, 6);
          switch ($ligne['Status']) {
            case "O":
            case "DO":
              $Status = "Occasion";
              break;
            case "N":
            case "DN":
              $Status = "Neuf";
              break;
          }
          echo "<option value='$cpt'>$NoChasis&nbsp;$Marque&nbsp;$Model&nbsp;$Couleur&nbsp;$Annee&nbsp;$Km&nbsp;$Status</option>\n";
          $cpt++;
        }
        if (empty($NoClient))
          $NoClient = 0;
        if (empty($NoClient2))
          $NoClient2 = 0;
        echo "</SELECT><input class='button bt_vendre' type='button' value='Vendre' onclick='vendre_vhc_newfact($NoClient,$NoClient2,$NoCommande," . $GLOBALS['Devis'] . ");'>\n";
        echo "<input type='hidden' value=0 name='WaitVhcVente'>\n";
        echo "<input type='hidden' value='' name='LastVhc'>\n";
        echo $tmp_no_cha;
      }
      echo "</div>\n";
    }
    if ($Mode & 256) {
      echo "<div class='div_vhc_achat'>\n";
      echo "<BIG class='titre_bloc'>Vehicule reprise</BIG><BR>\n";
      echo "NoChâssis<input name='NoChasisAchat' value='' readonly><input class='button bt_rechecher_creer' type='button' value='Rechercher-Créer' onclick='recherche_vhc(2);'><input type='button' value='Acheter' onclick='achat_vhc_newfact($NoClient, $NoCommande, " . '"O"' . ");'>";
      echo "</div>\n";
    }
    if ($Mode & 32) {
      echo "<div class='div_bulletin_livraison'>\n";
      echo "<BIG class='titre_bloc'>Bulletin de livraison</BIG><BR>\n";
      $requette = "SELECT * FROM commande" . ID_GARAGE . " WHERE Type='BP' AND Genre='B' AND Paye!='O' AND NoClient=:noclient";
      $statement = Connection::getStatement($requette);
      $statement->bindParam(":noclient", $NoClient);
      $statement->execute();
      $resultat = $statement->fetchAll($requette);
      echo "<SELECT class='select_bulletin_livraison' name='liste_bultin'>\n"; //  style='font-family: Courier, monospace;'
      $tmp_no_bul = "";
      $cpt = 0;
      foreach ($resultat as $ligne) {
        $tmp_no_bul .= "<input type='hidden' name='Bul$cpt' value=" . '"' . $ligne['NoCommande'] . '"' . ">\n";
        $NoCommande2 = $ligne['NoCommande'];
        $NoCommande2 = aligne_droite_select($NoCommande2, 6);
        $MontantTotal = $ligne['MontantTotal'];
        $MontantTotal = aligne_droite_select($MontantTotal, 9);
        echo "<option value='$cpt'>$NoCommande2&nbsp;$MontantTotal&nbsp;" . Cree_Entree_Type("", 2, 0, $ligne['DateModification'], AFFICHAGE) . "</option>";
        $cpt++;
      }
      echo "</SELECT><input class='button bt_importer' type='button' value='Importer' onclick='add_bultin_newfact();'>\n";
      echo $tmp_no_bul;
      echo "</div>\n";
    }
    if ($Mode & 64) {
      echo "<div class='div_presse_papier'>\n";
      echo "<BIG class='titre_bloc'>Presse papier</BIG><BR>\n";
      if ($Mode & 512) {
        echo "No fourniseur<input class='no_fourniseur' name='NoCommandeFourniseur' value='" . $NoFourniseur . "'>\n";
      }
      if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
        //$browser = 'Internet Explorer (MSIE/Compatible)';
        echo "<input class='button bt_copier' type='button' value='Copier' onclick='copyToClipboard_newfact();'>\n";
        echo "<input class='button bt_coller' type='button' value='Coller' onclick='pasteFromClipboard_newfact();'>\n";
      } else {
        echo "<input class='button bt_copier' type='button' value='Copier' onclick='copyToClipboard_newfact_ff();'>\n";
        echo "<input class='button bt_coller' type='button' value='Coller' onclick='pasteFromClipboard_newfact_ff();'>\n";
        echo "presse_papier <textarea name=\"presse_papier\" id=\"presse_papier\" rows=\"1\" cols=\"10\"></textarea>\n";
      }
      echo "<input class='input_no_import' type='text' name='NoImport' size=6 readonly>\n";
      echo "<input class='button bt_inserer' type='button' value='Insérer' onclick='insertNoCommande_newfact(";
      if ($Mode & 512) {
        echo "1";
      } else {
        echo "0";
      }
      echo ");'>\n<input class='button bt_rechercher' type='button' value='Rechercher' onclick='fenetre_find(14,1," . '"' . "&Cible=NoImport" . '"' . ");'>\n";
      echo "<TEXTAREA ID='FullText' STYLE='position: absolute; top: -1000; left: -1000;'></TEXTAREA>";
      echo "</div>\n";
    }
    if ($Mode & 4096) {
      echo "<div class='div_dupliquer'>\n";
      echo "<BIG class='titre_bloc'>Dupliquer</BIG><BR><BR>\n";
      echo "<input class='button bt_dupliquer' type='button' onClick='dupliquer(this.form);' value='Dupliquer' /><br/><br/><br/>\n";
      echo "</div>\n";
    }
    if ($Mode & 16384) {
      echo "<div class='div_modele'>\n";
      echo "<BIG class='titre_bloc'>Modèle</BIG><BR><BR>\n";
      echo "<select class='select_modele' name='liste_modele'>";
      $requette = "SELECT * FROM commande" . ID_GARAGE . " WHERE Type='MO' AND Genre='M' ORDER BY Titre";
      $statement = Connection::getStatement($requette);
      $statement->execute();
      $resultat = $statement->fetchAll();
      foreach ($resultat as $ligne) {
        $noModele = $ligne["NoCommande"];
        $titreModele = $ligne["Titre"];
        echo "<option value='$noModele'>$titreModele</option>";
      }
      echo "</select>";
      echo "<input class='button bt_modele' type='button' onClick='insertNoModele();' value='Insérer' /><br/><br/><br/>\n";
      echo "</div>\n";
    }
    if ($Mode != 0) {
      echo "<div class='div_valider'>\n";
      echo "<input type='hidden' value=0 name='Encaisse'>";
      echo "<input type='hidden' value=0 name='Duplique'>";
      echo "<input class='button bt_valider' type='button' onClick='go_imprime(this.form);' value='Valider' />\n";
      if ($Menu & M_ENC) {
        echo "<input class='button bt_valider_encaisser' type='button' onClick='go_encaisse(this.form);' value='Valider et encaisser' />";
      }
      echo "</div>\n";
    }
  } else {
    echo "</div>\n";
  }
  echo "</form>\n";
  if (As_Right_Fonction(6, 35))
    echo "<BR><input class='button bt_valider' type='button' onclick='valide_supprimer($NoCommande);' value='Supprimer' />";
  //}
}

function Create_Articles_Facture($NoCommande, $NoClient, $Mode = 0, $Menu = 0)
{
  // Mode 1       Edition
  // Mode 2       Total intermediaire
  // Mode 4       Article
  // Mode 8       Texte libre
  // Mode 16      Vehicule(neuf)
  // Mode 32      Bulletin livraison
  // Mode 64      Presse papier
  // Mode 128     Vehicule(occasion)
  // Mode 256     Vehicule(reprise)
  // Mode 512     Mode commande
  // Mode 1024   Achat marchandise
  global $Type, $Sous_Type, $NoClient2;
  $requette = "SELECT Paye, NoFourniseur FROM commande" . ID_GARAGE . " WHERE NoCommande=:nocommande";
  $statement = Connection::getStatement($requette);
  $statement->bindParam(":nocommande", $NoCommande);
  $statement->execute();
  $resultat = $statement->fetchAll();
  $ligne = $resultat[0];
  $Paye = $ligne[0];
  $NoFourniseur = $ligne[1];

  $resultat = CommandeArticle::getCommandeArticleByNoCommande($NoCommande);
  echo "<SCRIPT language=JavaScript src=" . '"fonctionscommande.js"' . " type=text/javascript></SCRIPT>\n";
  echo "<form METHOD='POST' name='info' action='default.php' onsubmit='return test_submit();'>\n";
  echo "<div class='div_corps'>\n";
  $tmp_to_add = "";
  echo "<INPUT class='input_titre_corps police_prop' type='text' readonly name='liste_bof' value='No Article&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Description&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Prix&nbsp;unit&nbsp;Rabais&nbsp;&nbsp;&nbsp;&nbsp;TVA&nbsp;Quantité&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Prix&nbsp;Stock";
  if ($Mode & 512)
    echo "&nbsp;Destinataire&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Reçu&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date";
  echo "', size=";
  if ($Mode & 512)
    echo "141";
  else
    echo "106";
  echo "><BR>";
  echo "<SELECT class='select_corps police_prop' name='liste_articles' size='15' onchange='change_position();' MULTIPLE>\n"; //  style='font-family: Courier, monospace;'
  $cpt = 0;
  $total = 0;
  $NotRecep = false;
  foreach ($resultat as $ligne) {
    echo "<option value='$cpt'>";
    $tmp_to_add .= "<input type='hidden' name='MemTypeData$cpt' value='" . $ligne['TypeData'] . "'>\n";
    switch ($ligne['TypeData']) {
      case 0:
      case 4:
        $tmp = $ligne['NoArticle'];
        $tmp_to_add .= "<input type='hidden' name='MemNoArticle$cpt' value=" . '"' . htmlspecialchars($tmp) . '"' . ">\n";
        $tmp = aligne_gauche_select($tmp, 17);
        echo $tmp;
        $tmp = $ligne['Description'];
        $tmp_to_add .= "<input type='hidden' name='MemDescription$cpt' value=" . '"' . htmlspecialchars($tmp) . '"' . ">\n";
        $tmp = aligne_gauche_select($tmp, 41);
        echo $tmp;
        $tmp = $ligne['PrixBase'];
        $tmp_to_add .= "<input type='hidden' name='MemPrix$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 9);
        echo $tmp . "&nbsp;";
        $tmp = $ligne['Rabais'];
        $tmp_to_add .= "<input type='hidden' name='MemRabais$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 6);
        echo $tmp . "&nbsp;";
        $tmp = $ligne['TVA'];
        $tmp_to_add .= "<input type='hidden' name='MemTVA$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 6);
        echo $tmp . "&nbsp;";
        $tmp = $ligne['GM'];
        $tmp_to_add .= "<input type='hidden' name='MemGM$cpt' value='$tmp'>\n";
        $tmp = aligne_gauche_select($tmp, 5);
        $tmp = $ligne['Quantite'];
        $tmp_to_add .= "<input type='hidden' name='MemQuantite$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 8);
        echo $tmp . "&nbsp;";
        $tmp = $ligne['PrixMulti'];
        $total += $tmp;
        $tmp_to_add .= "<input type='hidden' name='MemPrixTotal$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 9);
        echo $tmp;
        $requette2 = "SELECT EnStock FROM stock" . ID_GARAGE . " WHERE NoArticleRR=:noarticlerr";
        $statement2 = Connection::getStatement($requette2);
        $statement2->bindParam(":noarticlerr", addslashes(Texte_Sans_Espace($ligne['NoArticle'])));
        $statement2->execute();
        if ($ligne2 = $statement2->fetch()) {
          $tmp = $ligne2[0];
        } else {
          $tmp = "0.00";
        }
        $tmp = round($tmp);
        $tmp_to_add .= "<input type='hidden' name='MemStock$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 6);
        echo $tmp;
        if ($Mode & 512) {
          $tmp = $ligne['Dest'];
          $tmp_to_add .= "<input type='hidden' name='MemDest$cpt' value='$tmp'>\n";
          echo "&nbsp;";
          $tmp = aligne_gauche_select($tmp, 14);
          echo $tmp;
          $tmp = $ligne['NbRecu'];
          $tmp_to_add .= "<input type='hidden' name='MemNbRecu$cpt' value='$tmp'>\n";
          $tmp = $ligne['DateRecu'];
          $tmp_to_add .= "<input type='hidden' name='MemDateRecu$cpt' value='$tmp'>\n";
          if ($ligne['NbRecu'] == 0) {
            $NotRecep = true;
            echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;NON&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
          } else if ($ligne['NbRecu'] == $ligne['Quantite']) {
            echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;OUI&nbsp;" . Cree_Entree_Type("", 2, 0, $ligne['DateRecu'], AFFICHAGE);
          } else {
            $NotRecep = true;
            $tmp = $ligne['NbRecu'];
            echo "&nbsp;";
            $tmp = aligne_droite_select($tmp, 8);
            echo $tmp;
            echo "&nbsp;" . Cree_Entree_Type("", 2, 0, $ligne['DateRecu'], AFFICHAGE);
          }
        }
        break;
      case 1:
        $tmp = $ligne['NoArticle'];
        $tmp_to_add .= "<input type='hidden' name='MemNoArticle$cpt' value=" . '"' . htmlspecialchars($tmp) . '"' . ">\n";
        $tmp = $ligne['Description'];
        $tmp_to_add .= "<input type='hidden' name='MemDescription$cpt' value=" . '"' . htmlspecialchars($tmp) . '"' . ">\n";
        $tmp = aligne_gauche_select($tmp, 100);
        echo $tmp;
        $tmp = $ligne['PrixBase'];
        $tmp_to_add .= "<input type='hidden' name='MemPrix$cpt' value='$tmp'>\n";
        $tmp = $ligne['Rabais'];
        $tmp_to_add .= "<input type='hidden' name='MemRabais$cpt' value='$tmp'>\n";
        $tmp = $ligne['TVA'];
        $tmp_to_add .= "<input type='hidden' name='MemTVA$cpt' value='$tmp'>\n";
        $tmp = $ligne['GM'];
        $tmp_to_add .= "<input type='hidden' name='MemGM$cpt' value='$tmp'>\n";
        $tmp = $ligne['Quantite'];
        $tmp_to_add .= "<input type='hidden' name='MemQuantite$cpt' value='$tmp'>\n";
        $tmp = $ligne['PrixMulti'];
        $tmp_to_add .= "<input type='hidden' name='MemPrixTotal$cpt' value='$tmp'>\n";
        $tmp = "0.00";
        $tmp_to_add .= "<input type='hidden' name='MemStock$cpt' value='$tmp'>\n";
        if ($Mode & 512) {
          $tmp = $ligne['Dest'];
          $tmp_to_add .= "<input type='hidden' name='MemDest$cpt' value='$tmp'>\n";
          $tmp = $ligne['NbRecu'];
          $tmp_to_add .= "<input type='hidden' name='MemNbRecu$cpt' value='$tmp'>\n";
          $tmp = $ligne['DateRecu'];
          $tmp_to_add .= "<input type='hidden' name='MemDateRecu$cpt' value='$tmp'>\n";
        }
        break;
      case 2:
        $tmp = $ligne['NoArticle'];
        $tmp_to_add .= "<input type='hidden' name='MemNoArticle$cpt' value=" . '"' . htmlspecialchars($tmp) . '"' . ">\n";
        $tmp = aligne_gauche_select($tmp, 17);
        echo $tmp;
        $tmp = $ligne['Description'];
        $tmp_to_add .= "<input type='hidden' name='MemDescription$cpt' value=" . '"' . htmlspecialchars($tmp) . '"' . ">\n";
        $tmp = aligne_gauche_select($tmp, 41);
        echo $tmp;
        $tmp = $ligne['PrixBase'];
        $tmp_to_add .= "<input type='hidden' name='MemPrix$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 9);
        echo $tmp . "&nbsp;";
        $tmp = $ligne['Rabais'];
        $tmp_to_add .= "<input type='hidden' name='MemRabais$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 6);
        echo $tmp . "&nbsp;";
        $tmp = $ligne['TVA'];
        $tmp_to_add .= "<input type='hidden' name='MemTVA$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 6);
        echo $tmp . "&nbsp;";
        $tmp = $ligne['GM'];
        $tmp_to_add .= "<input type='hidden' name='MemGM$cpt' value='$tmp'>\n";
        $tmp = aligne_gauche_select($tmp, 5);
        $tmp = $ligne['Quantite'];
        $tmp_to_add .= "<input type='hidden' name='MemQuantite$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 8);
        echo $tmp . "&nbsp;";
        $tmp = $ligne['PrixMulti'];
        $total += $tmp;
        $tmp_to_add .= "<input type='hidden' name='MemPrixTotal$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 9);
        echo $tmp;
        $requette2 = "SELECT EnStock FROM stock" . ID_GARAGE . " WHERE NoArticleRR=:noarticlerr";
        $statement2 = Connection::getStatement($requette2);
        $statement2->bindParam(":noarticlerr", addslashes(Texte_Sans_Espace($ligne['NoArticle'])));
        $statement2->execute();
        if ($ligne2 = $statement2->fetch()) {
          $tmp = $ligne2[0];
        } else {
          $tmp = "0.00";
        }
        $tmp = round($tmp);
        $tmp_to_add .= "<input type='hidden' name='MemStock$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 6);
        echo $tmp;
        if ($Mode & 512) {
          $tmp = $ligne['NbDest'];
          $tmp_to_add .= "<input type='hidden' name='MemDest$cpt' value='$tmp'>\n";
          $tmp = $ligne['NbRecu'];
          $tmp_to_add .= "<input type='hidden' name='MemNbRecu$cpt' value='$tmp'>\n";
          $tmp = $ligne['DateRecu'];
          $tmp_to_add .= "<input type='hidden' name='MemDateRecu$cpt' value='$tmp'>\n";
        }
        break;
      case 3:
        $tmp = $ligne['NoArticle'];
        $tmp_to_add .= "<input type='hidden' name='MemNoArticle$cpt' value=" . '"' . htmlspecialchars($tmp) . '"' . ">\n";
        $tmp = aligne_gauche_select($tmp, 17);
        echo $tmp;
        $tmp = $ligne['Description'];
        $tmp_to_add .= "<input type='hidden' name='MemDescription$cpt' value=" . '"' . htmlspecialchars($tmp) . '"' . ">\n";
        $tmp = aligne_gauche_select($tmp, 41);
        echo $tmp;
        $tmp = $ligne['PrixBase'];
        $tmp_to_add .= "<input type='hidden' name='MemPrix$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 9);
        echo $tmp . "&nbsp;";
        $tmp = $ligne['Rabais'];
        $tmp_to_add .= "<input type='hidden' name='MemRabais$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 6);
        echo $tmp . "&nbsp;";
        $tmp = $ligne['TVA'];
        $tmp_to_add .= "<input type='hidden' name='MemTVA$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 6);
        echo $tmp . "&nbsp;";
        $tmp = $ligne['GM'];
        $tmp_to_add .= "<input type='hidden' name='MemGM$cpt' value='$tmp'>\n";
        $tmp = aligne_gauche_select($tmp, 5);
        $tmp = $ligne['Quantite'];
        $tmp_to_add .= "<input type='hidden' name='MemQuantite$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 8);
        echo $tmp . "&nbsp;";
        $tmp = $ligne['PrixMulti'];
        $tmp_to_add .= "<input type='hidden' name='MemPrixTotal$cpt' value='$tmp'>\n";
        $tmp = aligne_droite_select($tmp, 9);
        echo $tmp;
        $requette2 = "SELECT EnStock FROM stock" . ID_GARAGE . " WHERE NoArticleRR=:noarticlerr";
        $statement2 = Connection::getStatement($requette2);
        $statement2->bindParam(":noarticlerr", addslashes(Texte_Sans_Espace($ligne['NoArticle'])));
        $statement2->execute();
        if ($ligne2 = $statement2->fetch()) {
          $tmp = $ligne2[0];
        } else {
          $tmp = "0.00";
        }
        $tmp = round($tmp);
        $tmp_to_add .= "<input type='hidden' name='MemStock$cpt' value='$tmp'>\n";
        $stmp = strlen($tmp);
        $tmp = aligne_droite_select($tmp, 6);
        echo $tmp;
        if ($Mode & 512) {
          $tmp = $ligne['Dest'];
          $tmp_to_add .= "<input type='hidden' name='MemDest$cpt' value='$tmp'>\n";
          echo "&nbsp;";
          $tmp = aligne_gauche_select($tmp, 14);
          echo $tmp;
          $tmp = $ligne['NbRecu'];
          $tmp_to_add .= "<input type='hidden' name='MemNbRecu$cpt' value='$tmp'>\n";
          $tmp = $ligne['DateRecu'];
          $tmp_to_add .= "<input type='hidden' name='MemDateRecu$cpt' value='$tmp'>\n";
          if ($ligne['NbRecu'] == 0) {
            $NotRecep = true;
            echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;NON&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
          } else if ($ligne['NbRecu'] == $ligne['Quantite']) {
            echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;OUI&nbsp;" . Cree_Entree_Type("", 2, 0, $ligne['DateRecu'], AFFICHAGE);
          } else {
            $NotRecep = true;
            $tmp = $ligne['NbRecu'];
            echo "&nbsp;";
            $tmp = aligne_droite_select($tmp, 8);
            echo $tmp;
            echo "&nbsp;" . Cree_Entree_Type("", 2, 0, $ligne['DateRecu'], AFFICHAGE);
          }
        }
        break;
    }
    echo "</option>\n";
    $cpt++;
  }
  $cpt2 = $cpt;
  for ($cpt = $cpt2; $cpt < 200; $cpt++) {
    $tmp_to_add .= "<input type='hidden' name='MemTypeData$cpt' value=''>\n";
    $tmp_to_add .= "<input type='hidden' name='MemNoArticle$cpt' value=''>\n";
    $tmp_to_add .= "<input type='hidden' name='MemDescription$cpt' value=''>\n";
    $tmp_to_add .= "<input type='hidden' name='MemPrix$cpt' value=''>\n";
    $tmp_to_add .= "<input type='hidden' name='MemRabais$cpt' value=''>\n";
    $tmp_to_add .= "<input type='hidden' name='MemTVA$cpt' value=''>\n";
    $tmp_to_add .= "<input type='hidden' name='MemGM$cpt' value=''>\n";
    $tmp_to_add .= "<input type='hidden' name='MemQuantite$cpt' value=''>\n";
    $tmp_to_add .= "<input type='hidden' name='MemPrixTotal$cpt' value=''>\n";
    $tmp_to_add .= "<input type='hidden' name='MemStock$cpt' value=''>\n";
    if ($Mode & 512) {
      $tmp_to_add .= "<input type='hidden' name='MemDest$cpt' value=''>\n";
      $tmp_to_add .= "<input type='hidden' name='MemNbRecu$cpt' value=''>\n";
      $tmp_to_add .= "<input type='hidden' name='MemDateRecu$cpt' value=''>\n";
    }
  }
  echo "</SELECT><BR>\n";
  echo "<INPUT class='input_total_corps police_prop' type='text' readonly name='liste_total' value='&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
  $str_total = Arrondi_5_ct($total);
  $taille_str = strlen($str_total);
  for ($cpt3 = $taille_str; $cpt3 < 9; $cpt3++) {
    $str_total = "&nbsp;" . $str_total;
  }
  echo "$str_total' size=100><BR>\n"; //  style='font-family: Courier, monospace;'
  echo "<input type='hidden' name='Type' value='$Type'>\n";
  echo "<input type='hidden' name='Sous_Type' value='$Sous_Type'>\n";
  echo "<input type='hidden' name='Etape' value='4'>\n";
  echo "<input type='hidden' name='NoCommande' value='$NoCommande'>\n";
  if ($Paye != 'O' || $NotRecep) {
    if ($Mode & 1) {
      echo "<input type='hidden' name='Modif' value='1'>\n";
      echo "<input class='button bt_modifier' type='button' value='Modifier' onclick='edit_tab();'>\n";
      echo "<input class='button bt_up' type='button' value='Up' onclick='move_up();'>\n";
      echo "<input class='button bt_down' type='button' value='Down' onclick='move_down();'>\n";
      echo "<input class='button bt_supprimer' type='button' value='Supprimer' onclick='delete_select();'>\n";
    }
    if ($Mode & 2) {
      echo "<input class='button bt_total_inter' type='button' name='total_intermediaire' value='Sous total' onclick='tot_inter();'>\n";
    }
    if ($Mode & 512) {
      echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type='button' value='Récep comp' onclick='recep_comp();'>\n";
      echo "<input class='button bt_recept_article' type='button' value='Récep article' onclick='recep_art();'>\n";
      echo "<input class='button bt_recept_article_partiel' type='button' value='Récep part' onclick='recep_part();'><input type='text' name='NbPart' size=4>\n";
    }
    echo "</div>\n";
    if ($Mode & 1) {
      echo $tmp_to_add;
    }
    echo "<input type='hidden' name='NoClient' value='$NoClient'>\n";
    echo "<input type='hidden' name='ElementActuel' value='-1'>\n";
    echo "<input type='hidden' name='NbElements' value='$cpt2'>\n";
    echo "<input type='hidden' name='IsCommande' value='";
    if ($Mode & 512)
      echo "1";
    else
      echo "0";
    echo "'>\n";
    echo "<input type='hidden' name='IsAchatMarchandise' value='";
    if ($Mode & 1024)
      echo "1";
    else
      echo "0";
    echo "'>\n";
    if ($Mode & 4) {
      echo "<div class='div_article'>\n";
      echo "<BIG class='titre_bloc'>Article</BIG>\n";
      echo "<input type='hidden' name='Stock' value='0'>\n";
      echo "<TABLE class='table_article' cellspacing='0'>\n";
      echo "<TR class='tr_no_article_description'><TD class='td_label no_article'>Numéro Article</TD><TD class='td_valeur no_article'><input type='texte' name='NoArticle' value='' onkeydown='test_return(event);' onchange='recherche_article_ajax(0);'></TD>\n";
      echo "<script language=JavaScript>\nthis.document.info.NoArticle.focus();\n</script>\n";
      echo "<TD class='td_label description'>Description</TD><TD class='td_valeur description' colspan='3'><input type='texte' size='52' name='Description' value='' onkeydown='test_return();'></TD></TR>\n";
      echo "<TR class='tr_prix_rabais_tva'><TD class='td_label prix'>Prix</TD><TD class='td_valeur prix'><input type='texte' name='Prix' value='' onkeydown='test_return();'></TD>\n";
      echo "<TD class='td_label rabais'>Rabais</TD><TD class='td_valeur rabais'><input type='texte' name='Rabais' value='' onkeydown='test_return();'></TD>\n";
      echo "<TD class='td_label tva'>TVA</TD><TD class='td_valeur tva'><input type='texte' name='TVA' value='' onkeydown='test_return();'></TD></TR>\n";
      echo "<TR class='tr_gm_quantite_dest'><TD class='td_label gm'>Groupe Marchandise</TD><TD class='td_valeur gm'><input type='texte' name='GM' value='' onkeydown='test_return();'></TD>\n";
      echo "<TD class='td_label quantite'>Quantite</TD><TD class='td_valeur quantite'><input type='texte' name='Quantite' value='' onkeydown='enter_quantite(event);'></TD>";
      if ($Mode & 512)
        echo "<TD class='td_label dest'>Dest</TD><TD class='td_valeur dest'><input type='texte' name='Destinataire' value='Stock' onkeydown='test_return();'></TD>";
      else
        echo "<TD colspan='2'>&nbsp;</TD>";
      echo "</TR>\n</TABLE>\n";
      echo "<input class='button bt_ajouter' type='button' value='Ajouter' onclick='add_new(true);' onkeydown='annule_return();'>\n";
      echo "<input class='button bt_effacer' type='button' value='Effacer' onclick='clear_data();' onkeydown='annule_return();'>\n";
      echo "<input class='button bt_modifier' type='button' name='modif_data' value='Modifier' onclick='modif_select();' onkeydown='annule_return();' disabled>\n";
      echo "<input class='button bt_rechercher' type='button' value='Rechercher' onclick='ouvre_recherche_article(0);' onkeydown='annule_return();'>\n";
      /*if($Mode&512)
            echo "<input class='button bt_rechercher' type='button' value='Rechercher' onclick='fenetre_find(1,2,". '"' ."&Detail=3&NoClient=$NoClient". '"' .");' onkeydown='annule_return();'>\n";
          else
            echo "<input class='button bt_rechercher' type='button' value='Rechercher' onclick='fenetre_find(1,2,". '"' ."&Detail=2&NoClient=$NoClient". '"' .");' onkeydown='annule_return();'>\n";*/
      echo "</div>\n";
    } else {
      echo "<input type='hidden' name='NoArticle'>\n";
      echo "<input type='hidden' name='Description'>\n";
      echo "<input type='hidden' name='Prix'>\n";
      echo "<input type='hidden' name='Rabais'>\n";
      echo "<input type='hidden' name='TVA'>\n";
      echo "<input type='hidden' name='GM'>\n";
      echo "<input type='hidden' name='Quantite'>\n";
      echo "<input type='hidden' name='Stock'>\n";
    }
    if ($Mode & 8) {
      echo "<div class='div_texte_libre'>\n";
      echo "<BIG class='titre_bloc'>Texte libre</BIG><BR>\n";
      echo "<textarea class='ta_texte_libre police_prop' cols=91 rows=";
      if ($GLOBALS['size'] == 2) {
        echo "3";
      } else {
        echo "5";
      }
      echo " name='Texte_libre' onkeydown='annule_return();'></textarea><BR>\n"; //  style='font-family: Courier, monospace;'
      echo "<input class='button bt_ajouter' type='button' value='Ajouter' onclick='add_new_text();' onkeydown='annule_return();'>\n";
      echo "<input class='button bt_effacer' type='button' value='Effacer' onclick='clear_texte();' onkeydown='annule_return();'>\n";
      echo "<input class='button bt_modifier' type='button' name='modif_text' value='Modifier' onclick='modif_select_text();' onkeydown='annule_return();' disabled>\n";
      echo "</div>\n";
    }
    if ($Mode & (16 + 128)) {
      echo "<div class='div_vhc_vente'>\n";
      echo "<BIG class='titre_bloc'>Vehicule vente</BIG><BR>\n";
      $requette = "SELECT * FROM vehicules WHERE ";
      if ($Mode & 128)
        $requette .= "Status='O' OR Status='DO'";
      if (($Mode & (16 + 128)) == (16 + 128))
        $requette .= " OR ";
      if ($Mode & 16)
        $requette .= "Status='N' OR Status='DN'";
      $requette .= " ORDER BY MarqueModel, Model, NoChasis";
      $statement = Connection::getStatement($requette);
      $statement->execute();
      $resultat = $statement->fetchAll();
      if ($resultat) {
        echo "<SELECT class='select_vhc_vente' name='liste_vhc_vente'>\n"; //  style='font-family: Courier, monospace;'
        $cpt = 0;
        $tmp_no_cha = "";
        foreach ($resultat as $ligne) {
          $tmp_no_cha .= "<input type='hidden' name='Vhc$cpt' value=" . '"' . $ligne['NoChasis'] . '"' . ">\n";
          $tmp_no_cha .= "<input type='hidden' name='VhcType$cpt' value=" . '"';
          if (($ligne['Status'] == "N") || ($ligne['Status'] == "DN")) {
            $tmp_no_cha .= "N";
          } else {
            $tmp_no_cha .= "O";
          }
          $tmp_no_cha .= '"' . ">\n";
          $NoChasis = $ligne['NoChasis'];
          $NoChasis = aligne_gauche_select($NoChasis, 20);
          $Marque = $ligne['MarqueModel'];
          $Marque = aligne_gauche_select($Marque, 10);
          $Model = $ligne['Model'];
          $Model = aligne_gauche_select($Model, 10);
          $Couleur = $ligne['Couleur'];
          $Couleur = aligne_gauche_select($Couleur, 8);
          $Annee = substr($ligne['DateCircul'], 0, 4);
          $Km = $ligne['Km'];
          $Km = aligne_droite_select($Km, 6);
          switch ($ligne['Status']) {
            case "O":
            case "DO":
              $Status = "Occasion";
              break;
            case "N":
            case "DN":
              $Status = "Neuf";
              break;
          }
          echo "<option value='$cpt'>$NoChasis&nbsp;$Marque&nbsp;$Model&nbsp;$Couleur&nbsp;$Annee&nbsp;$Km&nbsp;$Status</option>\n";
          $cpt++;
        }
        if (empty($NoClient))
          $NoClient = 0;
        if (empty($NoClient2))
          $NoClient2 = 0;
        echo "</SELECT><input class='button bt_vendre' type='button' value='Vendre' onclick='vendre_vhc($NoClient,$NoClient2,$NoCommande," . $GLOBALS['Devis'] . ");'>\n";
        echo "<input type='hidden' value=0 name='WaitVhcVente'>\n";
        echo "<input type='hidden' value='' name='LastVhc'>\n";
        echo $tmp_no_cha;
      }
      echo "</div>\n";
    }
    if ($Mode & 256) {
      echo "<div class='div_vhc_achat'>\n";
      echo "<BIG class='titre_bloc'>Vehicule reprise</BIG><BR>\n";
      echo "NoChâssis<input name='NoChasisAchat' value='' readonly><input class='button bt_rechecher_creer' type='button' value='Rechercher-Créer' onclick='recherche_vhc(2);'><input type='button' value='Acheter' onclick='achat_vhc($NoClient, $NoCommande, " . '"O"' . ");'>";
      echo "</div>\n";
    }
    if ($Mode & 32) {
      echo "<div class='div_bulletin_livraison'>\n";
      echo "<BIG class='titre_bloc'>Bulletin de livraison</BIG><BR>\n";
      $requette = "SELECT * FROM commande" . ID_GARAGE . " WHERE Type='BP' AND Genre='B' AND Paye!='O' AND NoClient=:noclient";
      $statement = Connection::getStatement($requette);
      $statement->bindParam(":noclient", $NoClient);
      $statement->execute();
      $resultat = $statement->fetchAll();
      echo "<SELECT class='select_bulletin_livraison' name='liste_bultin'>\n"; //  style='font-family: Courier, monospace;'
      $tmp_no_bul = "";
      $cpt = 0;
      foreach ($resultat as $ligne) {
        $tmp_no_bul .= "<input type='hidden' name='Bul$cpt' value=" . '"' . $ligne['NoCommande'] . '"' . ">\n";
        $NoCommande2 = $ligne['NoCommande'];
        $NoCommande2 = aligne_droite_select($NoCommande2, 6);
        $MontantTotal = $ligne['MontantTotal'];
        $MontantTotal = aligne_droite_select($MontantTotal, 9);
        echo "<option value='$cpt'>$NoCommande2&nbsp;$MontantTotal&nbsp;" . Cree_Entree_Type("", 2, 0, $ligne['DateModification'], AFFICHAGE) . "</option>";
        $cpt++;
      }
      echo "</SELECT><input class='button bt_importer' type='button' value='Importer' onclick='add_bultin();'>\n";
      echo $tmp_no_bul;
      echo "</div>\n";
    }
    if ($Mode & 64) {
      echo "<div class='div_presse_papier'>\n";
      echo "<BIG class='titre_bloc'>Presse papier</BIG><BR>\n";
      if ($Mode & 512) {
        echo "No fourniseur<input class='no_fourniseur' name='NoCommandeFourniseur' value='" . $NoFourniseur . "'>\n";
      }
      echo "<input class='button bt_copier' type='button' value='Copier' onclick='copyToClipboard();'>\n";
      echo "<input class='button bt_coller' type='button' value='Coller' onclick='pasteFromClipboard();'>\n";
      echo "<input class='input_no_import' type='text' name='NoImport' size=6 readonly>\n";
      echo "<input class='button bt_inserer' type='button' value='Insérer' onclick='insertNoCommande(";
      if ($Mode & 512) {
        echo "1";
      } else {
        echo "0";
      }
      echo ");'>\n<input class='button bt_rechercher' type='button' value='Rechercher' onclick='fenetre_find(14,1," . '"' . "&Cible=NoImport" . '"' . ");'>\n";
      echo "<TEXTAREA ID='FullText' STYLE='position: absolute; top: -1000; left: -1000;'></TEXTAREA>";
      echo "</div>\n";
    }
    if ($Mode != 0) {
      echo "<div class='div_valider'>\n";
      echo "<input type='hidden' value=0 name='Encaisse'>";
      echo "<input class='button bt_valider' type='button' onClick='go_imprime(this.form);' value='Valider' />\n";
      if ($Menu & M_ENC) {
        echo "<input class='button bt_valider_encaisser' type='button' onClick='go_encaisse(this.form);' value='Valider et encaisser' />";
      }
      echo "</div>\n";
    }
  } else {
    echo "</div>\n";
  }
  echo "</form>\n";
  if (As_Right_Fonction(6, 35))
    echo "<BR><input class='button bt_valider' type='button' onclick='valide_supprimer($NoCommande);' value='Supprimer' />";
}

function Update_Coordonnees_Facture($Type, $Genre)
{
  global $NoCommande, $Modif, $New, $NoClient, $NoClient2, $Vendeur, $lg_user, $NoChasis, $Km, $NoPlaque, $DateCommande, $Titre, $FactureAssociee;
  if (isset($Modif) == False) {
    $Modif = 0;
  }
  if (isset($New) == False) {
    $New = 0;
  }
  if ($Modif == 1) {
    if (empty($NoClient)) $NoClient = 0;
    if (empty($NoClient2)) $NoClient2 = 0;
    if (empty($Vendeur)) $Vendeur = 0;
    if (empty($Km)) $Km = 0;
    $FactureSansTexteTVA = 0;
    if (isset($_REQUEST['FactureSansTexteTVA'])) $FactureSansTexteTVA = 1;
    if ($New == 1) {
      if ($NoCommande < 1)
        $NoCommande = Trouve_No_Commande_Libre($Type);

      $noCommandeAssocie = '0';
      if (isset($FactureAssociee) && !empty($FactureAssociee)) {
        $noCommandeAssocie = $FactureAssociee;
      }

      $requette = "INSERT INTO commande" . ID_GARAGE . " (NoFourniseur, IPClient, NoCommande,Type,Genre,Titre,PersonneModif,NoClient,NoClient2,NoCommandeAssocie,Vendeur,Vehicule,KmVhc,NoPlaque,DateCommande,DateSaisie,DateModification,DateDelaisPayement,FactureSansTexteTVA) VALUES " .
        "('','', $NoCommande, '$Type', '$Genre', '" . addslashes($Titre) . "', '$lg_user', '$NoClient', '$NoClient2', $noCommandeAssocie, '$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"))) . "', $FactureSansTexteTVA)";
    } else {
      $Version = Commande::getVersionByNoCommande($NoCommande);
      $Version += 1;
      $IPClient = $_SERVER["REMOTE_ADDR"];
      $requette = "UPDATE commande" . ID_GARAGE . " SET Type='$Type', Genre='$Genre', Titre='" . addslashes($Titre) . "', PersonneModif='$lg_user', NoClient='$NoClient', NoClient2='$NoClient2', NoCommandeAssocie='$FactureAssociee', Vendeur='$Vendeur', Vehicule='" . addslashes($NoChasis) . "', KmVhc='$Km', NoPlaque='$NoPlaque', DateModification='" . date("Y-m-d") . "', Version=$Version, IPClient='$IPClient', FactureSansTexteTVA=$FactureSansTexteTVA WHERE NoCommande='$NoCommande'";
    }
    $resultat = Connection::executeRawQuery($requette);

    if ($resultat) {
      if (!empty($NoChasis)) {
        if ($ligne = Vehicule::getVehiculeByNoChassis(addslashes($NoChasis))) {
          if ($Km > $ligne['Km']) {
            $requette = "UPDATE vehicules SET Km='$Km' WHERE NoChasis=:nochasis";
            $statementUpdate = Connection::getStatement($requette);
            $chassis = addslashes($NoChasis);
            $statementUpdate->bindParam(":nochasis", $chassis);
            $statementUpdate->execute();
          }
        }
      }
    } else {
      echo "KO $requette <BR>\n";
    }
  } else {
    $ligne = Commande::getCommandeByNoCommande($NoCommande);
    $NoClient = $ligne['NoClient'];
    $NoClient2 = $ligne['NoClient2'];
    $NoChasis = $ligne['Vehicule'];
  }
}

function Affiche_Facture($Type, $Genre, $Mode, $Menu)
{
  global $NoCommande, $Modif, $New, $NoClient, $NoClient2, $Vendeur, $lg_user, $NoChasis, $Km, $NoPlaque, $DateCommande;
  Select_Etape_Facture($NoCommande, $NoClient, $NoClient2, $Menu);
  Create_Articles_Facture_newfact($NoCommande, $NoClient, $Mode, $Menu);
}

function Maj_Commande_Articles($NoCommande, $Mode = 0)
{
  // Mode 0 ne modifie pas le stock
  // Mode 1 modifie le stock retrais
  // Mode 2 modifie le stock ajout
  // Mode 3 modifie le stock ajout selon recep
  if ($Mode == 3) {
    $recu_tout = true;
  }
  if ($Mode != 0) {
    $array_article_prec = array();
    $resultat = CommandeArticle::getCommandeArticleByNoCommande($NoCommande);;
    if ($resultat) {
      foreach ($resultat as $ligne) {
        if (!empty($ligne['NoArticle'])) {
          $noArticleRR = Texte_Sans_Espace($ligne['NoArticle']);
          if (array_key_exists($noArticleRR, $array_article_prec)) {
            $array_article_prec[$noArticleRR] = $ligne['Quantite'];
          } else {
            $array_article_prec[$noArticleRR] = $array_article_prec[$noArticleRR] + $ligne['Quantite'];
          }
          $requette_existe_stock = "SELECT * FROM stock" . ID_GARAGE . " WHERE NoArticleRR = :noarticlerr";
          $statementExistStock = Connection::getStatement($requette_existe_stock);
          $statementExistStock->bindParam(":noarticlerr", addslashes($noArticleRR));
          $statementExistStock->execute();
          if ($Mode == 1) {
            if ($statementExistStock->fetch()) { // UPDATE
              $requette2 = "UPDATE stock" . ID_GARAGE . " SET EnStock = EnStock + (" . $ligne['Quantite'] . ") WHERE NoArticleRR = '" . addslashes($noArticleRR) . "'";
            } else { // INSERT
              $requette2 = "INSERT INTO stock" . ID_GARAGE . " (`NoArticleRR` ,`LieuxStock` ,`EnStock` ,`EnTransfert`) VALUES ('" . addslashes($noArticleRR) . "', NULL , +(" . $ligne['Quantite'] . "), 0);";
            }
          }
          if ($Mode == 2) {
            if ($statementExistStock->fetch()) { // UPDATE
              $requette2 = "UPDATE stock" . ID_GARAGE . " SET EnStock = EnStock - (" . $ligne['Quantite'] . ") WHERE NoArticleRR = '" . addslashes($noArticleRR) . "'";
            } else { // INSERT
              $requette2 = "INSERT INTO stock" . ID_GARAGE . " (`NoArticleRR` ,`LieuxStock` ,`EnStock` ,`EnTransfert`) VALUES ('" . addslashes($noArticleRR) . "', NULL , -(" . $ligne['Quantite'] . "), 0);";
            }
          }
          if ($Mode == 3) {
            if ($statementExistStock->fetch()) { // UPDATE
              $requette2 = "UPDATE stock" . ID_GARAGE . " SET EnStock = EnStock - (" . $ligne['NbRecu'] . "), EnTransfert = EnTransfert - (" . ($ligne['Quantite'] - $ligne['NbRecu']) . ") WHERE NoArticleRR = '" . addslashes($noArticleRR) . "'";
            } else { // INSERT
              $requette2 = "INSERT INTO stock" . ID_GARAGE . " (`NoArticleRR` ,`LieuxStock` ,`EnStock` ,`EnTransfert`) VALUES ('" . addslashes($noArticleRR) . "', NULL , -(" . $ligne['NbRecu'] . "), - (" . ($ligne['Quantite'] - $ligne['NbRecu']) . "));";
            }
          }
          $statement = Connection::getStatement($requette2);
          $statement->execute();
          if ($Mode == 1) {
            /*$requette2 = "SELECT * FROM articles WHERE  NoArticle = '" . addslashes($ligne['NoArticle']) . "'";
              if($resultat2 = mysql_query($requette2))
              {
                if($ligne2 = mysql_fetch_array($resultat2))
                {
                  if($ligne2['Annee1']==date("Y"))
                  {
                    $requette3 = "UPDATE articles SET NombreVendu1 = NombreVendu1 - (" . $ligne['Quantite'] . "), SommeVendu1 = SommeVendu1 - (" . $ligne['PrixMulti'] . ") WHERE NoArticle = '" . addslashes($ligne['NoArticle']) . "'";
                    $resultat3 = mysql_query($requette3);
                  }
                  else if($ligne2['Annee2']==date("Y"))
                  {
                    $requette3 = "UPDATE articles SET NombreVendu2 = NombreVendu2 - (" . $ligne['Quantite'] . "), SommeVendu2 = SommeVendu2 - (" . $ligne['PrixMulti'] . ") WHERE NoArticle = '" . addslashes($ligne['NoArticle']) . "'";
                    $resultat3 = mysql_query($requette3);
                  }
                  else if($ligne2['Annee3']==date("Y"))
                  {
                    $requette3 = "UPDATE articles SET NombreVendu3 = NombreVendu3 - (" . $ligne['Quantite'] . "), SommeVendu3 = SommeVendu3 - (" . $ligne['PrixMulti'] . ") WHERE NoArticle = '" . addslashes($ligne['NoArticle']) . "'";
                    $resultat3 = mysql_query($requette3);
                  }
                }
              }*/
          }
          if ($Mode == 2) {
            /*$requette2 = "SELECT * FROM articles WHERE  NoArticle = '" . addslashes($ligne['NoArticle']) . "'";
              if($resultat2 = mysql_query($requette2))
              {
                if($ligne2 = mysql_fetch_array($resultat2))
                {
                  if($ligne2['Annee1']==date("Y"))
                  {
                    $requette3 = "UPDATE articles SET NombreVendu1 = NombreVendu1 + (" . $ligne['Quantite'] . "), SommeVendu1 = SommeVendu1 + (" . $ligne['PrixMulti'] . ") WHERE NoArticle = '" . addslashes($ligne['NoArticle']) . "'";
                    $resultat3 = mysql_query($requette3);
                  }
                  else if($ligne2['Annee2']==date("Y"))
                  {
                    $requette3 = "UPDATE articles SET NombreVendu2 = NombreVendu2 + (" . $ligne['Quantite'] . "), SommeVendu2 = SommeVendu2 + (" . $ligne['PrixMulti'] . ") WHERE NoArticle = '" . addslashes($ligne['NoArticle']) . "'";
                    $resultat3 = mysql_query($requette3);
                  }
                  else if($ligne2['Annee3']==date("Y"))
                  {
                    $requette3 = "UPDATE articles SET NombreVendu3 = NombreVendu3 + (" . $ligne['Quantite'] . "), SommeVendu3 = SommeVendu3 + (" . $ligne['PrixMulti'] . ") WHERE NoArticle = '" . addslashes($ligne['NoArticle']) . "'";
                    $resultat3 = mysql_query($requette3);
                  }
                }
              }*/
          }
        }
      }
    }
  }
  $requette = "DELETE FROM commandearticles" . ID_GARAGE . " WHERE NoCommande=:nocommande";
  $statement = Connection::getStatement($requette);
  $statement->bindParam(":nocommande", $NoCommande);
  $statement->execute();
  for ($cpt = 0; $cpt < $GLOBALS['NbElements']; $cpt++) {
    $prix_multi = $GLOBALS["MemQuantite" . $cpt] * $GLOBALS["MemPrix" . $cpt] * ((100 + $GLOBALS["MemRabais" . $cpt]) / 100);
    if ($GLOBALS["MemTVA" . $cpt] > 0) {
      $prix_multi = $prix_multi * ((100 + $GLOBALS["MemTVA" . $cpt]) / 100);
    }
    if ($Mode == 3) {
      $prix_multi = Arrondi_1_ct($prix_multi);
    } else {
      $prix_multi = Arrondi_5_ct($prix_multi);
    }
    $requette = "INSERT INTO commandearticles" . ID_GARAGE . " (NoCommande, Position, TypeData, NoArticle, Description, TVA, GM, Quantite, PrixBase, Rabais, PrixMulti";
    if ($Mode == 3) {
      $requette .= ", NbRecu, DateRecu, Dest";
    }
    $requette .= ") VALUES (" .
      "$NoCommande, " . ($cpt + 1) . ", " . $GLOBALS["MemTypeData" . $cpt] . ", '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "', '" . addslashes($GLOBALS["MemDescription" . $cpt]) .
      "', " . Arrondi_5_ct($GLOBALS["MemTVA" . $cpt]) . ", " . Min_zero($GLOBALS["MemGM" . $cpt]) . ", " . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", " . Arrondi_5_ct($GLOBALS["MemPrix" . $cpt]) . ", " . Arrondi_1_ct($GLOBALS["MemRabais" . $cpt]) . ", " .
      $prix_multi;
    if ($Mode == 3) {
      $requette .= ", " . Min_zero($GLOBALS["MemNbRecu" . $cpt]) . ", '" . $GLOBALS["MemDateRecu" . $cpt] . "', '" . addslashes($GLOBALS["MemDest" . $cpt]) . "'";
      if ($GLOBALS["MemNbRecu" . $cpt] != $GLOBALS["MemQuantite" . $cpt]) {
        $recu_tout = false;
      }
    }
    $requette .= ")";
    $statement = Connection::getStatement($requette);
    if ($statement->execute()) {
    } else {
      echo "KO<BR>\n";
    }
    if ($Mode != 0) {
      if (!empty($GLOBALS["MemNoArticle" . $cpt])) {
        $noArticleRR = Texte_Sans_Espace($GLOBALS["MemNoArticle" . $cpt]);
        $requette_existe_stock = "SELECT * FROM stock" . ID_GARAGE . " WHERE NoArticleRR = :noarticlerr";
        $statementExistStock = Connection::getStatement($requette_existe_stock);
        $statementExistStock->bindParam(":noarticlerr", addslashes($noArticleRR));
        $statementExistStock->execute();
        if ($Mode == 1) {
          if ($statementExistStock->fetch()) { // UPDATE
            $requette2 = "UPDATE stock" . ID_GARAGE . " SET EnStock = EnStock - (" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ") WHERE NoArticleRR = '" . addslashes($noArticleRR) . "'";
          } else { // INSERT
            $requette2 = "INSERT INTO stock" . ID_GARAGE . " (`NoArticleRR` ,`LieuxStock` ,`EnStock` ,`EnTransfert`) VALUES ('" . addslashes($noArticleRR) . "', NULL , -(" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . "), 0);";
          }
        }
        if ($Mode == 2) {
          if ($statementExistStock->fetch()) { // UPDATE
            $requette2 = "UPDATE stock" . ID_GARAGE . " SET EnStock = EnStock + (" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ") WHERE NoArticleRR = '" . addslashes($noArticleRR) . "'";
          } else { // INSERT
            $requette2 = "INSERT INTO stock" . ID_GARAGE . " (`NoArticleRR` ,`LieuxStock` ,`EnStock` ,`EnTransfert`) VALUES ('" . addslashes($noArticleRR) . "', NULL , +(" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . "), 0);";
          }
        }
        if ($Mode == 3) {
          if ($statementExistStock->fetch()) { // UPDATE
            $requette2 = "UPDATE stock" . ID_GARAGE . " SET EnStock = EnStock + (" . Arrondi_1_ct($GLOBALS["MemNbRecu" . $cpt]) . "), EnTransfert = EnTransfert + (" . (Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) - Arrondi_1_ct($GLOBALS["MemNbRecu" . $cpt])) . ") WHERE NoArticleRR = '" . addslashes($noArticleRR) . "'";
          } else { // INSERT
            $requette2 = "INSERT INTO stock" . ID_GARAGE . " (`NoArticleRR` ,`LieuxStock` ,`EnStock` ,`EnTransfert`) VALUES ('" . addslashes($noArticleRR) . "', NULL , +(" . Arrondi_1_ct($GLOBALS["MemNbRecu" . $cpt]) . "), + (" . (Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) - Arrondi_1_ct($GLOBALS["MemNbRecu" . $cpt])) . "));";
          }
        }
        $statement = Connection::getStatement($requette2);
        $statement->execute();
        if ($Mode == 1) {
          /*$requette2 = "SELECT * FROM articles WHERE  NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
            if($resultat2 = mysql_query($requette2))
            {
              if($ligne2 = mysql_fetch_array($resultat2))
              {
                if($ligne2['Annee1']==date("Y"))
                {
                  $requette3 = "UPDATE articles SET NombreVendu1 = NombreVendu1 + (" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . "), SommeVendu1 = SommeVendu1 + (" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ") WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee2']==date("Y"))
                {
                  $requette3 = "UPDATE articles SET NombreVendu2 = NombreVendu2 + (" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . "), SommeVendu2 = SommeVendu2 + (" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ") WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee3']==date("Y"))
                {
                  $requette3 = "UPDATE articles SET NombreVendu3 = NombreVendu3 + (" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . "), SommeVendu3 = SommeVendu3 + (" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ") WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee1']==0)
                {
                  $requette3 = "UPDATE articles SET NombreVendu1 = " . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", SommeVendu1 = " . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ", Annee1 = ".date("Y")." WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee2']==0)
                {
                  $requette3 = "UPDATE articles SET NombreVendu2 = " . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", SommeVendu2 = " . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ", Annee2 = ".date("Y")." WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee3']==0)
                {
                  $requette3 = "UPDATE articles SET NombreVendu3 = " . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", SommeVendu3 = " . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ", Annee3 = ".date("Y")." WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else
                {
                  $requette3 = "UPDATE articles SET Annee1 = Annee2, NombreVendu1 = NombreVendu2, SommeVendu1 = SommeVendu2, Annee2 = Annee3, NombreVendu2 = NombreVendu3, SommeVendu2 = SommeVendu3, NombreVendu3 = " . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", SommeVendu3 = " . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ", Annee3 = ".date("Y")." WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                $resultat3 = mysql_query($requette3);
              }
            }*/
        }
        if ($Mode == 2) {
          /*$requette2 = "SELECT * FROM articles WHERE  NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
            if($resultat2 = mysql_query($requette2))
            {
              if($ligne2 = mysql_fetch_array($resultat2))
              {
                if($ligne2['Annee1']==date("Y"))
                {
                  $requette3 = "UPDATE articles SET NombreVendu1 = NombreVendu1 - (" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . "), SommeVendu1 = SommeVendu1 - (" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ") WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee2']==date("Y"))
                {
                  $requette3 = "UPDATE articles SET NombreVendu2 = NombreVendu2 - (" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . "), SommeVendu2 = SommeVendu2 - (" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ") WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee3']==date("Y"))
                {
                  $requette3 = "UPDATE articles SET NombreVendu3 = NombreVendu3 - (" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . "), SommeVendu3 = SommeVendu3 - (" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ") WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee1']==0)
                {
                  $requette3 = "UPDATE articles SET NombreVendu1 = -" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", SommeVendu1 = -" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ", Annee1 = ".date("Y")." WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee2']==0)
                {
                  $requette3 = "UPDATE articles SET NombreVendu2 = -" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", SommeVendu2 = -" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ", Annee2 = ".date("Y")." WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee3']==0)
                {
                  $requette3 = "UPDATE articles SET NombreVendu3 = -" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", SommeVendu3 = -" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ", Annee3 = ".date("Y")." WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else
                {
                  $requette3 = "UPDATE articles SET Annee1 = Annee2, NombreVendu1 = NombreVendu2, SommeVendu1 = SommeVendu2, Annee2 = Annee3, NombreVendu2 = NombreVendu3, SommeVendu2 = SommeVendu3, NombreVendu3 = -" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", SommeVendu3 = -" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ", Annee3 = ".date("Y")." WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                $resultat3 = mysql_query($requette3);
              }
            }*/
        }
      }
    }
  }
  if ($Mode == 3) {
    $requette = "UPDATE commande" . ID_GARAGE . " SET Recu='";
    if ($recu_tout) {
      $requette .= "O";
    } else {
      $requette .= "N";
    }
    $requette .= "' WHERE NoCommande=:nocommande";
    $statement = Connection::getStatement($requette);
    $statement->bindParam(":nocommande", $NoCommande);
    $statement->execute();
  }
}

function Maj_Commande_Somme($NoCommande, $Mode = 0, $tot = True)
{
  $somme = 0.0;
  $somme2 = 0.0;
  for ($cpt = 0; $cpt < $GLOBALS['NbElements']; $cpt++) {
    if ($GLOBALS["MemTypeData" . $cpt] == 0 || $GLOBALS["MemTypeData" . $cpt] == 4) {
      $prix_multi = $GLOBALS["MemQuantite" . $cpt] * $GLOBALS["MemPrix" . $cpt] * ((100 + $GLOBALS["MemRabais" . $cpt]) / 100);
      if ($GLOBALS["MemTVA" . $cpt] > 0) {
        $prix_multi = $prix_multi * ((100 + $GLOBALS["MemTVA" . $cpt]) / 100);
      }
      if ($Mode == 3) {
        $prix_multi2 = $GLOBALS["MemNbRecu" . $cpt] * $GLOBALS["MemPrix" . $cpt] * ((100 + $GLOBALS["MemRabais" . $cpt]) / 100);
        if ($GLOBALS["MemTVA" . $cpt] > 0) {
          $prix_multi2 = $prix_multi2 * ((100 + $GLOBALS["MemTVA" . $cpt]) / 100);
        }
        $prix_multi = Arrondi_1_ct($prix_multi);
        $prix_multi2 = Arrondi_1_ct($prix_multi2);
        $somme2 += $prix_multi2;
      } else {
        $prix_multi = Arrondi_5_ct($prix_multi);
      }
      $somme += $prix_multi;
    }
  }
  $somme = Arrondi_5_ct($somme);
  $ligne = Commande::getCommandeByNoCommande($NoCommande);
  $sommeold = $ligne['MontantTotal'];
  $apayerold = $ligne['APayer'];
  $apayer = $apayerold + ($somme - $sommeold);
  if ($tot) {
    $requette = "UPDATE commande" . ID_GARAGE . " SET MontantTotal=:somme, APayer=$apayer WHERE NoCommande=:nocommande";
  } else {
    $requette = "UPDATE commande" . ID_GARAGE . " SET MontantTotal=:somme, APayer=0 WHERE NoCommande=:nocommande";
  }

  $statement = Connection::getStatement($requette);
  $statement->bindParam(":somme", $somme);
  $statement->bindParam(":nocommande", $NoCommande);
  $statement->execute();

  if ($Mode == 3) {
    if (!empty($GLOBALS['NoCommandeFourniseur'])) {
      echo "No fourniseur " . $GLOBALS['NoCommandeFourniseur'] . "<BR>\n";
    }
    $somme2old = $ligne['SommeFourniseur'];
    $diff = $somme2 - $somme2old;
    $requette = "UPDATE commande" . ID_GARAGE . " SET SommeFourniseur=:somme, NoFourniseur=:nofournisseur WHERE NoCommande=:nocommande";
    $statement = Connection::getStatement($requette);
    $statement->bindParam(":somme", $somme2);
    $noFourn = addslashes($GLOBALS['NoCommandeFourniseur']);
    $statement->bindParam(":nofournisseur", $noFourn);
    $statement->bindParam(":nocommande", $NoCommande);
    $statement->execute();
    $requette2 = "SELECT * FROM fourniseur WHERE NoFourniseur=:noclient";
    $statement2 = Connection::getStatement($requette2);
    $statement2->bindParam(":noclient", $ligne['NoClient']);
    $statement2->execute();
    if ($statement2->fetch()) {
      $requette = "UPDATE fourniseur SET Montant = Montant + $diff WHERE NoFourniseur=:noclient";
    } else {
      $requette = "INSERT INTO fourniseur (NoFourniseur, Montant) VALUES (:noclient, $diff)";
    }
    $statement = Connection::getStatement($requette);
    $statement->bindParam(":noclient", $ligne['NoClient']);
    $statement->execute();
  }
}

function Maj_Commande_Somme_newfact($NoCommande, $Mode = 0, $tot = True)
{
  $requette = "SELECT SUM(PrixMulti) FROM commandearticles" . ID_GARAGE . " WHERE NoCommande=:nocommande AND TypeData IN (0,4)";
  $statement = Connection::getStatement($requette);
  $statement->bindParam(":nocommande", $NoCommande);
  $statement->execute();
  $ligne = $statement->fetch();
  $somme = Arrondi_5_ct($ligne[0]);
  $ligne = Commande::getCommandeByNoCommande($NoCommande);
  $sommeold = $ligne['MontantTotal'];
  $apayerold = $ligne['APayer'];
  $apayer = $apayerold + ($somme - $sommeold);
  $Version = Commande::getVersionByNoCommande($NoCommande);
  $Version += 1;
  $IPClient = $_SERVER["REMOTE_ADDR"];

  $requette = "UPDATE commande" . ID_GARAGE . " SET MontantTotal=:somme, APayer=:apayer, Version=:version, IPClient=:ip WHERE NoCommande=:nocommande";
  $statement = Connection::getStatement($requette);
  $statement->bindParam(":somme", $somme);
  if ($tot) {
    $statement->bindParam(":apayer", $apayer);
  } else {
    $statement->bindParam(":apayer", 0);
  }
  $statement->bindParam(":version", $Version);
  $statement->bindParam(":ip", $IPClient);
  $statement->bindParam(":nocommande", $NoCommande);
  $statement->execute();
  if ($Mode == 3) {
    $somme2 = 0;
    $resultat2 = CommandeArticle::getCommandeArticleByNoCommande($NoCommande);;
    foreach ($resultat2 as $ligne2) {
      $prix_multi2 = $ligne2["NbRecu"] * $ligne2["PrixBase"] * ((100 + $ligne2["Rabais"]) / 100);
      if ($ligne2["TVA"] > 0) {
        $prix_multi2 = $prix_multi2 * ((100 + $ligne2["TVA"]) / 100);
      }
      $somme2 += Arrondi_1_ct($prix_multi2);
    }
    if (!empty($GLOBALS['NoCommandeFourniseur'])) {
      echo "No fourniseur " . $GLOBALS['NoCommandeFourniseur'] . "<BR>\n";
    }
    $somme2old = $ligne['SommeFourniseur'];
    $diff = $somme2 - $somme2old;
    $requette = "UPDATE commande" . ID_GARAGE . " SET SommeFourniseur=:somme, NoFourniseur=:nofournisseur WHERE NoCommande=:nocommande";
    $statement = Connection::getStatement($requette);
    $statement->bindParam(":somme", $somme2);
    $noFournisseur = addslashes($GLOBALS['NoCommandeFourniseur']);
    $statement->bindParam(":nofournisseur", $noFournisseur);
    $statement->bindParam(":nocommande", $NoCommande);
    $statement->execute();
    $requette2 = "SELECT * FROM fourniseur WHERE NoFourniseur=:nofournisseur";
    $statement2 = Connection::getStatement($requette2);
    $statement2->bindParam(":nofournisseur", $ligne['NoClient']);
    $statement2->execute();
    if ($ligne = $statement2->fetch()) {
      $requette = "UPDATE fourniseur SET Montant = Montant + $diff WHERE NoFourniseur=:noclient";
    } else {
      $requette = "INSERT INTO fourniseur (NoFourniseur, Montant) VALUES (:noclient, $diff)";
    }
    $statement = Connection::getStatement($requette);
    $statement->bindParam(":noclient", $ligne['NoClient']);
    $statement->execute();
  }
}

function Gestion_Impression($NoCommande, $Options)
{
  echo "<table border=1>\n";
  echo "<tr><th>mode</th><th>client</th><th>avec no d'article</th><th>sans no d'article</th></tr>\n";
  echo "<tr><th rowspan=2>Direct</th><th>client1</th><td><form action='print.php' target='_blank' rel='opener'>\n";
  echo " <input type='hidden' name='Type' value='1'>\n";
  echo " <input type='hidden' name='Sous_Type' value='1'>\n";
  echo " <input type='hidden' name='NoCommande' value='$NoCommande'>\n";
  echo " <input type='hidden' name='NoArticle' value='1'>\n";
  echo " <input type='hidden' name='NoClient' value='1'>\n";
  echo " <input type='hidden' name='Direct' value='1'>\n";
  echo " <button type='submit'>Imprimer</button>";
  echo "</form></td>\n";
  echo "<td><form action='print.php' target='_blank' rel='opener'>\n";
  echo " <input type='hidden' name='Type' value='1'>\n";
  echo " <input type='hidden' name='Sous_Type' value='1'>\n";
  echo " <input type='hidden' name='NoCommande' value='$NoCommande'>\n";
  echo " <input type='hidden' name='NoArticle' value='0'>\n";
  echo " <input type='hidden' name='NoClient' value='1'>\n";
  echo " <input type='hidden' name='Direct' value='1'>\n";
  echo " <button class=case3 type='submit'>Imprimer</button>";
  echo "</form></td></tr>\n";
  echo "<tr><th>client2</th><td><form action='print.php' target='_blank'>\n";
  echo " <input type='hidden' name='Type' value='1'>\n";
  echo " <input type='hidden' name='Sous_Type' value='1'>\n";
  echo " <input type='hidden' name='NoCommande' value='$NoCommande'>\n";
  echo " <input type='hidden' name='NoArticle' value='1'>\n";
  echo " <input type='hidden' name='NoClient' value='2'>\n";
  echo " <input type='hidden' name='Direct' value='1'>\n";
  echo " <button type='submit'>Imprimer</button>";
  echo "</form></td>\n";
  echo "<td><form action='print.php' target='_blank' rel='opener'>\n";
  echo " <input type='hidden' name='Type' value='1'>\n";
  echo " <input type='hidden' name='Sous_Type' value='1'>\n";
  echo " <input type='hidden' name='NoCommande' value='$NoCommande'>\n";
  echo " <input type='hidden' name='NoArticle' value='0'>\n";
  echo " <input type='hidden' name='NoClient' value='2'>\n";
  echo " <input type='hidden' name='Direct' value='1'>\n";
  echo " <button type='submit'>Imprimer</button>";
  echo "</form></td></tr>\n";
  echo "<tr><th rowspan=2>Ecran</th><th>client1</th><td><form action='print.php' target='_blank' rel='opener'>\n";
  echo " <input type='hidden' name='Type' value='1'>\n";
  echo " <input type='hidden' name='Sous_Type' value='1'>\n";
  echo " <input type='hidden' name='NoCommande' value='$NoCommande'>\n";
  echo " <input type='hidden' name='NoArticle' value='1'>\n";
  echo " <input type='hidden' name='NoClient' value='1'>\n";
  echo " <input type='hidden' name='Direct' value='0'>\n";
  echo " <button type='submit'>Imprimer</button>";
  echo "</form></td>\n";
  echo "<td><form action='print.php' target='_blank' rel='opener'>\n";
  echo " <input type='hidden' name='Type' value='1'>\n";
  echo " <input type='hidden' name='Sous_Type' value='1'>\n";
  echo " <input type='hidden' name='NoCommande' value='$NoCommande'>\n";
  echo " <input type='hidden' name='NoArticle' value='0'>\n";
  echo " <input type='hidden' name='NoClient' value='1'>\n";
  echo " <input type='hidden' name='Direct' value='0'>\n";
  echo " <button type='submit'>Imprimer</button>";
  echo "</form></td></tr>\n";
  echo "<tr><th>client2</th><td><form action='print.php' target='_blank' rel='opener'>\n";
  echo " <input type='hidden' name='Type' value='1'>\n";
  echo " <input type='hidden' name='Sous_Type' value='1'>\n";
  echo " <input type='hidden' name='NoCommande' value='$NoCommande'>\n";
  echo " <input type='hidden' name='NoArticle' value='1'>\n";
  echo " <input type='hidden' name='NoClient' value='2'>\n";
  echo " <input type='hidden' name='Direct' value='0'>\n";
  echo " <button type='submit'>Imprimer</button>";
  echo "</form></td>\n";
  echo "<td><form action='print.php' target='_blank' rel='opener'>\n";
  echo " <input type='hidden' name='Type' value='1'>\n";
  echo " <input type='hidden' name='Sous_Type' value='1'>\n";
  echo " <input type='hidden' name='NoCommande' value='$NoCommande'>\n";
  echo " <input type='hidden' name='NoArticle' value='0'>\n";
  echo " <input type='hidden' name='NoClient' value='2'>\n";
  echo " <input type='hidden' name='Direct' value='0'>\n";
  echo " <button type='submit'>Imprimer</button>";
  echo "</form></td></tr>\n";
  echo "<tr><th>Ticket</th><td>&nbsp;</td><td><form action='print_ticket.php' target='_blank' rel='opener'>\n";
  echo " <input type='hidden' name='NoCommande' value='$NoCommande'>\n";
  echo " <input type='hidden' name='NoArticle' value='1'>\n";
  echo " <button type='submit'>Imprimer</button>";
  echo "</form></td><td><form action='print_ticket.php' target='_blank' rel='opener'>\n";
  echo " <input type='hidden' name='NoCommande' value='$NoCommande'>\n";
  echo " <input type='hidden' name='NoArticle' value='0'>\n";
  echo " <button type='submit'>Imprimer</button>";
  echo "</form></td></tr>";
  if ($Options & 1) {
    echo "<tr><th>Vente</th><td>&nbsp;</td><td><form action='print.php' target='_blank'>\n";
    echo " <input type='hidden' name='Type' value='2'>\n";
    echo " <input type='hidden' name='Sous_Type' value='1'>\n";
    echo " <input type='hidden' name='NoCommande' value='$NoCommande'>\n";
    echo " <input type='hidden' name='NoArticle' value='1'>\n";
    echo " <input type='hidden' name='NoClient' value='1'>\n";
    echo " <input type='hidden' name='Direct' value='0'>\n";
    echo " <button type='submit'>Imprimer</button>";
    echo "</form></td><td><form action='print.php' target='_blank'>\n";
    echo " <input type='hidden' name='Type' value='2'>\n";
    echo " <input type='hidden' name='Sous_Type' value='1'>\n";
    echo " <input type='hidden' name='NoCommande' value='$NoCommande'>\n";
    echo " <input type='hidden' name='NoArticle' value='0'>\n";
    echo " <input type='hidden' name='NoClient' value='1'>\n";
    echo " <input type='hidden' name='Direct' value='0'>\n";
    echo " <button type='submit'>Imprimer</button>";
    echo "</form></td></tr>";
  }
  echo "</table>\n";
}

function Maj_Facture($Mode, $tot)
{
  // Mode 0 ne modifie pas le stock
  // Mode 1 modifie le stock retrais
  // Mode 2 modifie le stock ajout
  // Mode 3 modifie le stock ajout selon recep
  global $Modif, $NoCommande, $NoClient, $NoClient2, $Type, $Sous_Type, $Etape, $lg_user, $Encaisse, $Duplique;
  Maj_Facture_newfact($Mode, $tot);
  return;
  if (isset($Modif) == False) {
    $Modif = 0;
  }
  if ($Modif == 1) {
    Maj_Commande_Articles($NoCommande, $Mode);
    Maj_Commande_Somme($NoCommande, $Mode, $tot);
    $requette = "UPDATE commande" . ID_GARAGE . " SET PersonneModif=:lguser, DateModification=:date WHERE NoCommande=:nocommande";
    $statement = Connection::getStatement($requette);
    $statement->bindParam(":lguser", $lg_user);
    $statement->bindParam(":date", date("Y-m-d"));
    $statement->bindParam(":nocommande", $NoCommande);
    $statement->execute();
    if ($Encaisse == 1) {
      echo "encaisse<BR>\n";
      echo "<script language=JavaScript>\n";
      echo "window.location.href='default.php?Type=$Type&Sous_Type=$Sous_Type&Etape=5&NoCommande=$NoCommande&NoClient=$NoClient&NoClient2=$NoClient2';\n";
      echo "</script>\n";
    }
  }
}

function Maj_Facture_newfact($Mode, $tot)
{
  // Mode 0 ne modifie pas le stock
  // Mode 1 modifie le stock retrais
  // Mode 2 modifie le stock ajout
  // Mode 3 modifie le stock ajout selon recep
  global $Modif, $NoCommande, $NoClient, $NoClient2, $Type, $Sous_Type, $Etape, $lg_user, $Encaisse, $Duplique, $Commantaire;
  if (isset($Modif) == False) {
    $Modif = 0;
  }
  if ($Modif == 1) {
    Maj_Commande_Articles_newfact($NoCommande, $Mode);
    Maj_Commande_Somme_newfact($NoCommande, $Mode, $tot);
    $requette = "UPDATE commande" . ID_GARAGE . " SET PersonneModif=:lguser, DateModification=:date, Titre=:titre, Commantaire=:commentaire WHERE NoCommande=:nocommande";
    $statement = Connection::getStatement($requette);
    $statement->bindParam(":lguser", $lg_user);
    $date = date("Y-m-d");
    $titre = addslashes($GLOBALS["titre_commande"]);
    $commentaire = addslashes($GLOBALS["Commantaire"]);
    $statement->bindParam(":date", $date);
    $statement->bindParam(":titre", $titre);
    $statement->bindParam(":commentaire", $commentaire);
    $statement->bindParam(":nocommande", $NoCommande);
    $statement->execute();
    if ($Encaisse == 1) {
      echo "encaisse<BR>\n";
      echo "<script language=JavaScript>\n";
      echo "window.location.href='default.php?Type=$Type&Sous_Type=$Sous_Type&Etape=5&NoCommande=$NoCommande&NoClient=$NoClient&NoClient2=$NoClient2';\n";
      echo "</script>\n";
    }
    if ($Duplique == 1) {
      $NoCommande2 = Duplique_Facture($NoCommande, $Mode);
      Maj_Commande_Somme_newfact($NoCommande2);
      echo "<script language=JavaScript>\n";
      echo "window.location.href='default.php?Type=$Type&Sous_Type=$Sous_Type&Etape=3&NoCommande=$NoCommande2&NoClient=$NoClient&NoClient2=$NoClient2';\n";
      echo "</script>\n";
    }
  }
}

function Duplique_Facture($NoCommande, $Mode)
{
  if ($ligne1 = Commande::getCommandeByNoCommande($NoCommande)) {
    $NoCommandeNew = Trouve_No_Commande_Libre($ligne1["Type"]);
    $requette2 = "INSERT INTO commande" . ID_GARAGE . " (NoCommande,Type,Genre,PersonneModif,NoClient,NoClient2,Vendeur,Vehicule,KmVhc,NoPlaque,DateCommande,DateSaisie,DateModification,DateDelaisPayement,FactureSansTexteTVA) VALUES " .
      "($NoCommandeNew, '" . $ligne1["Type"] . "', '" . $ligne1["Genre"] . "', '" . addslashes($ligne1["PersonneModif"]) . "', '" . $ligne1["NoClient"] . "', '" . $ligne1["NoClient2"] . "', '" . addslashes($ligne1["Vendeur"]) . "','" . $ligne1["Vehicule"] . "', '" . $ligne1["KmVhc"] . "', '" . addslashes($ligne1["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"))) . "', " . $ligne1["FactureSansTexteTVA"] . ")";
    echo $requette2 . "<br>";
    Connection::executeRawQuery($requette2);
    $resultat3 = CommandeArticle::getCommandeArticleByNoCommande($NoCommande);
    foreach ($resultat3 as $ligne3) {
      $created = false;
      if ($ligne3["TypeData"] == 0) {
        $requette4 = "SELECT * FROM articles WHERE NoArticleRR = :noarticle";
        $statement4 = Connection::getStatement($requette4);
        $statement4->bindParam(":noarticle", $ligne3["NoArticle"]);
        $statement4->execute();
        if ($ligne4 = $statement4->fetch()) {
          $ligneV = $ligne4;
          $requetteT = "SELECT * FROM articles WHERE NoArticleRR=:noarticle";
          $statementT = Connection::getStatement($requetteT);
          $noArt = addslashes($ligneV['Description']);
          $statementT->bindParam(":noarticle", $noArt);
          $statementT->execute();
          $resultatT = $statementT->fetchAll();
          // TODO this seems odd
          foreach ($resultatT as $ligneT) // on suit le chainage
          {
            $ligneV = $ligneT;
            $requetteT = "SELECT * FROM articles WHERE NoArticleRR=:noarticle";
            $statementT = Connection::getStatement($requetteT);
            $noArt = addslashes($ligneV['Description']);
            $statementT->bindParam(":noarticle", $noArt);
            $statementT->execute();
            $resultatT = $statementT->fetchAll();
          }
          //echo $ligneV["NoArticleRR"]."<BR/>";
          $prix = 0;
          if ($ligneV["PrixPropre"] != 0) {
            $prix = $ligneV["PrixPropre"];
          } else if ($ligneV["PrixImportateur"] != 0) {
            $prix = $ligneV["PrixImportateur"];
          }
          if ($prix != 0) {
            $prix_multi = $ligne3["Quantite"] * $prix * ((100 + Arrondi_1_ct($ligne3["Rabais"])) / 100);
            if ($ligneV["TVA"] > 0) {
              $prix_multi = $prix_multi * ((100 + $ligneV["TVA"]) / 100);
            }
            $prix_multi = Arrondi_5_ct($prix_multi);
            $requette5 = "INSERT INTO commandearticles" . ID_GARAGE . " (NoCommande, Position, TypeData, NoArticle, Description, TVA, GM, Quantite, PrixBase, Rabais, PrixMulti) VALUES" .
              " ($NoCommandeNew, " . $ligne3["Position"] . ", " . $ligne3["TypeData"] . ", '" . addslashes($ligneV["NoArticleRR"]) . "', '" . addslashes($ligneV["Description"]) . "', " .
              Arrondi_5_ct($ligneV["TVA"]) . ", " . Min_zero($ligneV["GroupeMarchandise"]) . ", " . Arrondi_1_ct($ligne3["Quantite"]) . ", " .
              Arrondi_5_ct($prix) . ", " . Arrondi_1_ct($ligne3["Rabais"]) . ", " . $prix_multi . ")";
            $created = true;
            //echo $requette5."<br>";
            //echo "UPDATE<br>";
          }
        }
      }
      if ($created == false) {
        $requette5 = "INSERT INTO commandearticles" . ID_GARAGE . " (NoCommande, Position, TypeData, NoArticle, Description, TVA, GM, Quantite, PrixBase, Rabais, PrixMulti) VALUES" .
          "($NoCommandeNew, " . $ligne3["Position"] . ", " . $ligne3["TypeData"] . ", '" . addslashes($ligne3["NoArticle"]) . "', '" . addslashes($ligne3["Description"]) . "', " .
          $ligne3["TVA"] . ", " . $ligne3["GM"] . ", " . $ligne3["Quantite"] . ", " .
          $ligne3["PrixBase"] . ", " . $ligne3["Rabais"] . ", " . $ligne3["PrixMulti"] . ")";
      }
      //echo $requette5."<br>";
      Connection::executeRawQuery($requette5);
    }
  }
  return $NoCommandeNew;
}

function Affiche_Impression($Mode, $Menu, $Options = 0)
{
  global $Modif, $NoCommande, $NoClient, $NoClient2, $Type, $Sous_Type, $Etape, $lg_user, $Encaisse;
  Select_Etape_Facture($NoCommande, $NoClient, $NoClient2, $Menu);
  echo "  <form name='info'>\n";
  echo "   <input type='hidden' name='Type' value=$Type>\n";
  echo "   <input type='hidden' name='Sous_Type' value=$Sous_Type>\n";
  echo "   <input type='hidden' name='Etape' value='" . ($Etape + 1) . "'>\n";
  echo "   <input type='hidden' name='NoCommande' value=$NoCommande>\n";
  echo "  </form>\n";
  Gestion_Impression($NoCommande, $Options);
  if (As_Right_Fonction(6, 35))
    echo "<BR><button type='button' onclick='valide_supprimer($NoCommande);'>Supprimer</button><BR>\n";
}

// TODO LSE moderniser AJAX  
function Affiche_Delais_Payement()
{
  global $NoCommande;
  $ligne = Commande::getCommandeByNoCommande($NoCommande);
  echo "Mode delais payement " . $ligne['ModeDelaisPayement'] . "<BR>\n";
  echo "Date payement " . $ligne['DatePayement'] . "<BR>\n";
  echo "<script language=JavaScript>\n";
  echo  "function valider_delais_payement(iciform)\n";
  echo  "{\n";
  echo "  var xhr_object = null;\n";
  echo "  if(window.XMLHttpRequest) // Firefox\n";
  echo "    xhr_object = new XMLHttpRequest();\n";
  echo "  else if(window.ActiveXObject)\n";
  echo "    xhr_object = new ActiveXObject(" . '"Microsoft.XMLHTTP"' . ");\n";
  echo "  else { // XMLHttpRequest non supporté par le navigateur\n";
  echo "    alert(" . '"Votre navigateur ne supporte pas les objets XMLHTTPRequest..."' . ");\n";
  echo "    return;\n";
  echo "  }\n";
  echo "  xhr_object.open(" . '"POST"' . ", " . '"delais.php"' . ", false);\n";
  echo "  xhr_object.setRequestHeader(" . '"Content-type", "application/x-www-form-urlencoded"' . ");\n";
  echo "  var data = " . '"nocommande=' . $NoCommande . '"' . "+" . '"&date="' . "+" . "iciform.elements['dateexp'].value" . "+" . "'&modedelais='" . "+" . "iciform.elements['ModeDelais'].value" . ";\n";
  echo "  xhr_object.send(data);\n";
  echo "  AsChange=0;\n";
  echo  "}\n";
  echo "\n";
  echo  "function gestion_delais(pos,iciform)\n";
  echo  "{\n";
  echo "  if(pos==0)\n";
  echo "  {\n";
  echo "    document.getElementById('mod0').style.visibility=" . '"visible"' . ";\n";
  echo "  }\n";
  echo "  if(pos==1)\n";
  echo "  {\n";
  echo "    document.getElementById('mod0').style.visibility=" . '"hidden"' . ";\n";
  echo "  }\n";
  echo "  if(pos==2)\n";
  echo "  {\n";
  echo "    document.getElementById('mod0').style.visibility=" . '"visible"' . ";\n";
  echo "  }\n";
  echo  "  valider_delais_payement(iciform);\n";
  echo  "}\n";
  echo "\n";
  echo "function jours10(iciform)\n";
  echo  "{\n";
  echo "  var dt=new Date();\n";
  echo "  dt.setDate(dt.getDate()+10);\n";
  echo "  if(dt.getDate()<10)\n";
  echo  "  {\n";
  echo "    iciform.elements['dateexp'].value='0'+dt.getDate();\n";
  echo  "  }\n";
  echo "  else\n";
  echo  "  {\n";
  echo "    iciform.elements['dateexp'].value=dt.getDate();\n";
  echo  "  }\n";
  echo "  if(dt.getMonth()<9)\n";
  echo  "  {\n";
  echo "    iciform.elements['dateexp'].value+='.0'+(dt.getMonth()+1);\n";
  echo  "  }\n";
  echo "  else\n";
  echo  "  {\n";
  echo "    iciform.elements['dateexp'].value+='.'+(dt.getMonth()+1);\n";
  echo  "  }\n";
  echo "  iciform.elements['dateexp'].value+='.'+dt.getFullYear();\n";
  echo  "  valider_delais_payement(iciform);\n";
  echo  "}\n";
  echo "\n";
  echo "function jours30(iciform)\n";
  echo  "{\n";
  echo "  var dt=new Date();\n";
  echo "  dt.setDate(dt.getDate()+30);\n";
  echo "  if(dt.getDate()<10)\n";
  echo  "  {\n";
  echo "    iciform.elements['dateexp'].value='0'+dt.getDate();\n";
  echo  "  }\n";
  echo "  else\n";
  echo  "  {\n";
  echo "    iciform.elements['dateexp'].value=dt.getDate();\n";
  echo  "  }\n";
  echo "  if(dt.getMonth()<9)\n";
  echo  "  {\n";
  echo "    iciform.elements['dateexp'].value+='.0'+(dt.getMonth()+1);\n";
  echo  "  }\n";
  echo "  else\n";
  echo  "  {\n";
  echo "    iciform.elements['dateexp'].value+='.'+(dt.getMonth()+1);\n";
  echo  "  }\n";
  echo "  iciform.elements['dateexp'].value+='.'+dt.getFullYear();\n";
  echo  "  valider_delais_payement(iciform);\n";
  echo  "}\n";
  echo "\n";
  echo "</script>\n";
  echo "<form name='info'>\n";
  echo "<SELECT name='ModeDelais' onchange='gestion_delais(this.value,this.form)'>\n";
  echo "<OPTION value='0'";
  if ($ligne['ModeDelaisPayement'] == 0) {
    echo " selected";
  }
  echo ">Unique</OPTION>\n";
  echo "<OPTION value='1'";
  if ($ligne['ModeDelaisPayement'] == 1) {
    echo " selected";
  }
  echo ">Aucun</OPTION>\n";
  echo "<OPTION value='2'";
  if ($ligne['ModeDelaisPayement'] == 2) {
    echo " selected";
  }
  echo ">Par mensualités</OPTION>\n";
  echo "</SELECT><BR>\n";
  echo "<span id='mod0'";
  if ($ligne['ModeDelaisPayement'] == 1) {
    echo " style='visibility:hidden;'";
  }
  echo ">Date " . Cree_Entree_Type("dateexp", 2, 100, $ligne['DateDelaisPayement'], MODIFICATION) . "<button type='button' onclick='jours10(this.form);'>10 jours</button><button type='button' onclick='jours30(this.form);'>30 jours</button></span><BR>\n";
  echo " <button type='button' onClick='valider_delais_payement(this.form);'>Valider</button><BR>\n";
  echo "</form>\n";
}

function Affiche_Convert_FD($NoCommande)
{
  if (As_Right_Fonction(6, 33)) {
    if ($_POST["change_type_facture"] == 1) {
      $Version = Commande::getVersionByNoCommande($NoCommande);
      $Version += 1;
      $IPClient = $_SERVER["REMOTE_ADDR"];
      switch ($_POST["new_type"]) {
        case "FI":
          $requette = "UPDATE commande" . ID_GARAGE . " SET Type='FI', APayer=0, Version=$Version, IPClient='$IPClient' WHERE NoCommande = $NoCommande";
          break;
        case "GF":
          $requette = "UPDATE commande" . ID_GARAGE . " SET Genre='G', Type='GF', Version=$Version, IPClient='$IPClient' WHERE NoCommande = $NoCommande";
          break;
        case "GG":
          $requette = "UPDATE commande" . ID_GARAGE . " SET Genre='G', Type='GG', APayer=0, Version=$Version, IPClient='$IPClient' WHERE NoCommande = $NoCommande";
          break;
      }
      Connection::executeRawQuery($requette);
      echo $requette . "<br />\n";
      header("Location: " . $_SERVER['REQUEST_URI']);
    }
    $resultat = DBCash::getDBCashByNoCommande($NoCommande);
    if (count($resultat) == 0) {
      echo "<script language=JavaScript>\n";
      echo "function valid_upd_type()\n";
      echo "{\n";
      echo "  if (confirm('changer type facture'))\n";
      echo "  {\n";
      echo "    document.upd_type.submit();\n";
      echo "  }\n";
      echo "}\n";
      echo "</script>\n";
      echo "<form name=\"upd_type\" method=\"post\">\n";
      echo "<input type=\"hidden\" name=\"change_type_facture\" value=\"1\">\n";
      echo "<select name=\"new_type\">\n";
      echo "<option value=\"FI\">Facture Interne</option>\n";
      echo "<option value=\"GF\">Garantie Fournisseur</option>\n";
      echo "<option value=\"GG\">Garantie Garage</option>\n";
      echo "</select>\n";
      echo "<button type=\"button\" onclick=\"valid_upd_type();\">Modifier</button>";
      echo "</form>\n";
    }
  }
}

function Affiche_Convert_FI($NoCommande)
{
  if (As_Right_Fonction(6, 33)) {
    if ($_POST["change_type_facture"] == 1) {
      $Version = Commande::getVersionByNoCommande($NoCommande);
      $Version += 1;
      $IPClient = $_SERVER["REMOTE_ADDR"];
      switch ($_POST["new_type"]) {
        case "FD":
          $requette = "UPDATE commande" . ID_GARAGE . " SET Genre='F', Type='FD', APayer=MontantTotal, Version=$Version, IPClient='$IPClient' WHERE NoCommande = $NoCommande";
          break;
        case "GF":
          $requette = "UPDATE commande" . ID_GARAGE . " SET Genre='G', Type='GF', APayer=MontantTotal, Version=$Version, IPClient='$IPClient' WHERE NoCommande = $NoCommande";
          break;
        case "GG":
          $requette = "UPDATE commande" . ID_GARAGE . " SET Genre='G', Type='GG', APayer=0, Version=$Version, IPClient='$IPClient' WHERE NoCommande = $NoCommande";
          break;
      }
      Connection::executeRawQuery($requette);
      echo $requette . "<br />\n";
      header("Location: " . $_SERVER['REQUEST_URI']);
    }
    echo "<script language=JavaScript>\n";
    echo "function valid_upd_type()\n";
    echo "{\n";
    echo "  if (confirm('changer type facture'))\n";
    echo "  {\n";
    echo "    document.upd_type.submit();\n";
    echo "  }\n";
    echo "}\n";
    echo "</script>\n";
    echo "<form name=\"upd_type\" method=\"post\">\n";
    echo "<input type=\"hidden\" name=\"change_type_facture\" value=\"1\">\n";
    echo "<select name=\"new_type\">\n";
    echo "<option value=\"FD\">Facture Détaillée</option>\n";
    echo "<option value=\"GF\">Garantie Fournisseur</option>\n";
    echo "<option value=\"GG\">Garantie Garage</option>\n";
    echo "</select>\n";
    echo "<button type=\"button\" onclick=\"valid_upd_type();\">Modifier</button>";
    echo "</form>\n";
  }
}

function Affiche_Convert_GG($NoCommande)
{
  if (As_Right_Fonction(6, 33)) {
    if ($_POST["change_type_facture"] == 1) {
      $Version = Commande::getVersionByNoCommande($NoCommande);
      $Version += 1;
      $IPClient = $_SERVER["REMOTE_ADDR"];
      switch ($_POST["new_type"]) {
        case "FD":
          $requette = "UPDATE commande" . ID_GARAGE . " SET Genre='F', Type='FD', APayer=MontantTotal, Version=$Version, IPClient='$IPClient' WHERE NoCommande = $NoCommande";
          break;
        case "FI":
          $requette = "UPDATE commande" . ID_GARAGE . " SET Genre='F', Type='FI', APayer=0, Version=$Version, IPClient='$IPClient' WHERE NoCommande = $NoCommande";
          break;
        case "GF":
          $requette = "UPDATE commande" . ID_GARAGE . " SET Genre='G', Type='GF', APayer=MontantTotal, Version=$Version, IPClient='$IPClient' WHERE NoCommande = $NoCommande";
          break;
      }
      Connection::executeRawQuery($requette);
      echo $requette . "<br />\n";
      header("Location: " . $_SERVER['REQUEST_URI']);
    }
    echo "<script language=JavaScript>\n";
    echo "function valid_upd_type()\n";
    echo "{\n";
    echo "  if (confirm('changer type facture'))\n";
    echo "  {\n";
    echo "    document.upd_type.submit();\n";
    echo "  }\n";
    echo "}\n";
    echo "</script>\n";
    echo "<form name=\"upd_type\" method=\"post\">\n";
    echo "<input type=\"hidden\" name=\"change_type_facture\" value=\"1\">\n";
    echo "<select name=\"new_type\">\n";
    echo "<option value=\"FD\">Facture Détaillée</option>\n";
    echo "<option value=\"FI\">Facture Interne</option>\n";
    echo "<option value=\"GF\">Garantie Fournisseur</option>\n";
    echo "</select>\n";
    echo "<button type=\"button\" onclick=\"valid_upd_type();\">Modifier</button>";
    echo "</form>\n";
  }
}

function Affiche_Convert_GF($NoCommande)
{
  if (As_Right_Fonction(6, 33)) {
    if ($_POST["change_type_facture"] == 1) {
      $Version = Commande::getVersionByNoCommande($NoCommande);
      $Version += 1;
      $IPClient = $_SERVER["REMOTE_ADDR"];
      switch ($_POST["new_type"]) {
        case "FI":
          $requette = "UPDATE commande" . ID_GARAGE . " SET Genre='F', Type='FI', APayer=0, Version=$Version, IPClient='$IPClient' WHERE NoCommande = $NoCommande";
          break;
        case "FD":
          $requette = "UPDATE commande" . ID_GARAGE . " SET Genre='F', Type='FD', APayer=MontantTotal, Version=$Version, IPClient='$IPClient' WHERE NoCommande = $NoCommande";
          break;
        case "GG":
          $requette = "UPDATE commande" . ID_GARAGE . " SET Genre='G', Type='GG', APayer=0, Version=$Version, IPClient='$IPClient' WHERE NoCommande = $NoCommande";
          break;
      }
      Connection::executeRawQuery($requette);
      echo $requette . "<br />\n";
      header("Location: " . $_SERVER['REQUEST_URI']);
    }
    $resultat = DBCash::getDBCashByNoCommande($NoCommande);
    if (count($resultat) == 0) {
      echo "<script language=JavaScript>\n";
      echo "function valid_upd_type()\n";
      echo "{\n";
      echo "  if (confirm('changer type facture'))\n";
      echo "  {\n";
      echo "    document.upd_type.submit();\n";
      echo "  }\n";
      echo "}\n";
      echo "</script>\n";
      echo "<form name=\"upd_type\" method=\"post\">\n";
      echo "<input type=\"hidden\" name=\"change_type_facture\" value=\"1\">\n";
      echo "<select name=\"new_type\">\n";
      echo "<option value=\"FD\">Facture Détaillée</option>\n";
      echo "<option value=\"FI\">Facture Interne</option>\n";
      echo "<option value=\"GG\">Garantie Garage</option>\n";
      echo "</select>\n";
      echo "<button type=\"button\" onclick=\"valid_upd_type();\">Modifier</button>";
      echo "</form>\n";
    }
  }
}

function Gestion_Encaissement($NoCommande, $Mode = 0)
{
  global $Type, $Sous_Type, $Etape, $NoClient, $NoClient2;
  if (isset($GLOBALS['status'])) {
    $Version = Commande::getVersionByNoCommande($NoCommande);
    $Version += 1;
    $IPClient = $_SERVER["REMOTE_ADDR"];
    $requette = "UPDATE commande" . ID_GARAGE . " SET APayer=:solde, Paye=:status, Version=:version, IPClient=:ip WHERE NoCommande=:nocommande";
    echo "$requette<BR>";
    $statement = Connection::getStatement($requette);
    $statement->bindParam(":solde", $GLOBALS['solde']);
    $statement->bindParam(":status", $GLOBALS['status']);
    $statement->bindParam(":version", $Version);
    $statement->bindParam(":ip", $IPClient);
    $statement->bindParam(":nocommande", $NoCommande);
    $statement->execute();
  }
  $resultat = DBCash::getDBCashByNoCommande($NoCommande);
  if (count($resultat) > 0) {
    foreach ($resultat as $ligne) {
      echo "Paye le " . $ligne['Date'] . " " . $ligne['Somme'] . " ";
      $ligne2 = ModePayement::getModePayementsByNoModeAndNoCaisse($ligne['ModePayement'], $ligne['NoCaisse']);
      echo $ligne2['Description'] . " caisse " . $ligne2['NoCaisse'];
      echo " <a class='bt_function' HREF='print_quitance.php?NoCash=" . $ligne['NoCash'] . "&NoOpen=1' target='_blank' rel='opener'>Quittance</a>\n";
      echo " <a class='bt_function' HREF='print_ticket_commande.php?NoCash=" . $ligne['NoCash'] . "&NoCommande=$NoCommande&NoOpen=1' target='_blank' rel='opener'>Ticket</a>\n";
      if (As_Right_Fonction(6, 36)) {
        echo " <a class='bt_function' href='default.php?Type=$Type&Sous_Type=$Sous_Type&Etape=$Etape&NoCommande=$NoCommande&NoClient=$NoClient&NoClient2=$NoClient2' onclick='cancel_quitance(" . $ligne['NoCash'] . ")'>cancel</a>\n";
      }
      if (As_Right_Fonction(6, 34)) {
        echo " <a class='bt_function' href='default.php?Type=$Type&Sous_Type=$Sous_Type&Etape=$Etape&NoCommande=$NoCommande&NoClient=$NoClient&NoClient2=$NoClient2' onclick='edit_quitance(" . $ligne['NoCash'] . ")'>modify</a>\n";
      }
      echo "<script language=JavaScript>\n";
      //echo "force_submit=true;\n";
      echo "</script>\n";
      echo "<BR>\n";
    }
  }
  $ligne = Commande::getCommandeByNoCommande($NoCommande);;
  if ($ligne) {
    echo "Total facture " . $ligne['MontantTotal'] . " reste a payer " . $ligne['APayer'] . "<BR>\n";
  }
  if ($ligne['Paye'] != 'O') {
    echo "<BR /><BR />\n";
    echo "<form name='info'>\n";
    echo " <input type='hidden' name='Type' value='" . $GLOBALS['Type'] . "'>\n";
    echo " <input type='hidden' name='Sous_Type' value='" . $GLOBALS['Sous_Type'] . "'>\n";
    echo " <input type='hidden' name='Etape' value='" . ($GLOBALS['Etape']) . "'>\n";
    if (isset($GLOBALS['NoClient']))
      echo " <input type='hidden' name='NoClient' value='" . $GLOBALS['NoClient'] . "'>\n";
    echo " <input type='hidden' name='NoCommande' value='$NoCommande'>\n";
    echo " <input type='hidden' name='Ticket' value='0'>\n";
    echo " <input type='text' name='Payement' value='" . $ligne['APayer'] . "'>\n";
    $resultat2 = null;
    if (As_Right_Groupe(6)) {
      $resultat2 = ModePayement::getVisibleModePayment();
    } else {
      $no_caisse = 1;
      if ($ligne1 = Poste::getPostesByIP()) {
        $no_caisse = $ligne1['NoCaisse'];
      }
      $resultat2 = ModePayement::getVisibleModePayment($no_caisse);
    }
    echo " <SELECT name='ModePayement' size='1'>\n";
    if (!is_null($resultat2)) {
      foreach ($resultat2 as $ligne2) {
        if (($ligne2['Type'] == 2) && (!Is_Banque())) {
        } else {
          if (As_Right_Groupe(6)) {
            echo "  <option value='" . $ligne2['NoMode'] . " " . $ligne2['NoCaisse'] . "'>" . $ligne2['Description'] . " caisse " . $ligne2['NoCaisse'] . "</option>\n";
          } else {
            echo "  <option value='" . $ligne2['NoMode'] . " " . $ligne2['NoCaisse'] . "'>" . $ligne2['Description'] . "</option>\n";
          }
        }
      }
    }
    echo " </SELECT>\n";
    echo " <button type='submit'>Quittance</button><button type='button' onClick='go_ticket(this.form);'>Facture</button><BR>\n";
    if (As_Right_Groupe(6) || true) {
      echo "Date valeur ";
    }
    echo Cree_Entree_Type("datevaleur", 18, 0, date("Y-m-d H:i:00"), MODIFICATION);
    echo "</form>\n";
  } else {
    echo "<form name='info'>\n";
    echo " <input type='hidden' name='Type' value='" . $GLOBALS['Type'] . "'>\n";
    echo " <input type='hidden' name='Sous_Type' value='" . $GLOBALS['Sous_Type'] . "'>\n";
    echo " <input type='hidden' name='Etape' value='" . ($GLOBALS['Etape']) . "'>\n";
    if (isset($GLOBALS['NoClient']))
      echo " <input type='hidden' name='NoClient' value='" . $GLOBALS['NoClient'] . "'>\n";
    echo " <input type='hidden' name='NoCommande' value='$NoCommande'>\n";
    echo "</form>\n";
  }
  if (As_Right_Fonction(6, 35)) {
    echo "<BR><form>\n";
    echo " <input type='hidden' name='Type' value='" . $GLOBALS['Type'] . "'>\n";
    echo " <input type='hidden' name='Sous_Type' value='" . $GLOBALS['Sous_Type'] . "'>\n";
    echo " <input type='hidden' name='Etape' value='" . $GLOBALS['Etape'] . "'>\n";
    echo " <input type='hidden' name='NoCommande' value='$NoCommande'>\n";
    echo "solde manuel<input type='text' name='solde' value='" . $ligne['APayer'] . "'>\n";
    echo "status<input type='text' name='status' value='" . $ligne['Paye'] . "' size=1 maxlength=1>\n";
    echo " <button type='submit'>valide</button></form>\n";
    echo "<BR><button type='button' onclick='valide_supprimer($NoCommande);'>Supprimer</button>\n";
    echo "<script language=JavaScript>\n";
    echo "cancel_submit=true;\n";
    echo "</script>\n";
  }
}

function Valide_Encaissement($NoCommande, $Mode = 0)
{
  // Mode 0 encaisement
  // Mode 1 décaissement
  global $lg_user, $Payement, $ModePayement, $datevaleur;
  global $Type, $Sous_Type, $Etape, $NoClient, $NoClient2;
  if (isset($GLOBALS['Payement'])) {
    $tab_mode = explode(" ", $ModePayement);
    $ligne = Commande::getCommandeByNoCommande($NoCommande);
    $lp = $ligne['DatePayement'];
    $lastpayement = substr($lp, 0, 4) . substr($lp, 5, 2) . substr($lp, 8, 2);
    $apayer = $ligne['APayer'];
    $apayer -= $Payement;
    //$date=$datevaleur[2]."-".$datevaleur[1]."-".$datevaleur[0]." ".$datevaleur[3].":".$datevaleur[4].":00";
    $date = Decode_Entree_Type($datevaleur, 18);
    if ($Mode == 1)
      DBCash::insert($NoCommande, $lg_user, $date, -$Payement, -get_config('TVA'), $tab_mode[0], $tab_mode[1]);
    else
      DBCash::insert($NoCommande, $lg_user, $date, $Payement, -get_config('TVA'), $tab_mode[0], $tab_mode[1]);

    //$actualpayement=$datevaleur[2].$datevaleur[1].$datevaleur[0];
    $actualpayement = substr($date, 0, 4) . substr($date, 5, 2) . substr($date, 8, 2);
    if ($lastpayement > $actualpayement) {
      $requette = "UPDATE commande" . ID_GARAGE . " SET APayer = $apayer, ";
    } else {
      $requette = "UPDATE commande" . ID_GARAGE . " SET APayer = $apayer, DatePayement= '" . Decode_Entree_Type($datevaleur[0], 2) . "', ";
    }
    if ($apayer == 0) {
      $requette .= "Paye='O'";
    } else {
      $requette .= "Paye='P'";
    }
    $Version = Commande::getVersionByNoCommande($NoCommande);
    $Version += 1;
    $IPClient = $_SERVER["REMOTE_ADDR"];
    $requette .= ", Version=$Version, IPClient='$IPClient'";
    $requette .= " WHERE NoCommande=$NoCommande";
    Connection::executeRawQuery($requette);
    if ($Mode == 0) {
      $ligne = DBCash::getNoCashByNoFactureAndDateAndSommeAndModePaymentAndNoCaisse($NoCommande, $date, $Payement, $tab_mode[0], $tab_mode[1])[0];
      if ($GLOBALS['Ticket'] == 1) {
        print_ticket_commande($NoCommande, 0, $ligne['NoCash']);
      } else {
        print_quitance($ligne['NoCash']);
      }
    }
    if ($Mode == 1) {
      $ligne = $ligne = DBCash::getNoCashByNoFactureAndDateAndSommeAndModePaymentAndNoCaisse($NoCommande, $date, -$Payement, $tab_mode[0], $tab_mode[1])[0];
      if ($GLOBALS['Ticket'] == 1) {
        print_ticket_commande($NoCommande, 0, $ligne['NoCash']);
      } else {
        print_quitance($ligne['NoCash']);
      }
    }
    echo "<script language=JavaScript>\n";
    echo "window.location.href='default.php?Type=$Type&Sous_Type=$Sous_Type&Etape=$Etape&NoCommande=$NoCommande&NoClient=&NoClient2=';\n";
    echo "</script>\n";
  }
}

function print_quitance($NoCash)
{
  $ligne = DBCash::getDBCashByNoCash($NoCash);
  if ($ligne) {
    $date = $ligne['Date'];
    $mode = "Inconnu";
    $ligne2 = ModePayement::getModePayementsByNoModeAndNoCaisse($ligne['ModePayement'], $ligne['NoCaisse']);
    if ($ligne2) {
      $mode = $ligne2['Description'];
      if ($ligne2['Type'] == 2) {
        return;
      }
    }
    $somme = $ligne['Somme'];
    $taille = strlen($somme);
    switch ($taille) {
      case 7:
        $somme = substr($somme, 0, 1) . "'" . substr($somme, 1);
        break;
      case 8:
        $somme = substr($somme, 0, 2) . "'" . substr($somme, 2);
        break;
    }
    $date = substr($date, 8, 2) . "." . substr($date, 5, 2) . "." . substr($date, 2, 2) . " " . substr($date, 11, 2) . ":" . substr($date, 14, 2);
    $f = fopen("../files/quitances/quitance$NoCash.pos", "w");
    $espace1 = " ";
    for ($cpt = strlen($mode); $cpt < 13; $cpt++) {
      $espace1 .= " ";
    }
    $espace2 = " ";
    for ($cpt = (strlen($ligne['NoFacture'] . "") + strlen($somme . "")); $cpt < 19; $cpt++) {
      $espace2 .= " ";
    }
    fwrite($f, t88_init() . t88_align(1) . t88_size(2) . "Quittance" . t88_cr() .
      //t88_align(0).t88_size(0).t88_cr()."Centre Honda Gen\x7dve".t88_cr().
      //"Charmilles 3 SA".t88_cr().
      //"Rue des Charmilles 3".t88_cr().
      //"1203 Gen\x7dve".t88_cr().
      t88_align(0) . t88_size(0) . t88_cr() . t88_convert_string(Config::getLigne1Adresse()) . t88_cr() .
      t88_convert_string(Config::getLigne2Adresse()) . t88_cr() .
      t88_convert_string(Config::getLigne3Adresse()) . t88_cr() .
      t88_convert_string(Config::getLigne4Adresse()) . t88_cr() .
      t88_font(1) . "T\x7bl " . t88_convert_string(Config::getNoTelephone()) . t88_cr() .
      "Fax " . t88_convert_string(Config::getNoFax()) . t88_cr() .
      "TVA " . t88_convert_string(Config::getNoTVA()) . t88_cr() . t88_cr() .
      t88_font(1) . t88_size(1) . $mode . $espace1 . $date . t88_cr() .
      t88_font(1) . t88_size(0) . t88_cr() .
      t88_font(1) . t88_size(1) . "Facture " . $ligne['NoFacture'] . $espace2 . $somme . t88_cr() . t88_cr() .
      t88_align(1) . t88_font(0) . t88_size(1) . "Merci de votre visite" . t88_cr() . t88_cut());
    if (($ligne['ModePayement'] == 1) && ($ligne['NoCaisse'] != 0)/*&&$_GET["NoOpen"]!=1*/) // TODO regarder à quoi sert le NoOpen
      fwrite($f, t88_pulse());
    fclose($f);
    $no_caisse = 1;
    if ($ligne1 = Poste::getPostesByIP()) {
      $no_caisse = $ligne1['NoCaisse'];
    }
    exec("lp -d ticket$no_caisse ../files/quitances/quitance$NoCash.pos");
    unlink("../files/quitances/quitance$NoCash.pos");
  }
}

function print_ticket_commande($NoCommande, $Detail, $NoCash)
{
  $f = fopen("../files/factures/$NoCommande.pos", "w");
  $resultat = CommandeArticle::getAbsoluteTVAByNoCommadneAndTypeDataTo0($NoCommande);
  $TVAS = array();
  $nb_tva = 0;
  foreach ($resultat as $ligne) {
    echo "$ligne[0]<BR>";
    $TVA = $ligne[0] * 1;
    $TVAS["$TVA"] = 0;
  }
  $ligne = Commande::getCommandeByNoCommande($NoCommande);
  $resultat2 = CommandeArticle::getCommandeArticleByNoCommandeAndTypeDataTo0($NoCommande);
  fwrite($f, t88_init() . t88_align(1) . t88_size(1));
  switch ($ligne['Type']) {
    case "FD":
      fwrite($f, "Facture ");
      break;
    case "BP":
      fwrite($f, "Bulletin liv. ");
      break;
    case "FB":
      fwrite($f, "Facture bulletin ");
      break;
    case "FV":
      fwrite($f, "Facture vhc ");
      break;
    case "FO":
      fwrite($f, "Facture occas. ");
      break;
    case "FL":
      fwrite($f, "Facture loc. ");
      break;
    case "FI":
      fwrite($f, "Facture int. ");
      break;
    case "CP":
      fwrite($f, "Commande ");
      break;
    case "OP":
      fwrite($f, "Offre pi\x7dces ");
      break;
    case "OV":
      fwrite($f, "Offre vhc ");
      break;
    case "DP":
      fwrite($f, "Devis ");
      break;
    case "GF":
      fwrite($f, "Garantie four. ");
      break;
    case "GG":
      fwrite($f, "Garantie gar. ");
      break;
    case "RV":
      fwrite($f, "Reprise vhc. ");
      break;
    case "ND":
      fwrite($f, "Note cr\x7bdit p ");
      break;
    case "NB":
      fwrite($f, "Note cr\x7bdit b ");
      break;
    case "NV":
      fwrite($f, "Note cr\x7bdit v ");
      break;
    case "NO":
      fwrite($f, "Note cr\x7bdit o ");
      break;
    case "NL":
      fwrite($f, "Note cr\x7bdit l ");
      break;
    case "AM":
      fwrite($f, "Achat ");
      break;
    case "VV":
      fwrite($f, "Achat vhc.");
      break;
  }
  $date = $ligne['DateCommande'];
  $date = substr($date, 8, 2) . "." . substr($date, 5, 2) . "." . substr($date, 0, 4);
  fwrite($f, $NoCommande . t88_cr() .
    t88_align(0) . t88_size(0) . t88_cr() . t88_convert_string(Config::getLigne1Adresse()) . t88_cr() .
    t88_convert_string(Config::getLigne2Adresse()) . t88_cr() .
    t88_convert_string(Config::getLigne3Adresse()) . t88_cr() .
    t88_convert_string(Config::getLigne4Adresse()) . t88_cr() .
    t88_font(1) . "T\x7bl " . t88_convert_string(Config::getNoTelephone()) . t88_cr() .
    "Fax " . t88_convert_string(Config::getNoFax()) . t88_cr() .
    "TVA " . t88_convert_string(Config::getNoTVA()) . t88_cr() . t88_cr() .
    t88_align(0) . t88_size(0) . t88_font(0) . "Date " . $date . t88_cr() . t88_font(1));
  foreach ($resultat2 as $ligne2) {
    $NoArticle = $ligne2['NoArticle'];
    $Description = $ligne2['Description'];
    if ($ligne2['TVA'] > 0) {
      $Prix = Arrondi_5_ct($ligne2['PrixBase'] * ((100 + $ligne2['TVA']) / 100));
    } else {
      $Prix = $ligne2['PrixBase'];
    }
    $Quantite = $ligne2['Quantite'];
    $Total = $ligne2['PrixMulti'];
    $TVA = abs($ligne2['TVA']);
    $TVAS["$TVA"] += $Total;
    $Rabais = $ligne2['Rabais'];
    if ($Detail == 1) {
      fwrite($f, taille_text($NoArticle, 19, 0) . " " . taille_text(t88_convert_string($Description), 30, 0) . t88_cr() . taille_text($Prix, 9, 1) . " " . taille_text($Quantite, 7, 1) . " ");
      if ($Rabais == 0) {
        fwrite($f, "                            ");
      } else {
        fwrite($f, taille_text($Rabais, 6, 1) . "%                     ");
      }
      fwrite($f, taille_text($Total, 10, 1) . t88_cr());
    } else {
      fwrite($f, taille_text(t88_convert_string($Description), 21, 0) . " " . taille_text($Prix, 8, 1) . " " . taille_text($Quantite, 7, 1) . " ");
      if ($Rabais == 0) {
        fwrite($f, "        ");
      } else {
        fwrite($f, taille_text($Rabais, 6, 1) . "% ");
      }
      fwrite($f, taille_text($Total, 8, 1) . t88_cr());
    }
  }
  fwrite($f, t88_font(0) . "Total" . taille_text($ligne['MontantTotal'], 37, 1) . t88_cr() . t88_font(1) . t88_cr());
  foreach ($TVAS as $TVA => $Total) {
    $ht = round($Total / ((100 + $TVA) / 100), 2);
    $tax = $Total - $ht;
    fwrite($f, taille_text(Arrondi_1_ct($Total), 8, 1) . " TVA " . taille_text(Arrondi_1_ct($TVA), 5, 1) . "% HT " . taille_text(Arrondi_1_ct($ht), 8, 1) . " TAX " . taille_text(Arrondi_1_ct($tax), 7, 1) . t88_cr());
    echo taille_text(Arrondi_1_ct($Total), 8, 1) . " TVA " . taille_text(Arrondi_1_ct($TVA), 5, 1) . "% HT " . taille_text(Arrondi_1_ct($ht), 8, 1) . " TAX " . taille_text(Arrondi_1_ct($tax), 7, 1) . "<BR>";
  }
  if ($NoCash != 0) {
    $ligne3 = DBCash::getDBCashByNoCash($NoCash);
    if ($ligne3) {
      $date = $ligne3['Date'];
      $somme = $ligne3['Somme'];
      $mode = "Inconnu";
      $ligne4 = ModePayement::getModePayementsByNoModeAndNoCaisse($ligne3['ModePayement'], $ligne3['NoCaisse']);
      if ($ligne4) {
        $mode = $ligne4['Description'];
      }
      $date = substr($date, 8, 2) . "." . substr($date, 5, 2) . "." . substr($date, 2, 2) . " " . substr($date, 11, 2) . ":" . substr($date, 14, 2);
      fwrite($f, t88_cr() . t88_font(0) . "Pay\x7b " . $somme . " " . $mode . " " . $date . t88_cr() . t88_cr());
    }
  }
  if ($ligne["APayer"] != 0) {
    fwrite($f, t88_cr() . t88_font(2) . t88_size(1) . "Solde \x85 payer" . taille_text($ligne['APayer'], 15, 1) . t88_cr() . t88_font(1) . t88_cr());
  }
  fwrite($f, t88_align(1) . t88_font(0) . t88_size(1) . "Merci de votre visite" . t88_cr() . t88_cut());
  if ($NoCash != 0) {
    if (($ligne3['ModePayement'] == 1) && ($ligne3['NoCaisse'] != 0)/*&&$_GET["NoOpen"]!=1*/) // TODO regarder à quoi sert le NoOpen
      fwrite($f, t88_pulse());
  }
  fclose($f);
  $no_caisse = 1;
  if ($ligne1 = Poste::getPostesByIP()) {
    $no_caisse = $ligne1['NoCaisse'];
  }
  exec("lp -d ticket$no_caisse ../files/factures/$NoCommande.pos");
  unlink("lp -d ticket$no_caisse ../files/factures/$NoCommande.pos");
}

function entete_commande($type, $nom, $mode = 0)
{
  global $NoCommande, $Type_default, $Etape, $Move, $NoClient, $NoClient2, $NoChasis;
  $Solde = "";
  $Client = "";
  $Vhc = "";
  $Rabais = "";
  $Status = "";
  $Date = "";
  $Type_default = $type;
  if (empty($NoCommande)) {
    $NoCommande = "0";
  }
  if ($NoCommande < 1 && $Etape == 3) {
    $NoCommande = Trouve_No_Commande_Libre($type);
  } else {
    echo "<SCRIPT language=JavaScript>\nmemnoform=4</SCRIPT>\n";
    if ($ligne = Commande::getCommandeByNoCommande($NoCommande)) {
      $Solde = $ligne['APayer'];
      $Date = Cree_Entree_Type("", 2, 0, $ligne['DateCommande'], AFFICHAGE);
      if (!isset($NoClient)) {
        $NoClient = $ligne['NoClient'];
      }
      if (!isset($NoClient2)) {
        $NoClient2 = $ligne['NoClient2'];
      }
      if ($ligne2 = Client::getClientByNoClient($NoClient)) {
        $Client = $ligne2['NoClient'] . " " . $ligne2['Nom'] . " " . $ligne2['Prenom'];
        if ($ligne3 = TypeRabais::getTypeRabaisByNoRabais($ligne2['TypeRabais'])) {
          $Rabais = $ligne3['Description'];
        }
      }
      if (!isset($NoChasis)) {
        $NoChasis = $ligne['Vehicule'];
      }
      if ($ligne2 = Vehicule::getVehiculeByNoChassis(addslashes($NoChasis))) {
        $Vhc = $ligne2['NoChasis'] . " " . $ligne2['MarqueModel'] . " " . $ligne2['Model'];
      }
      if ($mode == 1) {
        if (empty($ligne['NoFourniseur'])) {
          $Status = "Ouverte";
        } else {
          if ($ligne['Recu'] == 'O') {
            $Status = "Recue";
          } else {
            $Status = "Envoyée";
          }
        }
      }
    }
  }
  echo "<table class='table_info' cellspacing='0'><TR><TD>$nom $NoCommande</TD><TD>Client $Client</TD><TD>Vhc $Vhc</TD><TD>Solde $Solde</TD><TD>Rabais $Rabais</TD><TD>Date $Date</TD>";
  if ($mode == 1) {
    echo "<TD>$Status</TD>";
  }
  echo "</TR></table>\n";
}

function Maj_Commande_Articles_newfact($NoCommande, $Mode = 0)
{
  // Mode 0 ne modifie pas le stock
  // Mode 1 modifie le stock retrais
  // Mode 2 modifie le stock ajout
  // Mode 3 modifie le stock ajout selon recep
  //echo "Mode = $Mode\n";
  if ($Mode == 3) {
    $recu_tout = true;
  }
  $array_article_prec = array();
  if ($Mode != 0) {
    $array_prix_prec = array();
    if ($resultat = CommandeArticle::getCommandeArticleByNoCommande($NoCommande)) {
      foreach ($resultat as $ligne) {
        if (!empty($ligne['NoArticle'])) {
          $noArticleRR = Texte_Sans_Espace($ligne['NoArticle']);
          if (!array_key_exists($noArticleRR, $array_article_prec)) {
            $array_article_prec[$noArticleRR] = $ligne['Quantite'];
          } else {
            $array_article_prec[$noArticleRR] = $array_article_prec[$noArticleRR] + $ligne['Quantite'];
          }
          if (!array_key_exists($noArticleRR, $array_prix_prec)) {
            $array_prix_prec[$noArticleRR] = $ligne['Quantite'] * $ligne['PrixBase'];
          } else {
            $array_prix_prec[$noArticleRR] = $array_prix_prec[$noArticleRR] + ($ligne['Quantite'] * $ligne['PrixBase']);
          }
          $resultat_existe_stock = Stock::getStockByNoArticleRR(addslashes($noArticleRR));
          // TODO switch one Mode
          if ($Mode == 1) {
            if ($resultat_existe_stock) { // UPDATE
              $requette2 = "UPDATE stock" . ID_GARAGE . " SET EnStock = EnStock + (" . $ligne['Quantite'] . ") WHERE NoArticleRR = '" . addslashes($noArticleRR) . "'";
            } else { // INSERT
              $requette2 = "INSERT INTO stock" . ID_GARAGE . " (`NoArticleRR` ,`LieuxStock` ,`EnStock` ,`EnTransfert`) VALUES ('" . addslashes($noArticleRR) . "', NULL , +(" . $ligne['Quantite'] . "), 0)";
            }
          } else if ($Mode == 2) {
            if ($resultat_existe_stock) { // UPDATE
              $requette2 = "UPDATE stock" . ID_GARAGE . " SET EnStock = EnStock - (" . $ligne['Quantite'] . ") WHERE NoArticleRR = '" . addslashes($noArticleRR) . "'";
            } else { // INSERT
              $requette2 = "INSERT INTO stock" . ID_GARAGE . " (`NoArticleRR` ,`LieuxStock` ,`EnStock` ,`EnTransfert`) VALUES ('" . addslashes($noArticleRR) . "', NULL , -(" . $ligne['Quantite'] . "), 0);";
            }
          } else if ($Mode == 3) {
            if ($resultat_existe_stock) { // UPDATE
              $requette2 = "UPDATE stock" . ID_GARAGE . " SET EnStock = EnStock - (" . $ligne['NbRecu'] . "), EnTransfert = EnTransfert - (" . ($ligne['Quantite'] - $ligne['NbRecu']) . ") WHERE NoArticleRR = '" . addslashes($noArticleRR) . "'";
            } else { // INSERT
              $requette2 = "INSERT INTO stock" . ID_GARAGE . " (`NoArticleRR` ,`LieuxStock` ,`EnStock` ,`EnTransfert`) VALUES ('" . addslashes($noArticleRR) . "', NULL , -(" . $ligne['NbRecu'] . "), - (" . ($ligne['Quantite'] - $ligne['NbRecu']) . "));";
            }
          }
          $resultat2 = Connection::executeRawQuery($requette2);;
          //echo $requette2 . "<BR/>\n";
        }
      }
    }
  }
  $requette = CommandeArticle::deleteByNoCommande($NoCommande);
  //echo $GLOBALS['current_cpt']."<BR/>\n";
  $pos = 1;
  //return;
  $array_article_suiv = array();
  $array_prix_suiv = array();
  for ($cpt = 1; $cpt <= $GLOBALS['current_cpt']; $cpt++) {
    for ($cpt_el = 1; $cpt_el <= $GLOBALS['current_cpt']; $cpt_el++) {
      //echo "pos = ".$GLOBALS["pos" . $cpt_el];
      if ($GLOBALS["pos" . $cpt_el] == $cpt) {
        //echo "type = ".$GLOBALS["type" . $cpt_el];
        switch ($GLOBALS["type" . $cpt_el]) {
          case "article":
          case "tvamarges":
          case "ajouttva":
            $type = 0;
            if ($GLOBALS["type" . $cpt_el] == "tvamarges") {
              $type = 3;
            }
            if ($GLOBALS["type" . $cpt_el] == "ajouttva") {
              $type = 4;
            }
            //echo "article " . $pos . "<BR/>\n";
            $prix_multi = $GLOBALS["Quantite" . $cpt_el] * $GLOBALS["Prix" . $cpt_el] * ((100 + $GLOBALS["Rabais" . $cpt_el]) / 100);
            if ($GLOBALS["TVA" . $cpt_el] > 0) {
              $prix_multi = $prix_multi * ((100 + $GLOBALS["TVA" . $cpt_el]) / 100);
            }
            if ($Mode == 3) {
              $prix_multi = Arrondi_1_ct($prix_multi);
            } else {
              $prix_multi = Arrondi_5_ct($prix_multi);
            }
            $noArticleRR = Texte_Sans_Espace($GLOBALS["NoArticle" . $cpt_el]);
            if (!array_key_exists($noArticleRR, $array_article_suiv)) {
              $array_article_suiv[$noArticleRR] = Arrondi_1_ct($GLOBALS["Quantite" . $cpt_el]);
            } else {
              $array_article_suiv[$noArticleRR] = $array_article_suiv[$noArticleRR] + Arrondi_1_ct($GLOBALS["Quantite" . $cpt_el]);
            }
            if (!array_key_exists($noArticleRR, $array_prix_suiv)) {
              $array_prix_suiv[$noArticleRR] = Arrondi_1_ct($GLOBALS["Quantite" . $cpt_el] * $GLOBALS["Prix" . $cpt_el]);
            } else {
              $array_prix_suiv[$noArticleRR] = $array_prix_suiv[$noArticleRR] + Arrondi_1_ct($GLOBALS["Quantite" . $cpt_el] * $GLOBALS["Prix" . $cpt_el]);
            }

            $requette = "INSERT INTO commandearticles" . ID_GARAGE . " (NoCommande, Position, TypeData, NoArticle, Description, TVA, GM, Quantite, PrixBase, Rabais, PrixMulti";
            if ($Mode == 3) {
              $requette .= ", NbRecu, DateRecu, Dest";
            }
            $requette .= ") VALUES (" .
              "$NoCommande, $pos, $type, '" . addslashes($GLOBALS["NoArticle" . $cpt_el]) . "', '" . addslashes($GLOBALS["Description" . $cpt_el]) .
              "', " . Arrondi_5_ct($GLOBALS["TVA" . $cpt_el]) . ", " . Min_zero($GLOBALS["GM" . $cpt_el]) . ", " . Arrondi_1_ct($GLOBALS["Quantite" . $cpt_el]) . ", " . Arrondi_5_ct($GLOBALS["Prix" . $cpt_el]) . ", " . Arrondi_1_ct($GLOBALS["Rabais" . $cpt_el]) . ", " .
              $prix_multi;
            if ($Mode == 3) {
              $dateRecu = $GLOBALS["DateRecu" . $cpt_el];
              if (isset($dateRecu) && !empty($dateRecu)) {
                $dateRecu = "'" . $dateRecu . "'";
              } else {
                $dateRecu = 'NULL';
              }
              $destinataire = $GLOBALS["Destinataire" . $cpt_el];
              if (isset($destinataire) && !empty($destinataire)) {
                $destinataire = "'" . addslashes($destinataire) . "'";
              } else {
                $destinataire = 'NULL';
              }
              $requette .= ", " . Min_zero($GLOBALS["NbRecu" . $cpt_el]) . ", " . $dateRecu . ", " . $destinataire . "";
              if (intval($GLOBALS["NbRecu" . $cpt_el]) != intval($GLOBALS["Quantite" . $cpt_el])) {
                $recu_tout = false;
              }
            }
            $requette .= ")";
            //echo $requette . "<BR/>\n";
            Connection::executeRawQuery($requette);
            if ($Mode != 0) {
              if (!empty($GLOBALS["NoArticle" . $cpt_el])) {
                $noArticleRR = Texte_Sans_Espace($GLOBALS["NoArticle" . $cpt_el]);
                $resultat_existe_stock = Stock::getStockByNoArticleRR(addslashes($noArticleRR));
                if ($Mode == 1) {
                  if ($resultat_existe_stock) { // UPDATE
                    $requette2 = "UPDATE stock" . ID_GARAGE . " SET EnStock = EnStock - (" . Arrondi_1_ct($GLOBALS["Quantite" . $cpt_el]) . ") WHERE NoArticleRR = '" . addslashes($noArticleRR) . "'";
                  } else { // INSERT
                    $requette2 = "INSERT INTO stock" . ID_GARAGE . " (`NoArticleRR` ,`LieuxStock` ,`EnStock` ,`EnTransfert`) VALUES ('" . addslashes($noArticleRR) . "', NULL , -(" . Arrondi_1_ct($GLOBALS["Quantite" . $cpt_el]) . "), 0);";
                  }
                } else if ($Mode == 2) {
                  if ($resultat_existe_stock) { // UPDATE
                    $requette2 = "UPDATE stock" . ID_GARAGE . " SET EnStock = EnStock + (" . Arrondi_1_ct($GLOBALS["Quantite" . $cpt_el]) . ") WHERE NoArticleRR = '" . addslashes($noArticleRR) . "'";
                  } else { // INSERT
                    $requette2 = "INSERT INTO stock" . ID_GARAGE . " (`NoArticleRR` ,`LieuxStock` ,`EnStock` ,`EnTransfert`) VALUES ('" . addslashes($noArticleRR) . "', NULL , +(" . Arrondi_1_ct($GLOBALS["Quantite" . $cpt_el]) . "), 0);";
                  }
                } else if ($Mode == 3) {
                  if ($resultat_existe_stock) { // UPDATE
                    $requette2 = "UPDATE stock" . ID_GARAGE . " SET EnStock = EnStock + (" . Arrondi_1_ct($GLOBALS["NbRecu" . $cpt_el]) . "), EnTransfert = EnTransfert + (" . (Arrondi_1_ct($GLOBALS["Quantite" . $cpt_el]) - Arrondi_1_ct($GLOBALS["NbRecu" . $cpt_el])) . ") WHERE NoArticleRR = '" . addslashes($noArticleRR) . "'";
                  } else { // INSERT
                    $requette2 = "INSERT INTO stock" . ID_GARAGE . " (`NoArticleRR` ,`LieuxStock` ,`EnStock` ,`EnTransfert`) VALUES ('" . addslashes($noArticleRR) . "', NULL , +(" . Arrondi_1_ct($GLOBALS["NbRecu" . $cpt_el]) . "), " . (Arrondi_1_ct($GLOBALS["Quantite" . $cpt_el]) - Arrondi_1_ct($GLOBALS["NbRecu" . $cpt_el])) . ");";
                  }
                }
                //echo $requette2 . "<BR/>\n";
                Connection::executeRawQuery($requette2);
              }
            }
            $pos++;
            break;
          case "inter":
            CommandeArticle::insert($NoCommande, $pos, 2, '', addslashes($GLOBALS["Description" . $cpt_el]), 0, 0, 0, 0, 0, 0);
            $pos++;
            break;
          case "partiel":
            CommandeArticle::insert($NoCommande, $pos, 5, '', addslashes($GLOBALS["Description" . $cpt_el]), 0, 0, 0, 0, 0, 0);
            $pos++;
            break;
          case "partiel2":
            CommandeArticle::insert($NoCommande, $pos, 7, '', addslashes($GLOBALS["Description" . $cpt_el]), 0, 0, 0, 0, 0, 0);
            $pos++;
            break;
          case "texte":
            //echo "texte " . $pos . "<BR/>\n";
            $arr_texte = explode("\r\n", $GLOBALS["Texte" . $cpt_el]);
            if (isset($GLOBALS["Gras" . $cpt_el])) {
              $type_data_text = 6;
            } else {
              $type_data_text = 1;
            }
            foreach ($arr_texte as $ligne_texte) {
              CommandeArticle::insert($NoCommande, $pos, $type_data_text, '', addslashes($ligne_texte), 0, 0, 0, 0, 0, 0);
              //echo $requette . "<BR/>\n";
              $pos++;
            }
            break;
          default:
            break;
        }
      }
    }
  }
  $array_article_diff = array();
  foreach (array_keys($array_article_prec) as $key) {
    if (array_key_exists($key, $array_article_suiv)) {
      if (($array_article_suiv[$key] - $array_article_prec[$key]) != 0) {
        $array_article_diff[$key] = $array_article_suiv[$key] - $array_article_prec[$key];
      }
    } else {
      $array_article_diff[$key] = - ($array_article_prec[$key]);
    }
  }
  foreach (array_keys($array_article_suiv) as $key) {
    if (array_key_exists($key, $array_article_prec)) {
    } else {
      $array_article_diff[$key] = $array_article_suiv[$key];
    }
  }
  $array_prix_diff = array();
  foreach (array_keys($array_prix_prec) as $key) {
    if (array_key_exists($key, $array_prix_suiv)) {
      if (($array_prix_suiv[$key] - $array_prix_prec[$key]) != 0) {
        $array_prix_diff[$key] = $array_prix_suiv[$key] - $array_prix_prec[$key];
      }
    } else {
      $array_prix_diff[$key] = - ($array_prix_prec[$key]);
    }
  }
  foreach (array_keys($array_prix_suiv) as $key) {
    if (array_key_exists($key, $array_prix_prec)) {
    } else {
      $array_prix_diff[$key] = $array_prix_suiv[$key];
    }
  }
  // print_r($array_article_prec);
  // print_r($array_prix_prec);
  // print_r($array_article_suiv);
  // print_r($array_prix_suiv);
  // print_r($array_article_diff);
  // print_r($array_prix_diff);

  foreach ($array_article_diff as $key => $value) {
    if (array_key_exists($key, $array_prix_diff)) {
      LogMVTPieces::insertNowWithCurrentUser($key, $value, $array_prix_diff[$key], $NoCommande);
    } else {
      LogMVTPieces::insertNowWithCurrentUser($key, $value, 0, $NoCommande);
    }
  }
  foreach ($array_prix_diff as $key => $value) {
    if (array_key_exists($key, $array_article_diff)) {
    } else {
      LogMVTPieces::insertNowWithCurrentUser($key, 0, $value, $NoCommande);
    }
  }
  //return;
  if (false) {
    $prix_multi = $GLOBALS["MemQuantite" . $cpt] * $GLOBALS["MemPrix" . $cpt] * ((100 + $GLOBALS["MemRabais" . $cpt]) / 100);
    if ($GLOBALS["MemTVA" . $cpt] > 0) {
      $prix_multi = $prix_multi * ((100 + $GLOBALS["MemTVA" . $cpt]) / 100);
    }
    if ($Mode == 3) {
      $prix_multi = Arrondi_1_ct($prix_multi);
    } else {
      $prix_multi = Arrondi_5_ct($prix_multi);
    }
    $requette = "INSERT INTO commandearticles" . ID_GARAGE . " (NoCommande, Position, TypeData, NoArticle, Description, TVA, GM, Quantite, PrixBase, Rabais, PrixMulti";
    if ($Mode == 3) {
      $requette .= ", NbRecu, DateRecu, Dest";
    }
    $requette .= ") VALUES (" .
      "$NoCommande, " . ($cpt + 1) . ", " . $GLOBALS["MemTypeData" . $cpt] . ", '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "', '" . addslashes($GLOBALS["MemDescription" . $cpt]) .
      "', " . Arrondi_5_ct($GLOBALS["MemTVA" . $cpt]) . ", " . Min_zero($GLOBALS["MemGM" . $cpt]) . ", " . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", " . Arrondi_5_ct($GLOBALS["MemPrix" . $cpt]) . ", " . Arrondi_1_ct($GLOBALS["MemRabais" . $cpt]) . ", " .
      $prix_multi;
    if ($Mode == 3) {
      $requette .= ", " . Min_zero($GLOBALS["MemNbRecu" . $cpt]) . ", '" . $GLOBALS["MemDateRecu" . $cpt] . "', '" . addslashes($GLOBALS["MemDest" . $cpt]) . "'";
      if (intval($GLOBALS["NbRecu" . $cpt_el]) != intval($GLOBALS["Quantite" . $cpt_el])) {
        $recu_tout = false;
      }
    }
    $requette .= ")";
    if ($resultat = Connection::executeRawQuery($requette)) {
    } else {
      echo "KO<BR>\n";
    }
    if ($Mode != 0) {
      if (!empty($GLOBALS["MemNoArticle" . $cpt])) {
        $noArticleRR = Texte_Sans_Espace($GLOBALS["MemNoArticle" . $cpt]);
        $resultat_existe_stock = Stock::getStockByNoArticleRR(addslashes($noArticleRR));
        if ($Mode == 1) {
          if ($resultat_existe_stock) { // UPDATE
            $requette2 = "UPDATE stock" . ID_GARAGE . " SET EnStock = EnStock - (" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ") WHERE NoArticleRR = '" . addslashes($noArticleRR) . "'";
          } else { // INSERT
            $requette2 = "INSERT INTO stock" . ID_GARAGE . " (`NoArticleRR` ,`LieuxStock` ,`EnStock` ,`EnTransfert`) VALUES ('" . addslashes($noArticleRR) . "', NULL , -(" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . "), 0);";
          }
        } else if ($Mode == 2) {
          if ($resultat_existe_stock) { // UPDATE
            $requette2 = "UPDATE stock" . ID_GARAGE . " SET EnStock = EnStock + (" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ") WHERE NoArticleRR = '" . addslashes($noArticleRR) . "'";
          } else { // INSERT
            $requette2 = "INSERT INTO stock" . ID_GARAGE . " (`NoArticleRR` ,`LieuxStock` ,`EnStock` ,`EnTransfert`) VALUES ('" . addslashes($noArticleRR) . "', NULL , " . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", 0);";
          }
        } else if ($Mode == 3) {
          if ($resultat_existe_stock) { // UPDATE
            $requette2 = "UPDATE stock" . ID_GARAGE . " SET EnStock = EnStock + (" . Arrondi_1_ct($GLOBALS["MemNbRecu" . $cpt]) . "), EnTransfert = EnTransfert + (" . (Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) - Arrondi_1_ct($GLOBALS["MemNbRecu" . $cpt])) . ") WHERE NoArticleRR = '" . addslashes($noArticleRR) . "'";
          } else { // INSERT
            $requette2 = "INSERT INTO stock" . ID_GARAGE . " (`NoArticleRR` ,`LieuxStock` ,`EnStock` ,`EnTransfert`) VALUES ('" . addslashes($noArticleRR) . "', NULL , " . Arrondi_1_ct($GLOBALS["MemNbRecu" . $cpt]) . ", (" . (Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) - Arrondi_1_ct($GLOBALS["MemNbRecu" . $cpt])) . "));";
          }
        }
        Connection::executeRawQuery($requette2);
        if ($Mode == 1) {
          /*$requette2 = "SELECT * FROM articles WHERE  NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
            if($resultat2 = mysql_query($requette2))
            {
              if($ligne2 = mysql_fetch_array($resultat2))
              {
                if($ligne2['Annee1']==date("Y"))
                {
                  $requette3 = "UPDATE articles SET NombreVendu1 = NombreVendu1 + (" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . "), SommeVendu1 = SommeVendu1 + (" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ") WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee2']==date("Y"))
                {
                  $requette3 = "UPDATE articles SET NombreVendu2 = NombreVendu2 + (" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . "), SommeVendu2 = SommeVendu2 + (" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ") WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee3']==date("Y"))
                {
                  $requette3 = "UPDATE articles SET NombreVendu3 = NombreVendu3 + (" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . "), SommeVendu3 = SommeVendu3 + (" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ") WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee1']==0)
                {
                  $requette3 = "UPDATE articles SET NombreVendu1 = " . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", SommeVendu1 = " . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ", Annee1 = ".date("Y")." WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee2']==0)
                {
                  $requette3 = "UPDATE articles SET NombreVendu2 = " . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", SommeVendu2 = " . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ", Annee2 = ".date("Y")." WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee3']==0)
                {
                  $requette3 = "UPDATE articles SET NombreVendu3 = " . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", SommeVendu3 = " . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ", Annee3 = ".date("Y")." WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else
                {
                  $requette3 = "UPDATE articles SET Annee1 = Annee2, NombreVendu1 = NombreVendu2, SommeVendu1 = SommeVendu2, Annee2 = Annee3, NombreVendu2 = NombreVendu3, SommeVendu2 = SommeVendu3, NombreVendu3 = " . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", SommeVendu3 = " . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ", Annee3 = ".date("Y")." WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                $resultat3 = mysql_query($requette3);
              }
            }*/
        }
        if ($Mode == 2) {
          /*$requette2 = "SELECT * FROM articles WHERE  NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
            if($resultat2 = mysql_query($requette2))
            {
              if($ligne2 = mysql_fetch_array($resultat2))
              {
                if($ligne2['Annee1']==date("Y"))
                {
                  $requette3 = "UPDATE articles SET NombreVendu1 = NombreVendu1 - (" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . "), SommeVendu1 = SommeVendu1 - (" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ") WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee2']==date("Y"))
                {
                  $requette3 = "UPDATE articles SET NombreVendu2 = NombreVendu2 - (" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . "), SommeVendu2 = SommeVendu2 - (" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ") WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee3']==date("Y"))
                {
                  $requette3 = "UPDATE articles SET NombreVendu3 = NombreVendu3 - (" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . "), SommeVendu3 = SommeVendu3 - (" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ") WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee1']==0)
                {
                  $requette3 = "UPDATE articles SET NombreVendu1 = -" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", SommeVendu1 = -" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ", Annee1 = ".date("Y")." WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee2']==0)
                {
                  $requette3 = "UPDATE articles SET NombreVendu2 = -" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", SommeVendu2 = -" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ", Annee2 = ".date("Y")." WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else if($ligne2['Annee3']==0)
                {
                  $requette3 = "UPDATE articles SET NombreVendu3 = -" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", SommeVendu3 = -" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ", Annee3 = ".date("Y")." WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                else
                {
                  $requette3 = "UPDATE articles SET Annee1 = Annee2, NombreVendu1 = NombreVendu2, SommeVendu1 = SommeVendu2, Annee2 = Annee3, NombreVendu2 = NombreVendu3, SommeVendu2 = SommeVendu3, NombreVendu3 = -" . Arrondi_1_ct($GLOBALS["MemQuantite" . $cpt]) . ", SommeVendu3 = -" . Arrondi_1_ct($GLOBALS["MemPrixTotal" . $cpt]) . ", Annee3 = ".date("Y")." WHERE NoArticle = '" . addslashes($GLOBALS["MemNoArticle" . $cpt]) . "'";
                }
                $resultat3 = mysql_query($requette3);
              }
            }*/
        }
      }
    }
  }
  if ($Mode == 3) {
    if ($recu_tout) {
      Commande::updateRecuToOByNoCommande($NoCommande);
    } else {
      Commande::updateRecuToNByNoCommande($NoCommande);
    }
  }
}

?>