#!/usr/local/bin/perl

use DBI;
use udbi;
use in;
use u;
use vars qw{$db $shell $mergefile $in $user $s};
use strict;
$s = &in::settings;
$in = &in::ReadParse;
$db = &udbi::dbconnect($s);

$user = {};

my ($qr,$account);

# EXECUTE COMMAND IF IT IS THERE
if($$in{cmd} ne ""){ eval("&$$in{cmd}"); exit; }

if ($$in{catid} eq "")
{
#  &in::ct;
# print "list all categories";
  &toplevel;
  #&showprods(1);
	
#  $shell=&u::createshell($db,$user,'store.tpl');
#  &in::ct;
#  print $$shell;
}
else
{
  &showcat($$in{catid});
#  &showprods($$in{catid});
}


############################################################
# showcat
############################################################
sub showcat
{
  my($cat) = @_;
  my $rows = ""; 
	my ($info,$newrow);

  my $query=<<QUERY;
select c.*  
from category c,prod_cat pc,product p
where c.catid=pc.catid and pc.pid=p.pid and c.catid like "$cat:%" and c.catid not like "$cat:%:%"
group by pc.catid
QUERY

#&in::ct;
#print $query;
#exit;

# select *
# from category c,cs_prod_cat pc,product p
# where c.catid=pc.catid and pc.sku=p.sku and p.status='1' and c.catid like "$cat:%" and c.catid not like "$cat:%:%"
# group by pc.catid

  my $qr = $db->prepare($query);
  
  #warn($query);

  $qr->execute;

#&in::ct;
  ######## if no sub-cats, then show products ########
  if ($qr->rows == 0)
  {
    #&in::ct;
    #print "Prods";
    #exit;
    &showprods($cat);
		exit;
  }
  else
  {
    my $row = &in::cat('tpls/categoryrow.tpl');
    my $pos=1;

    while($info = $qr->fetchrow_hashref)
    {
    	$newrow = $row;
      #$$info{catgraphic} = $$info{catid};
      $$info{catgraphic} =~ s/\:/-/g;
      $$info{catgraphic} .= '.jpg';
      if (! -e "/images/products/$$info{catgraphic}")
			{
				#warn("select graphic from product p, category c, prod_cat pc where p.pid=pc.pid and pc.catid=c.catid and c.catid='$$info{catid}' order by prodname limit 1");
				($$info{catgraphic}) = $db->selectrow_array("select graphic from product p, category c, prod_cat pc where p.pid=pc.pid and pc.catid=c.catid and c.catid='$$info{catid}' order by prodname limit 1");
			}
      #$$info{catgraphic} = 'blank.gif' if (! -e "/images/products/$$info{catgraphic}.jpg");
      #$$info{catgraphic} = 'blank.gif' if (! -e "/images/products/$$info{catgraphic}");
  		&udbi::databasemerge(\$newrow,$info);
     	$rows .= $newrow;
		}

		if (0)
		{
    	foreach (keys %$info)
      {
        $newrow =~ s/<<$_$pos>>/$$info{$_}/g;
      }
	
	    if ($pos % 3 == 0)
	    {
	      $rows .= $newrow;
	      $newrow = $row;
	      $pos=1;
	    }
	    else
	    {
	      $pos++;
	    }
    }
    if ($pos != 1)
    {
      while ($pos<=3)
      {
        #$newrow =~ s|<td>.*?<<.*?$pos>>.*?</td>|<td>\&nbsp\;</td>|sg;
        $newrow =~ s/<<.*?$pos>>//g;
        $pos++;
      }
      $newrow =~ s|<img src="/images/category/".*?>||g;
     $rows .= $newrow;
    }
}

  $shell=&u::createshell($db,$user,'category.tpl','ecommerce');

    $$shell =~ s/<<rows>>/$rows/g;
		if (0)
		{
    my $str = &catheader($cat);
  	$$shell =~ s/<<catheader>>/$str/g;
		}

if($cat =~ m/%:%/){ 
	&in::ct;
	print "here";
	exit;
}

my $catid=$cat;
    my $cqr = $db->prepare("select * from category where catid = '$cat'");
    $cqr->execute;
  	my $cat = $cqr->fetchrow_hashref;

if($catid =~ m/.*?:.*?/){
  my $maincatid = $catid;
  $maincatid =~ m/(.*?):.*?/;
  $maincatid = $1;
  ($$cat{maincatname},$$cat{maincatid}) = $db->selectrow_array("select catname,catid from category where catid='$maincatid'");
  $$cat{breadcrumb} = qq|<a href="/ecommerce">All Products</a>/<a href="/shop/c/$$cat{maincatid}/$$cat{maincatname}">$$cat{maincatname}</a>/<a href="/shop/c/$$cat{catid}/$$cat{catname}">$$cat{catname}</a>|;
}
else{
  $$cat{breadcrumb} = qq|<a href="/ecommerce">All Products</a>/<a href="/shop/c/$$cat{catid}/$$cat{catname}">$$cat{catname}</a>|;
}

  	&udbi::databasemerge($shell,$cat);
		

    &in::ct;
    print $$shell;
  #}
}


############################################################
# showprods
############################################################
sub showprods
{

  my($cat) = @_;

  my $qr;

  if(!$$in{i}){ $$in{i} = $$s{products_per_page}; }
  if(!$$in{p}){ $$in{p} = "1"; }
  if(!$$in{l}){ $$in{l} = "0,$$in{i}"; }

  my $prodrow = &in::cat("tpls/productrow.tpl");
  my ($info,$newrow,$rows);

	my $ctqry = "select count(*) as numres from product p,prod_cat pc where p.pid=pc.pid and catid='$cat' and status=1";
	my $mainqry = "select * from product p,prod_cat pc where p.pid=pc.pid and catid='$cat' and status=1 group by p.pid order by pc.ordering,prodname limit $$in{l}";	
	my $vars = "catid=$cat";

	$$in{searchvar} = $$in{search} if ($$in{searchvar} eq '');
	if( $$in{searchvar} ){
		
		$ctqry = "select count(*) as numres from product where status=1 and (prodname like '%$$in{searchvar}' or prodlongdesc like '%$$in{searchvar}%' or prodkeywords like '%$$in{searchvar}%')";
		$mainqry = "select * from product where status=1 and (prodname like '%$$in{searchvar}%' or prodlongdesc like '%$$in{searchvar}%' or prodkeywords like '%$$in{searchvar}%') order by prodname limit $$in{l}";
		$vars = "cmd=showprods&searchvar=$$in{searchvar}";
	}

	
  # count rows
  $qr = $db->prepare($ctqry);
  $qr->execute;
  $info = $qr->fetchrow_hashref;
  my $nl = &in::nextstuff($$in{i},$$in{p},$$info{numres},"/ecommerce/category.i?$vars");
	my $totalnum = $$info{numres};

  my $aqr = $db->prepare("select aname,price from prod_attrib where pid=? order by price limit 4");
	my $ainfo;

  # get needed rows
  $qr = $db->prepare($mainqry);
  $qr->execute;


  my $intranet = 0;
	my $num=1;
  while($info = $qr->fetchrow_hashref)
  {
		$newrow = $prodrow;
    #$newrow =~ s|products/<<sku>>_sm.jpg|blank.gif|g if (! -e "images/products/$$info{graphic}_sm.jpg");
		$newrow =~ s|products/<<graphic>>_sm.jpg|blank.gif|g if (! -e "$ENV{DOCUMENT_ROOT}/images/products/$$info{graphic}_sm.jpg");
		$$info{price} = ($intranet) ? $$info{employee_price} : $$info{customer_price};
#    $$info{inventorystatus} = ($$info{tqty}>0) ? "In Stock ($$info{qty})" : 'Out of Stock';
#    &udbi::databasemerge(\$newrow,$account,'x');

if (0)
{
  	$aqr->execute($$info{pid});
  	while($ainfo = $aqr->fetchrow_hashref)
  	{
			$$ainfo{price} = &in::addcommas($$ainfo{price});
			$$info{att} .= "$$ainfo{aname} \$$$ainfo{price}<br>";
		}
		if ($$info{att} eq '')
		{
			$$info{customer_price} = &in::addcommas($$info{customer_price});
			$$info{att} = "\$" . $$info{customer_price};
			#$$info{att} = "\$" . int($$info{customer_price});
		}
}
		
		#$$info{prodlongdesc} =~ s/<.*?>//g;
    #$$info{prodlongdesc} = substr($$info{prodlongdesc},0,65) . "...";
		$$info{fprodname} = $$info{prodname};
		$$info{fprodname} =~ s|[ /\.]|-|g;
		$$info{fprodname} =~ s|['#%]||g;#'
		$$info{num} = $num;
		$newrow =~ s/<!-- add to cart -->(.*?)<!-- add to cart -->/<font color=\"red\"><b>OUT OF STOCK<\/b><\/font>/gsi if $$info{checkstock} == 1 && $$info{instock} == 0;
    &udbi::databasemerge(\$newrow,$info);

    $rows .= $newrow;
		$num++;
  }
	if ($qr->rows==0)
	{
		$rows = <<ROW;
<tr>
	<td width="10">&nbsp;</td>
	<td colspan="4" class="h2"><br>Currently there are no products in this category.</td>
</tr>
ROW
	}

  $shell=&u::createshell($db,$user,'productlist.tpl','ecommerce');
# DO THIS FIRST
	if( $$in{searchvar} ){
		$$shell =~ s/<<catname>>/Search Results/g;
		$$shell =~ s/<<catdesc>>/Your search returned the following results:/g;
	}


	$$shell =~ s/<<rows>>/$rows/g;
# my $str = &catheader($cat);
# $$shell =~ s/<<catheader>>/$str/g;
  $$shell =~ s/<<catheader>>//g;

my $catid=$cat;
  my $cqr = $db->prepare("select * from category where catid = '$cat'");
  $cqr->execute;
  my $cat = $cqr->fetchrow_hashref;

if($catid =~ m/.*?:.*?/){
	my $maincatid = $catid;
	$maincatid =~ m/(.*?):.*?/;
	$maincatid = $1;
	($$cat{maincatname},$$cat{maincatid}) = $db->selectrow_array("select catname,catid from category where catid='$maincatid'");
	$$cat{breadcrumb} = qq|<a href="/ecommerce">All Products</a>/<a href="/shop/c/$$cat{maincatid}/$$cat{maincatname}">$$cat{maincatname}</a>/<a href="/shop/c/$$cat{catid}/$$cat{catname}">$$cat{catname}</a>|;
}
else{
	$$cat{breadcrumb} = qq|<a href="/ecommerce">All Products</a>/<a href="/shop/c/$$cat{catid}/$$cat{catname}">$$cat{catname}</a>|;
}

  my @c = split(/\:/,$$cat{catid});
  $$shell =~ s|<!-- Cat -->(.*?)<!-- End Cat -->|<a  class="bodytextboldlink" href="category.i?catid=$c[0]">$1</a>|gsi;
  $$shell =~ s|<<subcat>>| \&gt\; $$cat{catname}|g;
  $$shell =~ s|<<nextlist>>|$nl|g;
	$$shell =~ s/<<totalnum>>/${totalnum}/g;
  &udbi::databasemerge($shell,$account,'x');
  &udbi::databasemerge($shell,$cat);

  &in::ct;
  print $$shell;
}


#### Category header
sub catheader {

  my ($cat) = @_;
  my @cat = split(/\:/,$cat);
  my $str = &in::cat("tpls/category$cat[0].tpl");
  return "$str";
}


########################################################
# list
# purpose: lists items
########################################################
sub list
{
	my ($qr,$info,$aqr,$ainfo);
	$qr = $db->prepare("select * from product where status=1");
	$qr->execute;
#	my $product = $qr->fetchrow_hashref;
	
	$aqr = $db->prepare("select * from prod_attrib where pid=? order by atype");
	
  my $row = &in::cat("tpls/product_listrow.tpl");
	my $rows;
  my $newrow;
	my $atype;

	while ($info = $qr->fetchrow_hashref)
	{
		$newrow = $row;
		$atype = '';
		$aqr->execute($$info{pid});
		while ($ainfo = $aqr->fetchrow_hashref)
		{
			if ($atype ne $$ainfo{atype})
			{
				$atype = $$ainfo{atype};
				$$info{attributes} .= qq'</select>\n';
				$$info{attributes} .= qq'<select name="att_${atype}_$$info{pid}">\n';
			}
			$$info{attributes} .= qq'<option value="$$ainfo{aname}">$$ainfo{aname}</option>\n';
		}
		$$info{attributes} .= qq'</select>\n';
		$$info{attributes} =~ s|^</select>\n||;
		
		&udbi::databasemerge(\$newrow,$info);
		$rows .= $newrow;
	}
	
	$shell=&udbi::createshell($db,'product_list.tpl','ecommerce');
	$$shell =~ s/<<rows>>/$rows/;
	
  &udbi::databasemerge($shell);
  &in::ct;
  print $$shell;
}

########################################################
# flavorlist
# purpose: lists items
########################################################
sub flavorlist
{
	my ($qr,$info,$aqr,$ainfo);
	$qr = $db->prepare("select * from product p,prod_cat pc where p.pid=pc.pid and catid='$$in{catid}' and status=1 group by p.pid order by p.pid");	
	$qr->execute;
#	my $product = $qr->fetchrow_hashref;
	
	$aqr = $db->prepare("select * from prod_attrib where pid=?");
	
  my $row = &in::cat("tpls/productrow_flavors.tpl");
  my $rows;
  my $newrow;
	my $atype;

	while ($info = $qr->fetchrow_hashref)
	{
		$newrow = $row;
		$atype = '';
		$aqr->execute($$info{pid});
		#$$info{attributes} .= qq'<select name="$$info{pid}_atidlist"><option value="">Concentrate</option>\n';
		$$info{attributes} .= qq'<select name="atidlist_$$info{pid}">\n';
		while ($ainfo = $aqr->fetchrow_hashref)
		{
			#$$info{attributes} .= qq'<option value="$$ainfo{aname}">$$ainfo{aname}</option>\n';
			$$info{attributes} .= qq'<option value="$$ainfo{atid}">$$ainfo{aname} - \$$$ainfo{price}</option>\n';
		}
		$$info{attributes} .= qq'</select>\n';
		
		&udbi::databasemerge(\$newrow,$info);
		$rows .= $newrow;
	}
	
	$shell=&u::createshell($db,$user,'productlist_flavors.tpl','ecommerce');
  $$shell =~ s/<<rows>>/$rows/;
	
  &udbi::databasemerge($shell);
  &in::ct;
  print $$shell;
}

sub toplevel
{
	$shell=&u::createshell($db,$user,'allcats.tpl','ecommerce');
	my $rows;
	my $row = &in::cat('tpls/allcats_level1.tpl');
	my $row2 = &in::cat('tpls/allcats_level2.tpl');
	my $sqr = $db->prepare("select * from category where catid like ? and catid not like ? order by catname");
	$qr = $db->prepare("select * from category where catid not like '%:%' order by catname");
	$qr->execute;
	while(my $h = $qr->fetchrow_hashref)
	{
		my $nrow = $row;

      $$h{catgraphic} =~ s/\:/-/g;
      $$h{catgraphic} = 'default.png' if (! -e "$ENV{DOCUMENT_ROOT}/images/categorys/$$h{catgraphic}" || !$$h{catgraphic});


		&udbi::databasemerge(\$nrow,$h);
		$rows .= $nrow;
		#$sqr->execute("$$h{catid}:\%","$$h{catid}:\%:\%");
		#while(my $h2 = $sqr->fetchrow_hashref)
		#{
		#	my $nrow2 = $row2;
		#	&udbi::databasemerge(\$nrow2,$h2);
		#	$rows .= $nrow2;
		#}
	}
  $$shell =~ s/<<rows>>/$rows/;
	&udbi::databasemerge($shell);
	&in::ct;
	print $$shell;
}

sub allcats
{
	$shell=&u::createshell($db,$user,'allcats.tpl','ecommerce');
	my $rows;
	my $row = &in::cat('tpls/allcats_level1.tpl');
	my $row2 = &in::cat('tpls/allcats_level2.tpl');
	my $sqr = $db->prepare("select * from category where catid like ? and catid not like ? order by catname");
	$qr = $db->prepare("select * from category where catid not like '%:%' order by catname");
	$qr->execute;
	while(my $h = $qr->fetchrow_hashref)
	{
		my $nrow = $row;
		&udbi::databasemerge(\$nrow,$h);
		$rows .= $nrow;
		$sqr->execute("$$h{catid}:\%","$$h{catid}:\%:\%");
		while(my $h2 = $sqr->fetchrow_hashref)
		{
			my $nrow2 = $row2;
			&udbi::databasemerge(\$nrow2,$h2);
			$rows .= $nrow2;
		}
	}
  $$shell =~ s/<<rows>>/$rows/;
	&udbi::databasemerge($shell);
	&in::ct;
	print $$shell;
}
