;;; basket.mhtml: -*- Meta-HTML -*-  Shopping Basket Example.
;;;
;;;  Copyright (c) 1996 Universal Access Inc.
;;;  Author: Art Medlar, Henry Minsky Fri Jul 26 18:19:12 PDT 1996

;;; Define a shopping basket entry form, and a data format for 
;;; product entries.

;;; Load the basket package from the current session
<session-import basket basket>

;;; Creates a local package to use as a data structure
;;; and returns it as an alist.
<define-function make-basket-entry>
  <package-delete temp>
  <set-var temp::quantity=<or <get-var posted::cake-quantity> 1>
           temp::price=<get-var posted::cake-price>
	   temp::title=<get-var posted::cake-title>
	   temp::product-id=<get-var posted::cake-id>
	   temp::url=<get-var posted::url>>
  <package-to-alist temp>
</define-function>

;;; This is a convenience macro for inserting variables
;;; and their values into hidden fields into a form.
<define-tag hide thing>
  <input type=hidden name="<get-var thing>" value="<get-var <get-var thing>>">
</define-tag>

<define-tag purchase-order>
  <when <package-vars posted>>
    <set-var basket::items[basket::current-item]=<make-basket-entry>>
    <increment basket::current-item>
    <session-export basket basket>
    <redirect show-basket.mhtml>
  </when>
  <form method="POST" action="<get-var mhtml::location>">
    <set-var url=<get-var mhtml::full-url>>
    <hide cake-id>
    <hide cake-title>
    <hide cake-price>
    <hide url>
    How Many:<input type=text value="" name="cake-quantity" size=4>
    <input type=submit value="Add to Basket">
  </form>
</define-tag>

;;; Get item number n from the basket, and put
;;; it in a package called BASKET-ITEM.
<define-function get-basket-entry n>
  <set-var item-alist=<get-var basket::items[n]>>
  <alist-to-package <get-var item-alist> basket-item>
</define-function>

;;; Prints an HTML table of the shopping basket contents
<define-function display-shopping-basket>
  <set-var i=0 total=0>
  ;;; Loop over the items in the basket
  <table border=1>
    <tr>
      <th>Item</th>
      <th>Description</th>
      <th>Qty</th>
      <th>Price</th>
      <th>Total</th>
    </tr>

    <while <lt i basket::current-item>>
      <get-basket-entry <get-var i>>
      <set-var cost=<mul basket-item::price basket-item::quantity>
	total=<add total cost>>
      <tr>
	<td><get-var basket-item::product-id></td>
	<td><a href="<get-var basket-item::url>">
             <get-var basket-item::title>
            </a>
        </td>
	<td><get-var basket-item::quantity></td>
	<td><get-var basket-item::price></td>
	<td><get-var cost></td>
      </tr>
      <increment i>
    </while>
    <tr><td colspan=5 align=right>Total Price: $<get-var total></td></tr>
  </table>
</define-function>
