#!/usr/bin/perl

# CollapsedSubs: Main_HTML_Doc  my_read_CGI_input  ConnectToDB  DisConnectFromDB  render_price_list_html  Read_Inventory_DB  urlencode
################################################################################
################################################################################
#####          This code tells the browser what MIME type the content is.  #####
#####          All content delivered by this script is HTML                #####
#####                                                                      #####
################################################################################
################################################################################
#use CGI::Carp qw(fatalsToBrowser);
#comment out the above line when you're done debugging this script
# start user configuration
################################################################################

    print "Content-type: text/html \n\n\r\n\r\n\r" unless ($content_type_printed);
    $content_type_printed++;

################################################################################
# the mysql database table name that this script will use for the products table.
$Feature_Name = "Cue Repair Price List";
$Feature_Link_Name = "price list";
$Inv_Table="services";
$Cart_Table = "repair_carts";
#$Sales_Order_Table = "service_orders";
#$Dealer_Table ="dealer_db";
$item_number_field = "Service_ID";
$item_name_field = "Service_Name";
$item_amount_field = "Reg_Price";
$item_sale_price_amount_field = "Sale_Price";
$item_active_field = "Active";
#$item_View_Permits_field ="View_Permits";
#$default_View_Permits ="%R%";
$item_category_field = "Category";
$cart_long_name ="Repair Ticket";
$cart_short_name ="Ticket";
$cart_url = "/cgi-bin/cue-shop.pl";

	# Enter the currency symbols PayPal uses to designate US dollars
	# or Euros or Pounds Sterlings. Enter a backslash before the $ symbol.
	# US: $
	# Euros:  �
	# Pounds Sterling: �
	# Canadian Dollar (C$)
	# Japanese Yen (�)
$m_symbol = "\$";
	# The currency of the payment is U.S.Dollars: USD
	# The currency of the payment is British Pounds Sterling: GBP
	# The currency of the payment is Euros: EUR
	# The currency of the payment is Canadian Dollar: CAD
	# The currency of the payment is Yen: JPY
$currency_code = "CAD";

################################################################################
################################################################################
# end user configuration ---> Begin Main Exec

$selfURL = $ENV{SCRIPT_NAME};
#$selfURL = "/cgi-bin/price-list.pl";

$|++;	#dont't buffer output

# find out the OS
if ($^O eq 'MSWin32' || $ENV{'OS'} eq 'Windows_NT') {
      # this one for windows
      $windows = 'Yes';
      $slash = '\\';
}
else
{
      $windows = 'No';
      $slash = '/';
}

#load required perl modules or libraries
#my $dbh;
my $db_params = "admin/params.pl";
my $db_common = "wsdbi_params.pm";
eval {
        #use strict;
        use DBI;
	 require $db_common;
        require $db_params;
        require 'cookie.pl';
};
#check for load errors
if ($@) {
        &my_load_error_doc($@);
        exit(0);
}

# connect to DB, read CGI data, verify Login,
SITe_ConnectToDB();
my_read_CGI_input();


##### define time variables
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$mon = $mon + 1;
$year = $year + 1900;
$accessTime = "$hour:$min:$sec";
$AN = int(rand(10000));


Main_HTML_Doc();

DisConnectFromDB();

#End of main perl code
################################################################################
####### this sub returns the script specific load error doc
################################################################################
sub Main_HTML_Doc(){

	#Determine Page Content
	$main_content = render_price_list_html() if ($data{cmd} eq "");  #Default Content
    $main_content = Read_Inventory_DB()  if ($data{cmd} eq "List");
    $main_content = Read_Inventory_DB()  if ($data{cmd} eq "ShowItem");

    print "Content-type: text/html \n\n\r\n\r\n\r" unless ($content_type_printed);
    $content_type_printed++;

	print qq~

	<html>
	<head>
	<title>$Feature_Name at $my_Business_name</title>
	<meta http-equiv="Content-Type" content="text/html;">
	<LINK rel="stylesheet" href="/ws_styles.css" type="text/css">
    <style type="text/css">
	    .cartTD  {
		        	font-size: 10px; font-family:verdana,helvetica,arial,sans-serif;
            	 }
	    .cartHDR {
        			font-size: 12px; font-weight:bold; font-family: verdana,helvetica,arial,sans-serif; background-color:#FFCC66
                 }
	</style>
	</HEAD>

	<body bgcolor="#ffffff" style='margin:0px; font-family:Ariel,Helvetica,sans-serif;'>

	    <TABLE align="center" width="600" border="0" cellpadding="2" class='Header'>
	        <TR>
	           <TD width="33%" valign="top" colspan=2>
                    <div style='font-size:18pt; font-family:Arial,Helvetica,sans-serif;'>$my_ws_logo_code  Bunjee Canada.com&#153;
                                <BR><FONT size='3' style='18pt;'><B>$Feature_Name</B></FONT>
			                     </div>
	           </TD>
            </TR>
            <TR>
	            <TD align='left' colspan=2>
	                $my_main_links
	            </TD>
	        </TR>
            <TR>
	           <TD align='center' colspan=2 style='font-size:18pt;' width="66%">
	                <BR><B>$Feature_Name</B><BR>
                    <DIV align="center" style="font-size: 8pt; font-family:Ariel,Helvetica,sans-serif;">(Currency: $currency_code)</DIV>
	           </TD>
	        </TR>

            <TR>
            	<TD colspan=2>
	                @error_messages
	                $main_content
                </TD>
            </TR>
            <TR>
            	<TD colspan=2>
                	<DIV align="center">
	                    <FONT face="Arial, Helvetica, sans-serif" size="1" style="font-size:8pt;">
	                            &copy; Copyright 2003 $my_Business_name&#153;
	                            All Rights Reserved. Trademarks and images not proprietary to
	                            $my_Business_name are used under license or with permission from their
	                            respective owners.<BR>Spark-IT Driven&#153
	                    </FONT>
	                </DIV>
                </TD>
            </TR>
        </TABLE>
	</body>
	</html>
	~;
}

sub my_read_CGI_input() {
        my($buffer) = undef;
        my($item);
        return(&SIT_read_CGI_input_multi_part()) if($ENV{'CONTENT_TYPE'} =~ /multi/i);

        if ($ENV{'REQUEST_METHOD'} =~ /POST/i) {
                read(STDIN,$buffer,$ENV{'CONTENT_LENGTH'});
        }
        else {
                $buffer=$ENV{'QUERY_STRING'};
        }
        $buffer = $ARGV[0]  if (not $buffer);

        my @pairs=split(/&/,$buffer);
        my $i = 0;
        foreach $item(@pairs) {
                my ($key,$content)=split (/=/,$item,2);    # Split into key and value.
                $content =~ tr/+/ /; # Convert plus's to spaces
                $content =~ s/%(..)/pack("c",hex($1))/ge;        # Convert %XX from hex numbers to alphanumeric
                # Convert %XX from hex numbers to alphanumeric when using hidden input tags
                $content =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
                $key =~ tr/+/ /; # Convert plus's to spaces
                $key =~ s/%(..)/pack("c",hex($1))/ge;        # Convert %XX from hex numbers to alphanumeric
                # Convert %XX from hex numbers to alphanumeric when using hidden input tags
                $key =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
                $key =~ s/ /_/g;

                # get rid of attempts to insert illegal characters
                $content =~ s/\\//g; # remove black slashes
                $content =~ s/\0//g; # remove nulls
                $content =~ s/[\\\&\;\`\'\"\|\*\~\^\[\]\{\}\$]//gs;
                # get rid of attempts to insert HTML tags
                $content =~ s/>/&gt;/gs;
                $content =~ s/</&lt;/gs;
                $content =~ s/\cM/\n/g;        #convert CR to LF
                $content =~ s/[\r\n]/ /g;
                $content =~ s/TRUNCATE/ /ig;
                $content = substr($content,0,4096);
                $content =~ s/^\s+|\s+$//gs;

                #make sure the email address is legal
                if(($content =~ m/\w\S+\@\w\S+\./) &&($key =~ /Email/i))
                {
                        my $mail_to = $content;
                        $mail_to =~ /([\w-.]+\@[\w-.]+)/;
                        $content = $1;
                }

                if (!defined($data{$key})) {
                        $data{$key}=$content;
                }
                else
                {
                    if($key !~ /username/ and   $key !~ /password/ and $key !~ /RecordID/)
                    {
                             $data{$key} .= ",$content" if($content ne "");
                    }
                }

                if ($data{$key} =~ /action/) {
                        $data{$key}=$content;
                }

                $CGI_input_names[$i]  = $key;
                $CGI_input_values[$i] = $content;

                $i++;
        }
        return 1;
}

sub ConnectToDB(){

    if (defined $sth){ $sth->finish();}
	$dbh = DBI -> connect("DBI:$dbdriver:$dbname:$dbserver", $dbuser, $dbpass);
	if(not $dbh){
		print "<p>Can't connect to  server.<p>Reason: $DBI::errstr";
		exit;
	}

}

sub DisConnectFromDB(){
	if (defined $sth){ $sth->finish();}
	if(defined $dbh){
		$dbh->disconnect or die "Can't disconnect from database. Reason: $DBI::errstr" and undef $dbh;
	}
}

sub render_price_list_html(){
	my $html = qq~
    <TABLE width="600">
    ~;


        my $dbquery = qq~SELECT DISTINCT Category FROM $Inv_Table WHERE $item_active_field LIKE 'TRUE'
        ORDER BY Category
        ~;
	    my $sth = $dbh -> prepare($dbquery) or print "Query syntax error. $dbquery. Reason: $DBI::errstr.";
	    if( not $sth -> execute())
	    {
	        print "<p>Can't execute query:<br> $dbquery.<p> Reason: $DBI::errstr.";
	        $sth -> finish;
	        DisConnectFromDB();
	        exit;
	    }
        @my_unique_categories = ();
	    while(my $sku_ref=$sth->fetchrow_hashref())
	    {
	    	push(@my_unique_categories,$sku_ref->{Category});
	    }
	    $sth->finish();

        my $col = 1;
        foreach $category (@my_unique_categories)
        {
            $html .= qq~
            	<TD valign="top" width="20%" style="font-size:12pt; color:#000000; background-color:#FFFFFF">
                	<DIV align="center" valign="top"  style="background-color:Gold">
                    	<B><A href="$selfURL?cmd=List&Category=$category" title="">$category</A></B></DIV>
                    <DIV style="font-size:10pt;">
            ~;

            my $dbquery = qq~SELECT * FROM $Inv_Table WHERE $item_active_field LIKE 'TRUE'
            AND Category LIKE '$category' ORDER BY $item_name_field
            ~;
	        my $sth = $dbh -> prepare($dbquery) or print "Query syntax error. $dbquery. Reason: $DBI::errstr.";
	        if( not $sth -> execute())
	        {
	            print "<p>Can't execute query:<br> $dbquery.<p> Reason: $DBI::errstr.";
	            $sth -> finish;
	            DisConnectFromDB();
	            exit;
	        }
            $i=1;
	        while(my $sku_ref=$sth->fetchrow_hashref())
	        {
            	if ($sku_ref->{$item_sale_price_amount_field} < $sku_ref->{$item_amount_field})
                {
                    $temp_price = "$sku_ref->{$item_sale_price_amount_field}";
                }
                else
                {
                	$temp_price = "$sku_ref->{$item_amount_field}";
                }
                my $temp_Item = $sku_ref->{$item_number_field};
	        	$html .= qq~<B>$i) <A href="$selfURL?cmd=ShowItem&Item=$sku_ref->{$item_number_field}" title="$sku_ref->{$item_name_field}">$sku_ref->{$item_name_field}</A></B>
                <BR>$m_symbol$temp_price<HR>
                ~;
                $i++;
	        }
            $html .=qq~</DIV></TD>~;
        	if ($col == 3)
            {
            	$col = 0;
                $html .=qq~</TR><TR>~;
            }
            $col++;
	        $sth->finish();
        }
        #$html .=qq~</TR>~;

    $html .=qq~</TABLE>~;
    return $html;
}

sub Read_Inventory_DB(){

    my $dbquery;
    if ($data{cmd} eq "ShowItem")
    {
        $dbquery = "SELECT * FROM $Inv_Table WHERE $item_number_field LIKE '$data{Item}' LIMIT 1";
        $third_column_header_HTML = qq~~;
        #$content_name = lc($item_number);
        $content_name = uc($item_number);
    }
    elsif ($data{Category} ne "")
    {
        $dbquery = "SELECT * FROM $Inv_Table WHERE  $item_category_field LIKE '$data{Category}' ORDER BY $item_name_field ";
        $third_column_header_HTML = qq~<td class="cartHDR" valign='top'><IMG src="$my_Images_folder/spacer.gif" width="175" height="1" ><BR>Features</td>~;
        #$content_name = lc($data{Category});
        $content_name = $data{Category};
    }
    else
    {
        $html = render_price_list_html();
        return $html;
    }

	my $sth = $dbh -> prepare($dbquery) or print "Query syntax error. $dbquery. Reason: $DBI::errstr.";
	if( not $sth -> execute())
	{
	    print "<p>Can't execute query:<br> $dbquery.<p> Reason: $DBI::errstr.";
	    $sth -> finish;
	    DisConnectFromDB();
	    exit;
	}

    my $html = qq~
        <TABLE align='left' cellpadding='4' cellspacing='0' width="100%">
        	<TR bgcolor='#FEF3DE'>

	            <TD align='center' colspan=3 valign='top' width='100%'>
	                <DIV style='font-size:16pt;'>
	                    <B>$data{Brand} $content_name</B>
	                </DIV>
	            </TD>

	        </TR>
        ~;

	# loop through the array of products and display the HTML add to cart buttons */
	    while($sku_ref=$sth->fetchrow_hashref())
	    {
            if (uc($sku_ref->{$item_active_field}) eq "TRUE")
            {
            	my $item_number =   $sku_ref->{$item_number_field};
	            my $item_name =   $sku_ref->{$item_name_field};
	            my $item_amount =   $sku_ref->{$item_amount_field};
                my $item_sale_price = "<FONT color='#990000' size=3><B>SALE! </B>$m_symbol$sku_ref->{$item_sale_price_amount_field}</FONT>" if ($sku_ref->{$item_sale_price_amount_field} < $item_amount);

	            if ($item_amount > 0)
                {
                	my $number = urlencode($item_number);
	                $item_name =~ s/\"/ /g;
	                my $name_value = $item_name;
	                #remove characters that migh cause problems with the javascript functions
	                $name_value =~ s/[\,\;\`\'\|\*\~\^\[\]\{\}\$\"]/ /g;
	                $name_value =~ s/^\s+|\s+$/ /;
	                my $name = urlencode($name_value);
	                my $amount = urlencode($item_amount);

                	my $add_form_HTML = qq~
	                     <FORM name="addItem$i" method="POST" action="$cart_url" target="_self" onSubmit="this.AN.value = Math.round(Math.random()*10000)+1000; if(this.quantity.value == ''){this.quantity.value=1;};">
	                         <INPUT    type="hidden"    name="login"     value="$LOGIN">
	                         <INPUT    type="hidden"    name="cmd"       value="">
                             <INPUT    type="hidden"    name="cmd2"      value="Start">
                             <INPUT    type="hidden"    name="Brand"     value="$sku_ref->{Brand}">
	                         <INPUT    type="hidden"    name="Item"      value="$sku_ref->{$item_number_field}">
                             <INPUT    type="hidden"    name="Model_Disc"      value="$sku_ref->{Model_Disc}">
                             <INPUT    type="hidden"    name="Description"   value="$sku_ref->{Description}">
	                         <INPUT    type="hidden"    name="AN"        value="$AN">
	                         <BR><B>Need this repair?</B><BR>
	                         <INPUT    type="hidden"      name="quantity"  value="1" size="3"  style="width:30; height:20; font-size:8pt; color:#000000;" maxlength='4'>
	                         <INPUT    type="submit"    name="submit"    value="Start a $cart_long_name" style="width:95; height:20; font-size:7pt; font-family:Arial,Helvetica,sans-serif; color:#000000; background-color:#CCFFCC;">
	                     </FORM>
	            	~;

                    $detail_link = qq~<a href="$my_WS_HTTP_URL$selfURL?login=$LOGIN&cmd=ShowItem&Item=$sku_ref->{$item_number_field}&Brand=$data{Brand}">Bigger Picture...</A><BR><BR>~;
                    $detail_link2 = qq~
	                <DIV style='height:24px; overflow:hidden;'>
                    	<FORM  name="List"   method="POST" action="$selfURL">
	                     <INPUT type="hidden" name="login"    value="$LOGIN">
	                     <INPUT type="hidden" name="AN"       value="$AN">
	                     <INPUT type="hidden" name="cmd"      value="ShowItem">
                         <INPUT type="hidden" name="Brand"    value="$data{Brand}">
                         <INPUT type="hidden" name="Item"      value="$sku_ref->{$item_number_field}">
	                     <INPUT type="submit" name="Submit"   Value='Show me more...' style='font-size:8pt; width:85px; height:18px; background-color:#eeeeee; text-align:left;'>
	                 	</FORM>
                    </DIV>
	             	~;
                    $this_row_bg_color = '#FFF7F0';
                	if ($listIndex % 2) {$this_row_bg_color = '#ffffff'; }

	                # create the code for the add to cart buttons for each product
                    if ($data{cmd} eq "ShowItem")
                    {
                        if (-e "../httpdocs/$Inv_Table/med/$item_number.jpg")
	                    {
	                        $product_img_URL = qq~<img src="$my_WS_HTTP_URL/$Inv_Table/med/$item_number.jpg" border="0">~;
	                    }
	                    else
	                    {
	                        $product_img_URL = "<FONT color='#990000'><B>No Photo</B></FONT>";
	                    }
                        $html_row = qq~
                        <tr bgcolor='$this_row_bg_color'>
                            <td class="cartTD" valign='top'>
                                <FONT style='font-size:10pt; font-weight:bold;'>$item_number</FONT><BR>
                                MSRP: $m_symbol$sku_ref->{MSRP}<BR>
                                $item_sale_price<BR>
                                $add_form_HTML<BR>
                            </td>
                            <td colspan='2' class="cartTD" valign='top'>
                                <FONT style='font-size:10pt; font-weight:bold;'>$item_name</FONT><BR>
                                $product_img_URL<BR>
                                $sku_ref->{Caption}<BR>
                                $sku_ref->{Details}
                            </td>
                        </tr>
                        <TR>
                            <TD colspan='3' class="cartTD" valign='top'>
                                $sku_ref->{Expanded_Details}
                            </TD>
                        </TR>
                        ~;
                    }
                    else
                    {
                        if (-e "../httpdocs/$Inv_Table/small/$item_number.jpg")
	                    {
	                        $product_img_URL = qq~<img src="$my_WS_HTTP_URL/$Inv_Table/small/$item_number.jpg" border="0">~;
	                    }
	                    else
	                    {
	                        $product_img_URL = "<FONT color='#990000'><B>Photo Pending</B></FONT>";
	                    }
                        $html_row = qq~
                        <tr>
                            <td class="cartHDR" valign='top'>
                            	<IMG src="$my_Images_folder/spacer.gif" width="100" height="1" ><BR>
                                Repair Item
                            </td>
                            <td class="cartHDR" colspan='2' valign='top'>
                            	<IMG src="$my_Images_folder/spacer.gif" width="225" height="1" ><BR>
                                Repair Description
                            </td>
                        </tr>
                        <tr bgcolor='$this_row_bg_color'>
                            <td class="cartTD" valign='top'>
                                <FONT style='font-size:10pt; font-weight:bold;'>$item_number</FONT><BR>
                                MSRP: $m_symbol$sku_ref->{MSRP}<BR>
                                $item_sale_price<BR>
                                $detail_link<BR>
                                $add_form_HTML
                            </td>
                            <td class="cartTD" colspan='2' valign='top'>
                                <FONT style='font-size:10pt; font-weight:bold;'>$item_name</FONT><BR>
                                $product_img_URL<BR>
                                <h5>$sku_ref->{Caption}</h5>
                                $sku_ref->{Details}
                            </td>
                        </tr>
	                	~;
                    }
                    # display the code for the add to cart buttons for each product
	                $html .= $html_row;
                    $listIndex++;
             	}
	    	}
		}
	$html .= qq~  </TABLE>~;
	$sth -> finish;
	DisConnectFromDB();
    return $html;
}


sub urlencode(){
    my($esc) = @_;
    $esc =~ s/^\s+|\s+$//gs;
    $esc =~ s/([^a-zA-Z0-9_\-.])/uc sprintf("%%%02x",ord($1))/eg;
    $esc =~ s/ /\+/g;
    $esc =~ s/%20/\+/g;
    return $esc;
}
