/* Author: Ram Samudrala (me@ram.org)
 * Version: O1.0
 * Detail: <http://www.ram.org/computing/sc/sc.html>
 * November 27, 1995.
 *
 * See the URL above for more information.
 */

#include "cgi_common.h"
#include "cgi_error_handlers.h"
#include "cgi_display.h"
#include "cgi_defines.h"
#include "sc_defines.h"
#include "search.h"
#include "items.h"
#include "display_item_list.h"

void display_search_results(item items[]);

/******************************************************************/

void search()
{
  entry entries[MAX_ENTRIES];
  item items[MAX_ITEMS];
  char filename[100], buf[200];

  display_content_type("Results of catalog search");
  check_content_type("POST");
  read_entries(entries);
  sprintf(filename, "%s.xxx.%d", TMP_FILENAME_STRING, (int) getpid());
  if (entries[0].val[0] != '\0')
    sprintf(buf, "%s '%s' %s> %s", SEARCH_COMMAND, entries[0].val, 
	    DEFAULT_ITEMS_FILE, filename);
  else
    sprintf(buf, "%s '%s' %s> %s", SEARCH_COMMAND, " ",
	    DEFAULT_ITEMS_FILE, filename);
  system(buf); 
  read_items(filename, items);
  remove(filename); 
  display_search_results(items);
  return;
}

/******************************************************************/

void display_search_results(item items[])
{  
  printf("<h1> Results of catalog search </h1>\n");  
  if (total_items(&items) == 0)
    {
      printf("<p align=center> Sorry, no items matched your query!  Try again. </p>\n");
      display_signature(SIGNATURE_FILE);
      return;
    }
  printf("<p> Here is a list of items that matched your query.\n");
  printf("For each item you're interested in ordering, please fill out the respective\n");
  printf("quantity field. Leave the quantity field blank if you don't wish to order an item.\n");
  printf("When you're done, click on the button below for the items to be added to your cart.</p>\n");
  printf("<hr>\n");
  printf("<form method=\"POST\" action=\"%s\">\n", FORM_COOKIE_PROCESSING_SCRIPT);  
  display_item_list(items);
  printf("<p> <input type=\"submit\" value=\"add to cart\"> </p>\n");
  printf("</form>\n");
  display_signature(SIGNATURE_FILE);
  return;
}

/******************************************************************/
