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

print header();
print start_html("Welcome");

my $dbh = DBI->connect( "dbi:mysql:products", "webserver", "", { RaiseError => 1, AutoCommit => 1 }) or &dienice("Can't connect to database: $DBI::errstr");

# declare some variables
my ($cookie_id, $username);

if (cookie('userID')) { # found a cookie!
   my $sth = $dbh->prepare("select * from user_cookies where cookie_id=?") or &dbdie;
   $sth->execute(cookie('userID')) or &dbdie;
   if (my $rec = $sth->fetchrow_hashref) {
      $cookie_id = cookie('userID');
      $username = $rec->{username};
   }
}
if ($cookie_id) {
   print h2("Welcome back, $username!");
} else {
   print h2("Welcome!");
   print qq(
<form action="cookieform.cgi" method="POST">
This appears to be your first visit. Please enter your name:
<input type="text" name="username">
<input type="submit" value="Enter">
</form>
<br>
);
}

print end_html;
$dbh->disconnect;

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

sub dbdie {
    my($package, $filename, $line) = caller;
    my($errmsg) = "Database error: $DBI::errstr<br>
                called from $package $filename line $line";
    &dienice($errmsg);
}