#!/usr/bin/perl

use CGI qw/:standard/;
use CGI::Cookie;

sub notegs
{ 
 #Удаление символов пеpевода стpоки и тегов
 local($str)=@_; 
 $str=~s/\s+/ /g;
 $str=~s/^\s+//;
 $str=~s/&/&amp;/g;
 $str=~s/</&lt;/g;
 $str=~s/>/&gt;/g;
 return $str;
}

#Распознание и запись в пеpеменные паpаметpов вызова пpогpаммы
sub urldecode
{ 
 local($val)=@_; 
 $val=~s/\+/ /g;
 $val=~s/%([0-9A-H]{2})/pack('C',hex($1))/ge;
 return $val;
} 

if($ENV{'REQUEST_METHOD'} eq 'GET')
{ 
 $query=$ENV{'QUERY_STRING'};
}
elsif($ENV{'REQUEST_METHOD'} eq 'POST')
{
 sysread STDIN,$query,$ENV{'CONTENT_LENGTH'};
}

@formfields=split /&/,$query;       
foreach(@formfields)
{
 if(/^id=(.*)/){$id=notegs(urldecode($1));}
 if(/^name=(.*)/){$name=notegs(urldecode($1));}
 if(/^dep=(.*)/){$dep=notegs(urldecode($1));}
 if(/^price=(.*)/){$price=notegs(urldecode($1));}
 if(/^count=(.*)/){$count=notegs(urldecode($1));}
 if(/^sign=(.*)/){$sign=notegs(urldecode($1));}
 if(/^img=(.*)/){$img=notegs(urldecode($1));}
}

while(($key,$val) = each(ENV))
{
 if ($key eq "REMOTE_ADDR"){$ip=$val;}
 if ($key eq "HTTP_REFERER"){$referer=$val;}
 if ($key eq "HTTP_USER_AGENT"){$browser=$val;}
}


%cookie = fetch CGI::Cookie;

if ($cookie{'custom_shop'} ne "")
{
 ($cart, $items)=$cookie{'custom_shop'}->value;

 @new_cart=();
 @cart=split /\n/, $items;

 #Удаление товара из корзины
 if ($mode eq "remove")
 {
  foreach $item (@cart)
  {
   ($item_id, $tmp)=split /#/, $item, 2;
   if ($item_id ne $id){push @new_cart, $item;}
  }

  $items=join "\n", @new_cart;

  $cookie = new CGI::Cookie(-name=>'custom_shop',-value=>{cart=>$items});
  print header(-cookie=>$cookie, -location=>$referer.'#cart');
 }

 #Пересчет корзины
 if ($mode eq "recalculate")
 {
  foreach $item (@cart)
  {
   ($id, $name, $price, $count)=split /#/, $item;
   foreach(@formfields)
   {
    if(/^$id=(.*)/){$count=notegs(urldecode($1));}
   }
 push @new_cart, $id."#".$name."#".$dep."#".$price."#".$count."#".$sign."#".$img;
  }

  $items=join "\n", @new_cart;

  $cookie = new CGI::Cookie(-name=>'custom_shop_conent',-value=>{cart=>$items});
  print header(-cookie=>$cookie, -location=>$referer);
 }

 if ($mode eq "" && $items ne "")
 {
  $sum=0;
  $order="";
  $result=0;

  foreach $item (@cart)
  {
   ($id, $name, $dep, $price, $count, $sign, $img)=split /#/, $item;
   $sum+=$price*$count;
   $result+=$count;
  }
 }
 else
 {
  $result="0";
 }
}
else
{
 $result="0";
}
print "Content-Type: text/html\n\n";
print "document.write (\'$result\');";

exit 0;

