#!/usr/bin/perl

# import modules
use dTemplate;
use CGI;
use DBI;

# initialize CGI object
$cgi = new CGI();

# set base dir for templates
$templateDir = "../htdocs/templates";

# set up a list of templates to be used
%templates = ("index" => "index.tmpl", "item" => "li.tmpl", "detail" => "detail.tmpl");

# create a dTemplate object for each template $templates={}; foreach $name (keys(%templates)) {
	$templateName = $templateDir . "/" . $templates{$name};
	$templates->{$name} = dTemplate->new(file => $templateName); }

# connect to database
$dbh = DBI->connect("DBI:mysql:database=db;host=localhost", "user", "pass", {'RaiseError' => 1});

if ($cgi->param('username'))
{
	# if username is present in the URL
	# query for the user details
	# prepare and execute query
	$sth = $dbh->prepare("SELECT lname, fname, dob, nat, YEAR(NOW())-YEAR(dob) as age FROM users WHERE username = '" . $cgi->param('username') . "'");
	$sth->execute();
	
	# get record set
	# replace template variables with field values
	$ref = $sth->fetchrow_hashref();
	$output = $templates->{detail}->parse(
		USER => $cgi->param('username'), 
		LNAME => $ref->{'lname'},
		FNAME => $ref->{'fname'},
		DOB => $ref->{'dob'},
		NAT => $ref->{'nat'},
		AGE => $ref->{'age'});
	$sth->finish();
}
else
{
	# no username
	# get user list
	$sth = $dbh->prepare("SELECT username FROM users");
	$sth->execute();
	
	# iterate over user list
	# generate an HTML list by parse()-ing and appending
	while($ref = $sth->fetchrow_hashref())
	{
		$items .= $templates->{item}->parse(NAME => $ref->{'username'});M
	}
	$sth->finish();

	# interpolate the final list in the main template
	$output = $templates->{index}->parse(LIST => $items); }

# disconnect from database
$dbh->disconnect();

# print HTTP headers
print $cgi->header();

# print rendered version
print $output;