#include <infocon.style>
#include <shop.inc>

<page title="Online-Shop">

<sql_prepare>
# BEGIN ... COMMIT oder BEGIN ... ROLLBACK
<?
  # Porto erst einmal auf 20,-- festgesetzt
  $porto = 20.00;

  # Colors
  $ch = "<colh>";
  $cd = "<cold>";
  $cn = "<coln>";

  $tbest = "<tr bgcolor=\"%s\"><td colspan=\"4\" align=\"left\"><font face=\"Helvetica,Arial\">"
	     ."<b>Bestellung Nr. %d</b><p></font></td></tr>";

  $tind = "<tr bgcolor=\"$ch\"><th width=\"10%\"><font face=\"Helvetica,Arial\">Anzahl</font></th>"
         ."<th width=\"70%\" align=\"left\"><font face=\"Helvetica,Arial\">Artikel</font></th>"
         ."<th width=\"10%\" align=\"right\"><font face=\"Helvetica,Arial\">Einzel</font></th>"
         ."<th width=\"10%\" align=\"right\"><font face=\"Helvetica,Arial\">Gesamt</font></th></tr>";

  $trow = "<tr bgcolor=\"%s\"><td align=\"right\"><font face=\"Helvetica,Arial\">%d&nbsp;</font></td>"
	 ."<td align=\"left\"><font face=\"Helvetica,Arial\">"
	 ."<a href=\"show.php3?article=%s\">%s, %s</a></font></td>"
	 ."<td align=\"right\"><font face=\"Helvetica,Arial\">%6.2f</font></td>"
	 ."<td align=\"right\"><font face=\"Helvetica,Arial\">%6.2f</font></td></tr>";

  $tporto = "<tr bgcolor=\"%s\"><td align=\"right\"><font face=\"Helvetica,Arial\">1&nbsp;</font></td>"
	   ."<td align=\"left\"><font face=\"Helvetica,Arial\"><a href=\"porto.html\">Porto und Verpackung</a></font></td>"
	   ."<td align=\"right\"><font face=\"Helvetica,Arial\">%6.2f</font></td>"
	   ."<td align=\"right\"><font face=\"Helvetica,Arial\">%6.2f</font></td></tr>";

  $tsum = "<tr bgcolor=\"%s\"><th colspan=\"3\" align=\"left\"><font face=\"Helvetica,Arial\">Summe</font></th>"
	 ."<th align=\"right\"><font face=\"Helvetica,Arial\">%7.2f</font></th></tr>";


#	  Kundennr.      !Kundennr.
#	 /     \       Kundendaten vollständig
#	/       \        /   \
# korrekt    inkorrekt  /     \
#	\         \    /    Kunden aufnehmen
#	 \         \  /       /
#	  \      Hinweis     /
#	   \     ->Back     /
#	    \              /
#	     \            /
#	 Bestellung aufnehmen
#	    -> Lagerbestand ändern
#	    -> Bestelliste
#	 Bestätigung per Mail
#	     Danke im Web
#
#

  # Infobox für die Kundennummer und das Kennwort
  # 0="Firma"/"Name"; 1=Name; 2=Kundennr.; 3=Kennwort
  $pwinfo = "<div align=\"center\"><table border=\"0\" cellpadding=\"2\" cellspacing=\"0\" summary=\"\">"
	   ."<tr><td colspan=\"3\"bgcolor=\"<colh>\" align=\"center\"><font face=\"Helvetica,Arial\">"
	   ."<b>Ihre Kundendaten</b></font></td></tr>"
	   ."<tr><td bgcolor=\"<cold>\"><font face=\"Helvetica,Arial\"><b>%s</b></font></td>"
	   ."<td bgcolor=\"<coln>\">&nbsp;</td>"
	   ."<td bgcolor=\"<coln>\"><font face=\"Helvetica,Arial\">%s</font></td></tr>"
	   ."<tr><td bgcolor=\"<cold>\"><font face=\"Helvetica,Arial\"><b>Kundennr.</b></font></td>"
	   ."<td bgcolor=\"<coln>\">&nbsp;</td>"
	   ."<td bgcolor=\"<coln>\"><font face=\"Helvetica,Arial\">%s</font></td></tr>"
	   ."<tr><td bgcolor=\"<cold>\"><font face=\"Helvetica,Arial\"><b>Kennwort</b></font></td>"
	   ."<td bgcolor=\"<coln>\">&nbsp;</td>"
	   ."<td bgcolor=\"<coln>\"><font face=\"Helvetica,Arial\">%s</font></td></tr></table></div><p>";


  $ok = 0;

  #if ($HTTP_REFERER != "http://infocon.infodrom.org/shop/order.php3") {
  if (strcasecmp ($HTTP_REFERER, "http://wwww.infodrom.ffis.de/infocon.infodrom.org/shop/order.php3") != 0) {
    echo ("<p>Hier stimmt etwas nicht."); // nämlich fehlt der richtige Referer-Wert...
  } else /* Referer */ {

   if ((strlen ($customer) > 0) && (strlen ($passwd) > 0)) {
      $dbh = dbconnect();
      $sth = dbquery ($dbh, sprintf ("SELECT passwd FROM customer WHERE customer = %d", $customer));
      if (pg_NumRows ($sth) > 0) {
	$row = pg_fetch_array ($sth, 0);
	if ( (strlen ($row['passwd']) > 0) && ($passwd == $row['passwd'])) {
	  $ok = 1;
	} else {
	  echo ("<p>Das angegebene Kennwort stimmt nicht mit dem gespeicherten überein.");
	}
      } else {
	echo ("<p>Die angegebene Kundennummer ist falsch.");
      }
    } else /* customer && passwd */ {
      if ( (strlen ($lastname) > 0)
	&& (strlen ($firstname) > 0)
	&& (strlen ($street) > 0)
	&& (strlen ($plz) > 0)
	&& (strlen ($city) > 0)
	&& (strlen ($country) > 0) ) {

	<:
	  for $i (('company','firstname','lastname','appendix','street','city','country')) {
	    printf "    \$%s=sql_prepare (\$%s);\n", $i, $i;
	  }
	:>

	$dbh = dbconnect();
	$sth = dbquery ($dbh, "SELECT max(customer) FROM customer");
	if (pg_NumRows ($sth) > 0) {
	  $row = pg_fetch_array ($sth, 0);
	  $customer = $row[0] > <kdnrmin>?$row[0]:<kdnrmin>;
	  $customer++;

	  # Now try to get a password
	  #
	  $pwgen = popen ("pwgen 10", "r");
	  if (!feof ($pwgen)) {
	    $newpasswd = fgets ($pwgen, 255);
	    pclose ($pwgen);
	  }

	  # ACHTUNG: Hier fehlt jeglicher Sicherheitsmechanismus, der verhindern könnte, daß
	  #          eine Firma zig-mal direkt hintereinander mit Bestellungen ... (fixme)
	  $query = sprintf ("INSERT INTO customer (customer,company,firstname,lastname,appendix,street,plz,city,country,passwd) "
			   ."VALUES (%d,'%s','%s','%s','%s','%s',%d,'%s','%s','%s')",
			    $customer,$company,$firstname,$lastname,$appendix,$street,$plz,$city,$country,$newpasswd);
	  $sth = dbquery ($dbh, $query);

	  printf ($pwinfo, strlen ($company)?"Firma":"Name",
			   strlen ($company)?$company:$firstname . " " . $lastname, $customer, $newpasswd);
          $ok = 1;
	} else {
	  echo ("<p>Es ist ein Datenbankfehler aufgetreten.");
	}

      } else {
	echo ("<p>Nicht alle erforderlichen Felder sind ausgefüllt.");
      }
    }
  }

  if ($ok) {
    <btable_begin>

    # Queries to insert Bestellung...

    $sth = dbquery ($dbh, "SELECT max(dispatch) FROM dispatch");
    if (pg_NumRows ($sth) > 0) {
      $dmin = date("Y") . sprintf ("%05d", <dispatchmin>);
      $row = pg_fetch_array ($sth, 0);
      $dispatch = $row[0] > $dmin?$row[0]:$dmin;
      $dispatch++;

      # fixme: Find out if 1st dispatch will be empty first...
      # Warning: If another user try to add dispatches, this will fail
      $sth = dbquery ($dbh, sprintf ("INSERT INTO dispatch (dispatch,customer,date) VALUES (%d,%d,now())",
	     $dispatch, $customer));
      $sth = dbquery ($dbh, sprintf ("INSERT INTO status (dispatch,status,staff,date) VALUES (%d,<st_order>,'web',now())",
	     $dispatch));

      if ($split == 1) {
	$sth = dbquery ($dbh, sprintf ("INSERT INTO dispatch (dispatch,customer,date) VALUES (%d,%d,now())",
	       $dispatch+1, $customer));
	$sth = dbquery ($dbh, sprintf ("INSERT INTO status (dispatch,status,staff,date) VALUES (%d,<st_order>,'web',now())",
	       $dispatch+1));
      }

      printf ($tbest, $ch, $dispatch);
      echo ($tind);

      # Status: customer verified || created; 1 or 2 dispatches reserved
      # WHERE spool > 0
      $sth = dbquery ($dbh, "SELECT article.name,article.article,offer.subname,offer.price,offer.articleid,spool.count_spare,"
			   ."count_sold "
			   ."FROM article,offer,spool WHERE article.article = offer.article AND offer.articleid = spool.articleid "
			   ."ORDER BY offer.articleid");

      $color = $cd;
      $color2 = $cd;
      $sum = 0.0;
      $table = "";
      for ($i=0; $i < pg_NumRows ($sth); $i++) {
	$row = pg_fetch_array ($sth, $i);

	if (${$row['articleid']} > 0) {
	  $sthi = dbquery ($dbh, sprintf ("UPDATE spool SET count_spare = %d, count_sold = %d WHERE articleid = '%s'",
					  $row['count_spare'] - ${$row['articleid']},
					  $row['count_sold'] + ${$row['articleid']},
					  $row['articleid']));

	  if ($split && (${$row['articleid']} > $row['count_spare'])) {

	    if ($row['count_spare'] > 0) {
	      $color = $color == $cd?$cn:$cd;
	      printf ($trow, $color, $row['count_spare'], $row['article'], $row['name'], $row['subname'], $row['price'],
		      $row['price'] * $row['count_spare']);

	      $sthi = dbquery ($dbh, sprintf ("INSERT INTO dispatchlist (dispatch,articleid,quantity,unitprice) "
					     ."VALUES (%d,'%s',%d,%5.2f)",
					     $dispatch,$row['articleid'],$row['count_spare'],$row['price']));
	      $sum += $row['price'] * $row['count_spare'];

	      ${$row['articleid']} -= $row['count_spare'];
	    }

	    $sthi = dbquery ($dbh, sprintf ("INSERT INTO dispatchlist (dispatch,articleid,quantity,unitprice) "
					   ."VALUES (%d,'%s',%d,%5.2f)",
					   $dispatch+1,$row['articleid'],${$row['articleid']},$row['price']));
            $sum2 += $row['price'] * ${$row['articleid']};
	    $color2 = $color2 == $cd?$cn:$cd;
	    $table .= sprintf ($trow, $color2, ${$row['articleid']}, $row['article'], $row['name'], $row['subname'], $row['price'],
			       $row['price'] * ${$row['articleid']});
	  } else {
	    $color = $color == $cd?$cn:$cd;
	    printf ($trow, $color, ${$row['articleid']}, $row['article'], $row['name'], $row['subname'], $row['price'],
		    $row['price'] * ${$row['articleid']});
	    $sthi = dbquery ($dbh, sprintf ("INSERT INTO dispatchlist (dispatch,articleid,quantity,unitprice) "
					   ."VALUES (%d,'%s',%d,%5.2f)",
					   $dispatch,$row['articleid'],${$row['articleid']},$row['price']));
            $sum += $row['price'] * ${$row['articleid']};
            ${$row['articleid']} = 0;
          }
	} /* ${$row['articleid']} > 0 */
      } /* for */
      $color = $color == $cd?$cn:$cd;
      printf ($tporto, $color, $porto, $porto);
      $sum2 += $porto;
      printf ($tsum, $ch, $sum);
    } else {
      echo ("<tr><td><font face=\"Helvetica,Arial\"><b>Interner Fehler.</b></font></td></tr>");
    }
    <btable_end>

    if ($split) {
      echo ("<p>");

      <btable_begin>

      printf ($tbest, $ch, $dispatch+1);
      echo ($tind);
      echo ($table);
      $color2 = $color2 == $cd?$cn:$cd;
      printf ($tporto, $color2, $porto, $porto);
      $sum2 += $porto;
      printf ($tsum, $ch, $sum2);

      <btable_end>
    }
  } else {
    echo ("<p><b>Bitte benutzen Sie den Back-Button ihres Browsers und korrigieren Sie Ihre Eingaben.</b>");
  }

?><p>

</page>
# Local variables:
# mode: indented-text
# mode: auto-fill
# mode-: iso-accents
# end:
