<SCRIPT language=JavaScript src='popup.js' type=text/javascript></SCRIPT>
<?php
require 'database.inc.php';
if (Test_User($lg_user, $lg_password) == TRUE) {
  clear_cache(5, 2);
  $date = date("Y-m-d");
  if (!isset($NoClient)) {
    $NoClient = 0;
  }
  $date_debut = Decode_Entree_Type($Date, 2);
  $Date_jour = substr($date_debut, 8, 2);
  $Date_mois = substr($date_debut, 5, 2);
  $Date_annee = substr($date_debut, 0, 4);
  //$date_debut="$Date_annee-".Chiffre_2_Car($Date_mois)."-".Chiffre_2_Car($Date_jour);
  //$heure_debut=Chiffre_2_Car($HD_heure) . ":" . Chiffre_2_Car($HD_minute) . ":00";
  $heure_debut = "08:00:00";
  $date_fin = $date_debut . " 18:00:00";
  if (isset($VhcPret)) {
    $reqPret = ", VhcPret = '1'";
  } else {
    $reqPret = ", VhcPret = '0'";
  }
  if (isset($new)) {
    $requette = "INSERT INTO atelier" . ID_GARAGE . " (NoClient) values ('$NoClient')";
    if (Connection::executeRawQuery($requette)) {
      $NoAtelier = Connection::getConnection()->lastInsertId();
      if (!empty($vhc_pret)) {
        $reqPret = ", VhcPret = '1'";
        if (true) // ICI LA NOUVELLE FACON DE METTRE DES DATE PRECISES POUR LES VEHICULES DE PRET
        {
          //$location = "location.href='location.php?new=1&jour=".Chiffre_2_Car($Date_jour)."&mois=".Chiffre_2_Car($Date_mois)."&anneed=".$Date_annee."&periode=0&vhc=".$vhc_pret."&NoClient=$NoClient&Nom=".urlencode($Nom)."&Prenom=".urlencode($Prenom)."&Telephone=".urlencode($Telephone)."';\n";
          $location = "location.href='location.php?new=1&jour=" . Chiffre_2_Car($Date_jour) . "&mois=" . Chiffre_2_Car($Date_mois) . "&anneed=" . $Date_annee . "&periode=0&vhc=" . $vhc_pret . "&NoClient=$NoClient&Nom=" . urlencode($Nom) . "&Prenom=" . urlencode($Prenom) . "&Telephone=" . urlencode($Telephone) . "';\n";
        } else {
          $resultat_loc = Location::getByNoChassisAndDate(addslashes($vhc_pret), $date_debut . ' ' . $heure_debut, $date_fin);
          $ligne_loc = count($resultat_loc);
          if ($ligne_loc != 0) {
            $err = true;
            echo "le véhicule de prêt est indisponible durant cette période";
          } else {
            $requette = "INSERT INTO location" . ID_GARAGE . " (NoChasis, Nom, Prenom, Telephone, Debut, Fin, TypeTarif, Tarif, NbUnites, Rabais, Total, Etape, NoClient, Pret) values ('";
            $requette .= addslashes($vhc_pret) . "', '" . addslashes($Nom) . "', '" . addslashes($Prenom) . "', '" . addslashes($Telephone) . "', " .
              "'$date_debut $heure_debut', '$date_fin', 0, 0, 0, 0, 0, 0, ";
            if (empty($NoClient)) {
              $requette .= "NULL";
            } else {
              $requette .= $NoClient;
            }
            $requette .= ", 1)";
            Connection::executeRawQuery($requette);
          }
        }
      }
    }
  }
  //echo "NbDatesAutre=".$NbDatesAutre."...<br/>";
  $arrayDatesAutre = array();
  $arrayNewDatesAutre = array();
  for ($cptDatesAutre = 1; $cptDatesAutre <= $NbDatesAutre; $cptDatesAutre++) {
    //echo $cptDatesAutre."<br/>";
    $dateAutre = ${"Date" . $cptDatesAutre};
    $tempsAutre = ${"Temps" . $cptDatesAutre};
    $mecanoAutre = ${"Mecano" . $cptDatesAutre};
    $noSuite = ${"NoSuite" . $cptDatesAutre};
    //echo "$noSuite $dateAutre $tempsAutre $mecanoAutre<br/>";
    if ($noSuite == "New" && strlen($dateAutre) > 0 && strlen($dateAutre) > 0 && strlen($mecanoAutre) > 0) {
      //echo "New date<br/>";

      array_push($arrayNewDatesAutre, $cptDatesAutre);
    } else if (strlen($dateAutre) > 0 && strlen($dateAutre) > 0 && strlen($mecanoAutre) > 0) {
      //echo "Pos $cptDatesAutre<br/>";
      $arrayDatesAutre[$noSuite] = $cptDatesAutre;
      //array_push($arrayDatesAutre, $cptDatesAutre);
    }
  }
  $requettedatesautre = "SELECT * FROM atelier_suite" . ID_GARAGE . " WHERE NoAtelier = $NoAtelier";
  //echo "$requettedatesautre<br/>";
  $resultatdatesautre = Connection::executeRawQueryWithfetchAll($requettedatesautre);
  foreach ($resultatdatesautre as $lignedatesautre) {
    if (isset($arrayDatesAutre[$lignedatesautre["NoSuite"]])) {
      //echo "Suite ".$arrayDatesAutre[$lignedatesautre["NoSuite"]]." ".$lignedatesautre["NoSuite"]." déjà là !<br/>";
      $idDateAutre = $lignedatesautre["NoSuite"];
      $posDateAutre = $arrayDatesAutre[$lignedatesautre["NoSuite"]];
      $requettesuite = "UPDATE atelier_suite" . ID_GARAGE . " SET Date = '" . Decode_Entree_Type(${"Date" . $posDateAutre}, 2) . "', Temps = " . ${"Temps" . $posDateAutre} . ", Mecano = " . ${"Mecano" . $posDateAutre} . " WHERE NoSuite = $idDateAutre";
      Connection::executeRawQuery($requettesuite);
      //echo "$requettesuite<br/>";
    } else {
      //echo "Supprimer suite ".$lignedatesautre["NoSuite"]."<br/>";
      $idDateAutre = $lignedatesautre["NoSuite"];
      $requettesuite = "DELETE FROM atelier_suite" . ID_GARAGE . " WHERE NoSuite = $idDateAutre";
      Connection::executeRawQuery($requettesuite);
      //echo "$requettesuite<br/>";
    }
  }
  foreach ($arrayNewDatesAutre as $dateAutre) {
    //echo "$dateAutre ajout<br/>";
    $requettesuite = "INSERT INTO atelier_suite" . ID_GARAGE . " (NoAtelier, Date, Temps, Mecano) VALUES ($NoAtelier, '" . Decode_Entree_Type(${"Date" . $dateAutre}, 2) . "', " . ${"Temps" . $dateAutre} . ", " . ${"Mecano" . $dateAutre} . ")";
    Connection::executeRawQuery($requettesuite);
    //echo "$requettesuite<br/>";
  }

  //$Description = mb_convert_encoding($Description, "UTF-8");
  $requette2 = "DELETE FROM atelier_option" . ID_GARAGE . " WHERE Id_atelier = $NoAtelier";
  Connection::executeRawQuery($requette2);
  if ($vhc != 0) {
    $requette2 = "SELECT service_option.Nom_court, vhc_option.Id  FROM vhc_option, service_option WHERE vhc_option.Id_vhc = $vhc AND vhc_option.Id_option = service_option.Id";
    $resultat2 = Connection::executeRawQueryWithfetchAll($requette2);
    foreach ($resultat2 as $ligne2) {
      if (isset(${"option_" . $ligne2["Id"]})) {
        $requette3 = "INSERT INTO atelier_option" . ID_GARAGE . " (Id_Atelier, Id_Option) VALUES ($NoAtelier, " . $ligne2["Id"] . ")";
        Connection::executeRawQuery($requette3);
      }
    }
  }
  switch ($etape) {
    case 0:
      $requette = "UPDATE atelier" . ID_GARAGE . " SET NoClient='$NoClient', Nom=" . Connection::getConnection()->quote($Nom) . ", Prenom=" . Connection::getConnection()->quote($Prenom) . ", Telephone='$Telephone', NoChasis='$NoChasis'," .
        " Vehicule='$Vehicule', Km='$Km', Date='$date_debut', Heure='$heure_debut', Temps='$Temps', Description='" . addslashes($Description) . "'," .
        " Restitution='$date_fin', Reception='" . addslashes($Reception) . "', Etape=0, Mecano='$Mecano', Id_Vhc='$vhc', Id_Service='$service'$reqPret WHERE NoAtelier=$NoAtelier";
      if ($resultat = Connection::executeRawQuery($requette)) {
        if ($Acompte != 0) {
          $NoCommande = Trouve_No_Commande_Libre("FD");
          $date = date("Y-m-d");
          if (empty($NoClient)) {
            $nc = "NULL";
          } else {
            $nc = $NoClient;
          }
          $requette = "INSERT INTO commande" . ID_GARAGE . " (NoCommande,Type,Genre,PersonneModif,NoClient,DateCommande,DateModification,MontantTotal,APayer,DateDelaisPayement) VALUES " .
            "($NoCommande, 'FD', 'F', '$lg_user', $nc, '$date', '$date', 0, -$Acompte, '" . date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") + 30, date("Y"))) . "')";
          if ($resultat = Connection::executeRawQuery($requette)) {
            $no_caisse = 1;
            $mode_payement = 1;
            $TabModePayement = explode(" ", $ModePayement);
            if (count($TabModePayement) == 2) {
              $mode_payement = $TabModePayement[0];
              $no_caisse = $TabModePayement[1];
            }
            $requette = "INSERT INTO dbcash" . ID_GARAGE . " (NoFacture, PersonneEncaissement, Date, Somme, TVA, ModePayement, NoCaisse) VALUES" .
              " ($NoCommande, '$lg_user', '$date " . date("H:i") . ":00', $Acompte, -" . get_config('TVA') . ", $mode_payement, $no_caisse)";
            echo $requette . "<BR />\n";
            Connection::executeRawQuery($requette);
            $no_cash = Connection::getConnection()->lastInsertId();
            print_quitance($no_cash);
          }
          Connection::executeRawQuery("UPDATE atelier" . ID_GARAGE . " SET NoCommande = $NoCommande, Acompte = $Acompte WHERE NoAtelier = $NoAtelier");
        }
        echo "<script language=JavaScript>\n";
        echo "this.opener.location.reload();\n";
        if ($pri == 1) {
          print_fiche_atelier($NoAtelier);
        }
        if ($prientete == 1) {
          print_entete($NoAtelier);
        }
        if ($prientete2 == 1) {
          print_entete2($NoAtelier);
        }
        if (isset($location)) {
          echo $location;
        } else {
          echo "close_popup();\n";
        }
        echo "</script>\n";
      } else {
        echo $requette;
        echo "<BR>KO<BR>";
        echo Connection::getConnection()->errorInfo();
      }
      break;
    case 1:
      $requette = "UPDATE atelier" . ID_GARAGE . " SET NoClient='$NoClient', Nom='" . Connection::getConnection()->quote($Nom) . "', Prenom='" . Connection::getConnection()->quote($Prenom) . "', Telephone='$Telephone', NoChasis='$NoChasis'," .
        " Vehicule='$Vehicule', Km='$Km', Date='$date_debut', Heure='$heure_debut', Temps='$Temps', Description='" . addslashes($Description) . "'," .
        " Restitution='$date_fin', Reception='" . addslashes($Reception) . "', Etape=1, Mecano='$Mecano', Id_Vhc='$vhc', Id_Service='$service'$reqPret WHERE NoAtelier=$NoAtelier";
      if ($resultat = Connection::executeRawQuery($requette)) {
        if ($Acompte != 0) {
          $NoCommande = Trouve_No_Commande_Libre("FD");
          $date = date("Y-m-d");
          if (empty($NoClient)) {
            $nc = "NULL";
          } else {
            $nc = $NoClient;
          }
          $requette = "INSERT INTO commande" . ID_GARAGE . " (NoCommande,Type,Genre,PersonneModif,NoClient,DateCommande,DateModification,MontantTotal,APayer,DateDelaisPayement) VALUES " .
            "($NoCommande, 'FD', 'F', '$lg_user', $nc, '$date', '$date', 0, -$Acompte, '" . date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") + 30, date("Y"))) . "')";
          if ($resultat = Connection::executeRawQuery($requette)) {
            $no_caisse = 1;
            $mode_payement = 1;
            $TabModePayement = explode(" ", $ModePayement);
            if (count($TabModePayement) == 2) {
              $mode_payement = $TabModePayement[0];
              $no_caisse = $TabModePayement[1];
            }
            $requette = "INSERT INTO dbcash" . ID_GARAGE . " (NoFacture, PersonneEncaissement, Date, Somme, TVA, ModePayement, NoCaisse) VALUES" .
              " ($NoCommande, '$lg_user', '$date " . date("H:i") . ":00', $Acompte, -" . get_config('TVA') . ", $mode_payement, $no_caisse)";
            echo $requette . "<BR />\n";
            Connection::executeRawQuery($requette);
            $no_cash = Connection::getConnection()->lastInsertId();
            print_quitance($no_cash);
          }
          Connection::executeRawQuery("UPDATE atelier" . ID_GARAGE . " SET NoCommande = $NoCommande, Acompte = $Acompte WHERE NoAtelier = $NoAtelier");
        }
        echo "<script language=JavaScript>\n";
        echo "this.opener.location.reload();\n";
        if ($pri == 1) {
          print_fiche_atelier($NoAtelier);
        }
        if ($prientete == 1) {
          print_entete($NoAtelier);
        }
        if ($prientete2 == 1) {
          print_entete2($NoAtelier);
        }
        if (isset($location)) {
          echo $location;
        } else {
          echo "close_popup();\n";
        }
        echo "</script>\n";
      } else {
        echo $requette;
        echo "<BR>KO<BR>";
        echo Connection::getConnection()->errorInfo();
      }
      break;
    case 2:
      if (!empty($NoChasis)) {
        $requette = "UPDATE vehicules SET Km=$Km, DateService='$date_debut' WHERE NoChasis='$NoChasis'";
        echo $requette . "<BR>\n";
        if ($resultat = Connection::executeRawQuery($requette)) {
        }
      }
      if ($ligne = Atelier::getAtelierByNoAtelier($NoAtelier)) {
        $prev_etape = $ligne['Etape'];
        if (!empty($NoCommande)) {
          if ($ligne = Commande::getCommandeByNoCommande($NoCommande)) {
            $Type = $ligne['Type'];
            $Genre = $ligne['Genre'];
          }
        } else if (empty($ligne['NoCommande'])) {
          switch ($fact) {
            case 1:
              $Type = "FD";
              $Genre = "F";
              break;
            case 2:
              $Type = "GF";
              $Genre = "G";
              break;
            case 3:
              $Type = "GG";
              $Genre = "G";
              break;
            case 4:
              $Type = "DP";
              $Genre = "D";
              break;
            case 5:
              $Type = "FI";
              $Genre = "F";
              break;
          }
          if ($service != 0) {
            echo "location.href='service.php?NoAtelier=$NoAtelier&Type=$Type';\n";
            $NoCommande = 0;
          } else {
            $NoCommande = Trouve_No_Commande_Libre($Type);
            $no_plaque = "";
            if (!empty($NoChasis)) {
              $ligne = Vehicule::getVehiculeByNoChassis(addslashes($NoChasis));
              $no_plaque = $ligne['NoPlaque'];
            }
            $requette = "INSERT INTO commande" . ID_GARAGE . " (NoCommande,Type,Genre,PersonneModif,NoClient,Vehicule,KmVhc,NoPlaque,DateCommande,DateModification,DateDelaisPayement)" .
              "values ($NoCommande, '$Type', '$Genre', '$lg_user', '$NoClient', '" . addslashes($NoChasis) . "', '$Km', '$no_plaque', '" . date("Y-m-d") . "', '" . date("Y-m-d") . "', '" . date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") + 30, date("Y"))) . "')";
            echo $requette;
            if ($resultat = Connection::executeRawQuery($requette)) {
              $arrayDescription = explode("\n", $Description);
              for ($cpt = 1; $cpt <= count($arrayDescription); $cpt++) {
                $requette = "INSERT INTO commandearticles" . ID_GARAGE . " (NoCommande, Position, TypeData, NoArticle, Description, TVA, GM, Quantite, PrixBase, Rabais, PrixMulti) VALUES (" .
                  "$NoCommande, $cpt, 1, '', '" . addslashes($arrayDescription[$cpt - 1]) . "', 0, 0, 0, 0, 0, 0)";
                if ($resultat = Connection::executeRawQuery($requette)) {
                }
              }
              echo "OK";
            } else {
              echo "KO";
            }
          }
        } else {
          $NoCommande = $ligne['NoCommande'];
          if ($ligne = Commande::getCommandeByNoCommande($NoCommande)) {
            $Type = $ligne['Type'];
            $Genre = $ligne['Genre'];
          }
        }
      }
      if ($service != 0 && $prev_etape != 2) {
        $requette = "UPDATE atelier" . ID_GARAGE . " SET NoClient='$NoClient', Nom='" . Connection::getConnection()->quote($Nom) . "', Prenom='" . Connection::getConnection()->quote($Prenom) . "', Telephone='$Telephone', NoChasis='$NoChasis'," .
          " Vehicule='$Vehicule', Km='$Km', Date='$date_debut', Heure='$heure_debut', Temps='$Temps', Description='" . addslashes($Description) . "'," .
          " Restitution='$date_fin', Etape=1, NoCommande=$NoCommande, Mecano='$Mecano', Id_Vhc='$vhc', Id_Service='$service'$reqPret WHERE NoAtelier=$NoAtelier";
      } else {
        $requette = "UPDATE atelier" . ID_GARAGE . " SET NoClient='$NoClient', Nom='" . Connection::getConnection()->quote($Nom) . "', Prenom='" . Connection::getConnection()->quote($Prenom) . "', Telephone='$Telephone', NoChasis='$NoChasis'," .
          " Vehicule='$Vehicule', Km='$Km', Date='$date_debut', Heure='$heure_debut', Temps='$Temps', Description='" . addslashes($Description) . "'," .
          " Restitution='$date_fin', Etape=2, NoCommande=$NoCommande, Mecano='$Mecano', Id_Vhc='$vhc', Id_Service='$service'$reqPret WHERE NoAtelier=$NoAtelier";
      }
      if ($resultat = Connection::executeRawQuery($requette)) {
        $Sous_Type = 1;
        echo "<script language=JavaScript>\n";
        if ($pri == 1) {
          echo "this.opener.location.reload();\n";
          print_fiche_atelier($NoAtelier);
          echo "close_popup();\n";
        } else {
          if ($service != 0 && $prev_etape != 2) {
            echo "location.href='service.php?NoAtelier=$NoAtelier&Type=$Type&Genre=$Genre';\n";
          } else {
            echo "this.opener.location='default.php?Type=4&Sous_Type=$Sous_Type&Etape=3&New=0&NoCommande=$NoCommande&NoClient=$NoClient';\n";
            echo "close_popup();\n";
          }
        }
        if ($prientete == 1) {
          print_entete($NoAtelier);
        }
        if ($prientete2 == 1) {
          print_entete2($NoAtelier);
        }
        echo "</script>\n";
      } else {
        echo $requette;
        echo "<BR>KO<BR>";
        echo Connection::getConnection()->errorInfo();
      }
      break;
    case 3:
      if (!empty($NoChasis)) {
        $requette = "UPDATE vehicules SET Km=$Km, DateService='$date_debut' WHERE NoChasis='$NoChasis'";
        echo $requette . "<BR>\n";
        if ($resultat = Connection::executeRawQuery($requette)) {
        }
      }
      $requette = "UPDATE atelier" . ID_GARAGE . " SET NoClient='$NoClient', Nom='" . Connection::getConnection()->quote($Nom) . "', Prenom='" . Connection::getConnection()->quote($Prenom) . "', Telephone='$Telephone', NoChasis='$NoChasis'," .
        " Vehicule='$Vehicule', Km='$Km', Date='$date_debut', Heure='$heure_debut', Temps='$Temps', Description='" . addslashes($Description) . "'," .
        " Restitution='$date_fin', Etape=3, NoCommande=NULL, Mecano='$Mecano', Id_Vhc='$vhc', Id_Service='$service'$reqPret WHERE NoAtelier=$NoAtelier";
      if ($resultat = Connection::executeRawQuery($requette)) {
        echo "<script language=JavaScript>\n";
        echo "this.opener.location.reload();\n";
        if ($pri == 1) {
          print_fiche_atelier($NoAtelier);
        }
        if ($prientete == 1) {
          print_entete($NoAtelier);
        }
        if ($prientete2 == 1) {
          print_entete2($NoAtelier);
        }
        echo "close_popup();\n";
        echo "</script>\n";
      } else {
        echo $requette;
        echo "<BR>KO<BR>";
        echo Connection::getConnection()->errorInfo();
      }
      break;
    case 99:
      if ($web == 1) {
        $requette = "UPDATE atelier" . ID_GARAGE . " SET NoClient='$NoClient', Nom='" . Connection::getConnection()->quote($Nom) . "', Prenom='" . Connection::getConnection()->quote($Prenom) . "', Telephone='$Telephone', NoChasis='$NoChasis'," .
          " Vehicule='$Vehicule', Km='$Km', Date='$date_debut', Heure='$heure_debut', Temps='$Temps', Description='" . addslashes($Description) . "'," .
          " Restitution='$date_fin', Reception='" . addslashes($Reception) . "', Etape=0, Mecano='$Mecano', Id_Vhc='$vhc', Id_Service='$service'$reqPret WHERE NoAtelier=$NoAtelier";
      } else {
        $requette = "DELETE FROM atelier" . ID_GARAGE . " WHERE NoAtelier=$NoAtelier";
      }
      if ($resultat = Connection::executeRawQuery($requette)) {
        $EmAil = GetEmail($NoClient);
        $mailsent = SendEmailSrvc($EmAil, $web, $date_debut, $Vehicule);
        echo "<script language=JavaScript>\n";
        echo "this.opener.location.reload();\n";
        if (isset($location)) {
          echo $location;
        } else {
          echo "close_popup();\n";
        }
        echo "</script>\n";
      } else {
        echo $requette;
        echo "<BR>KO<BR>";
        echo Connection::getConnection()->errorInfo();
      }
      break;
  }
}
?>