package Shopcart;
use strict;
use base qw(Exporter);
our @EXPORT = qw($dbh validate_cookie dienice dbdie sendmail display_shopcart);
our @EXPORT_OK = qw();

use DBI;
use CGI qw(:standard);

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

sub validate_cookie {
# Look for cookies. If they have a valid cookie, return it; if not,
# print an error message and abort.
    my $cookie_id = "";
    if (cookie('cart')) {
       $cookie_id = cookie('cart');
    } else {
       &dienice("You don't have a cart. (Perhaps your cart expired?)");
    }
    my $sth = $dbh->prepare("select * from cart_cookies where cookie_id=?") or &dbdie;
    $sth->execute(cookie('cart')) or &dbdie;
    unless ($sth->fetchrow_hashref) {
       &dienice("You don't have a cart. (Perhaps your cart expired?)");
    }
    return $cookie_id;
}

sub dienice {
    my($msg) = @_;
    print header;
    print start_html("Error");
    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);
}

sub sendmail {
    my($from, $to, $subject, $msg) = @_;
    $ENV{PATH} = "/usr/sbin";
    my $mailprog = "/usr/sbin/sendmail";
    open (MAIL, "|/usr/sbin/sendmail -t -oi") or 
        &dienice("Can't fork for sendmail: $!\n");
    print MAIL "To: $to\n";
    print MAIL "From: $from\n";
    print MAIL "Subject: $subject\n\n";
    print MAIL $msg;
    close(MAIL);
}

sub display_shopcart {
    my($cookie_id) = @_;
    my $sth = $dbh->prepare("select * from shopcart, items where shopcart.cookie=? and items.stocknum=shopcart.item_number") or &dbdie;
    $sth->execute($cookie_id) or &dbdie;
    my $subtotal = 0;
    print qq(
<center>
<h3>Your Shopping Cart</h3>
<form action="edcart.cgi" method="POST">
<table border=0 width=70%>
<tr>
    <th bgcolor="#cccccc">Item Number</th>
    <th bgcolor="#cccccc">Name</th>
    <th bgcolor="#cccccc">Price</th>
    <th bgcolor="#cccccc">Qty.</th>
</tr>
        );
    while (my $rec = $sth->fetchrow_hashref) {
       $subtotal = $subtotal + ($rec->{price} * $rec->{qty});
       print qq(
<tr>
    <td align="CENTER">$rec->{item_number}</td>
    <td align="CENTER">$rec->{name}</td>
    <td align="CENTER">\$$rec->{price}</td>
    <td align="CENTER"><input type="text" name="item_$rec->{item_number}" size=3 value="$rec->{qty}"></td>
</tr>
            );
    }
    $subtotal = sprintf("%4.2f", $subtotal);
    print qq(
<tr>
    <td></td>
    <td></td>
    <td><b>Subtotal:</b> \$$subtotal</td>
    <td></td>
</tr>
</table>
<input name="cartact" type="submit" value="Update Qty">
<input name="cartact" type="submit" value="Check Out">
</form>
</center>
        );
}

1;