#!/usr/bin/perl -w

# show-postcard.pl

use strict;
use diagnostics;
use CGI;  # available from http://www.perl.com/CPAN/
use Mysql;

# ------------------------------------------------------------
# Name some global variables
my $sender_name = "";
my $sender_email = "";
my $recipient_name = "";
my $graphic_name = "";
my $postcard_text = "";

# Create an instance of CGI
my $query = new CGI;

# Send an appropriate MIME header
print $query->header("text/html");

# Get the name to match from the query string
my $id = $query->param("keywords");

# Check that the user entered a postcard ID
if ($id == 0)
{
    print $query->start_html(-title => "No ID given!");
    print "<P>Sorry, but I can only retrieve postcards when an ";
    print "ID number is provided.  Please enter one, and I will try ";
    print "to find a postcard matching that ID number.</P>\n";
    print "<isindex>\n";
    print $query->end_html;
    exit;
}

# Connect via Unix sockets to the database on this server
my $dbh = Mysql->connect("localhost", "test");

# Build up our SQL command
my $command = "";
$command = "select postcards.sender_name,postcards.sender_email,";
$command .= "postcards.recipient_name,graphics.graphic_file,";
$command .= "postcards.postcard_text from postcards,graphics ";
$command .= "where id_number = $id";
$command .= "and postcards.graphic_id = graphics.graphic_id";

# Uncomment for debugging
# print "<P>SQL command: <"$command\"</P>\n";

# Send the query
my $sth = $dbh->query($command);

# Make sure that $sth returned reasonably
die "Error with command \"$command\"" unless (defined $sth);

# Report an error if no rows are returned
if ($sth->numrows == 0)
{
    print $query->start_html(-title => "Invalid ID!");
    print "<P>Sorry, but the ID number you provided does not match ";
    print "any postcard in my database.  Please try again, and I will try ";
    print "to find a postcard matching that ID number.</P>\n";
    print "<isindex>\n";
    print $query->end_html;
    exit;
}

# ------------------------------------------------------------
# Iterate through the returned rows
my @arr = ();

while (@arr = $sth->fetchrow)
{
    # Assign our variables to the returned row
    ($sender_name, $sender_email, $recipient_name, 
     $graphic_name,  $postcard_text) = @arr;
}

# ------------------------------------------------------------
# Begin the HTML output
print $query->start_html(-title => "Postcard for $recipient_name");

print "<img src=\"/tmp/$graphic_name\"</P>\n";
print "<P><pre>$postcard_text</pre></P>\n";
print "<P>From $sender_name ($sender_email)</P>\n";

# End the HTML
print $query->end_html;

exit;

