#!/usr/bin/perl -wT
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use Fcntl qw(:flock :seek);
use strict;

print header;
print start_html("Kite Catalog - Search Results");
print qq(<h2>Search Results</h2>\n);
print qq(<form action="order.cgi" method="POST">\n);

my @keywords = split(/ /,param('keyword'));
my $search_phrase = param('keyword');
print qq(<p>Results for search of `$search_phrase':</p>\n);

open(INF,"data.db") or &dienice("Can't open data.db: $! \n");
flock(INF, LOCK_SH);    # shared lock
seek(INF, 0, SEEK_SET); # rewind to beginning

my $found = 0;
while (my $i = <INF>) { # read each line one at a time
   chomp($i);
   my ($stocknum,$name,$instock,$price,$category) = split(/\|/,$i);
   # pass the @keywords array as a reference:
   if (&keyword_search($name, \@keywords)) {
      $found++;         # increment the results counter
      print qq(<input type="text" name="$stocknum" size=5> $name - \$$price<p>\n);
   }
}
close(INF);

if ($found) {
    print qq(<input type="submit" value="Order!">\n);
    print qq(<p>$found kites found.</p>\n);
} else {
   print qq(<p>No kites found.</p>\n);
}

print end_html;

sub dienice {
    my($msg) = @_;
    print "<h2>Error</h2>\n";
    print $msg;
    exit;
}

sub keyword_search {
    my($name, $keyref) = @_;    # args=kite name and keywords reference
    my @keywords = @{$keyref};  # here we dereference the keywords array
    my $count = 0;
    foreach my $word (@keywords) {
    # case-insensitive match
       if ($name =~ /$word/i) {
          $count++;
       }
    }
    # if it matched every keyword, return true.
    if ($count == scalar(@keywords)) {
       return 1;
    } else {
       return 0;
    }
}