#!/usr/bin/perl

#This file will add products to a content page - for example for Christmas gifts

use CGI;

use strict;
use lib '/home/sites/home/web/perl/admin';
use Links qw/$CFG $IN $DB $USER/;
Links::init('/home/sites/home/web/perl/admin');
Links::init_user();
use Links::SiteHTML;
use GT::SQL::Condition;
use GT::Dumper;
use GT::Date qw/:all/;

main();

sub main {
    my $in = $IN->get_hash;
    my $referer=$ENV{'HTTP_REFERER'};
    if ($in->{'do'}){
     unless ($in->{'do'} eq 'show'){ 
      unless ($referer=~/theukhighstreet.com/){&show_home();}
     }
    }
    if ($in->{'do'} eq 'show'){
      &show_gifts($in);
    }
    elsif ($in->{'do'} eq 'add_gift'){
      &do_add($in);
    }
    elsif ($in->{'do'} eq 'vote_for'){
      &do_vote_for($in);
    }
    elsif ($in->{'do'} eq 'vote_against'){
      &do_vote_against($in);
    }
    else{
      &show_home();
    }
}

sub add_gift {
    my $in=shift;
    print $IN->header;
    print Links::SiteHTML::display('gifts_add',$in);
}

sub show_gifts {
    my $in=shift;
    my $gifts=get_gifts($in->{'Age'},$in->{'Interests'},$in->{'Pricelt'},$in->{'Pricegt'},$in->{'nh'});
    $in->{'gifts_loop'} = $gifts->{'Gifts'};
    $in->{'old_loop'} = $gifts->{'Giftsold'};
    my $numhits = $in->{'numhits'} = $gifts->{'Total'};
    my $page="&amp;do=show&amp;Age=$in->{Age}&amp;Interests=$in->{Interests}";
    my $nh=$in->{'nh'}||'1';
    my $maxhits = $in->{'maxhits'} || 20;
    my %paging;
    if ($in->{'numhits'} > $in->{'maxhits'}) {
        %paging = (
                 url => "/perl/gifts.cgi?$page",
                 #page_format => 1,
                 num_hits => $numhits,
                 max_hits => $maxhits,
                 current_page => $nh
        );
    }
    $in->{'paging'}=\%paging;
    $in->{'category'} = &subcats;
    print $IN->header;
    print Links::SiteHTML::display('gifts',$in);
}

sub do_add {
    my $in=shift;
    my $product= $in->{'P_ID'};
    my $linkid=$in->{LinkID};
    my $owner = $USER->{'Username'}||'admin';
    my $age = $in->{'Age'}||'All';
    my $interests = $in->{'Interests'}||'Everything';
    my $gifts_db=$DB->table('Gifts');
    my $table = $in->{'TableName'};
#    my $clicktrack=$DB->table('PClickTrack');
    my $ip = $ENV{HTTP_X_FORWARDED_FOR} || $ENV{REMOTE_HOST} || $ENV{REMOTE_ADDR} || 'None';
    $ip=~s/^([^,]*).*$/$1/;

    my $rows = $gifts_db->count ( { P_ID => $product,LinkID=>$linkid, TableName => $table, Age => $age,Owner=>$owner,Interests=>$interests});
    if (! $rows){
      my $sth = $gifts_db->insert(
           P_ID=>$product,
           LinkID=>$linkid,
           TableName=>$table,
           P_Title=>$in->{'P_Title'},
           Owner=>$owner,
           Age=>$age,
           Interests=>$interests,
           );
#Can't add to clicktrack because you don't have the id
    my $hours = date_get ( (time() - 86400), '%yyyy%-%mm%-%dd% %HH%:%MM%:%ss%' ); # 1 day old
    my $clicktrack = $DB->table('PClickTrack');
    $clicktrack->insert({PID=>$product,LinkID=>$linkid,IP=>$ip,ClickType=>'For',Created=>\"NOW()" });
#add to newsfeed
    $DB->table('NewsFeed')->insert({Action=>'GiftSuggest',fk_productid=>$product,fk_link_id=>$linkid,fk_user=>$owner,Details=>"$in->{P_Title} was suggested as a gift"})||return $GT::SQL::error;

    # Print success page
        print $IN->header;
        print Links::SiteHTML::display('include_gift',$in);
        print "Thanks, your suggestion has been added";    
    }
    else {
      my $sth=$gifts_db->update ( { Vote_for => \"Vote_for + 1", P_Title=>$in->{'P_Title'} }, { P_ID => $product,LinkID=>$linkid,TableName=>$table,Age=>$age,Interests=>$interests,Owner=>$owner});
    $DB->table('NewsFeed')->insert({Action=>'GiftSuggest',fk_productid=>$product,fk_link_id=>$linkid,fk_user=>$owner,Details=>"$in->{P_Title} was suggested as a gift"})||return $GT::SQL::error;
      print $IN->header;
      print Links::SiteHTML::display('include_gift',$in);
      print 'Thanks, your suggestion has been added.';
    }
}

sub do_vote_for {
    my $in=shift;
    my $id= $in->{'ID'};
    my $linkid=$in->{'LinkID'};
    my $owner = $USER->{'Username'}||'admin';
    my $table = $in->{'TableName'}||'Products';

    # Add to Gifts table
    my $gifts_db = $DB->table('Gifts');

   my $ip = $ENV{HTTP_X_FORWARDED_FOR} || $ENV{REMOTE_HOST} || $ENV{REMOTE_ADDR} || 'None';
   $ip=~s/^([^,]*).*$/$1/;

   my $hours = date_get ( (time() - 86400), '%yyyy%-%mm%-%dd% %HH%:%MM%:%ss%' ); # 1 day old
   my $clicktrack = $DB->table('PClickTrack');
   $clicktrack->delete (GT::SQL::Condition->new ( 'Created', '<', $hours));
   my $rows = $clicktrack->count ( GT::SQL::Condition->new ('PID','=',$id,'LinkID','=',$linkid,'IP','=',$ip,'ClickType','=','For'));

#    my $rows = $clicktrack->count({ PID => $id, IP => $ip, ClickType => 'For' });
    if ($rows) {
      my $vfxt=$gifts_db->get($id);
      $vfxt->{ProductID}=$vfxt->{P_ID};
      $vfxt->{P_LinkID}=$vfxt->{LinkiD};      
    print $IN->header;
    my $message= Links::SiteHTML::display('include_gift',$vfxt);
    $message.= 'Sorry - you can only vote once per day.';
    print $message;
    }
    else {
    my $sth=$gifts_db->update ( { Vote_for => \"Vote_for + 1"}, { ID => $id});
    $clicktrack->insert({PID=>$id,IP=>$ip,ClickType=>'For',Created=>\"NOW()" });
    my $vfxt=$gifts_db->get($id);
    $DB->table('NewsFeed')->insert({Action=>'GiftSuggest',fk_productid=>$vfxt->{P_ID},fk_link_id=>$linkid,fk_user=>$owner,Details=>"$vfxt->{P_Title} was suggested as a gift"})||return $GT::SQL::error;
    
    print $IN->header;
    my $message= Links::SiteHTML::display('include_gift',$vfxt);
    $message.= 'Thanks. We have added your vote.';
    print $message; 
    }
}

sub do_vote_against {
    my $in=shift;
    my $id= $in->{'ID'};
    my $linkid=$in->{'LinkID'};
    my $owner = $USER->{'Username'}||'admin';
    my $table = $in->{'TableName'}||'Products';

    # Add to Gifts table

   my $ip =$ENV{HTTP_X_FORWARDED_FOR} || $ENV{REMOTE_HOST} || $ENV{REMOTE_ADDR} || 'None';
   $ip=~s/^([^,]*).*$/$1/;

   my $hours = date_get ( (time() - 86400), '%yyyy%-%mm%-%dd% %HH%:%MM%:%ss%' ); # 1 day old
   my $clicktrack = $DB->table('PClickTrack');
   $clicktrack->delete (GT::SQL::Condition->new ( 'Created', '<', $hours));
   my $rows = $clicktrack->count ( GT::SQL::Condition->new ( 'PID','=',$id,'LinkID','=',$linkid,'IP','=',$ip,'ClickType','=','Against'));

#    my $rows = $clicktrack->count({ LinkID => $id, IP => $ip, ClickType => 'Against' });
    if ($rows) {
    my $gifts_db = $DB->table('Gifts');
    my $vfxt=$gifts_db->get($id);
  $vfxt->{ProductID}=$vfxt->{P_ID};
  $vfxt->{P_LinkID}=$vfxt->{LinkID};

    print $IN->header;
    my $message= Links::SiteHTML::display('include_gift',$vfxt);
    $message.= 'Sorry - you can only vote once per day.';
    print $message;

    my $temp2=$vfxt;
    $message.= Links::SiteHTML::display ('update_gift', $temp2);
    print $message;
    }
}


sub show_home {
      print $IN->header;
      print Links::SiteHTML::display('home');
}

sub get_gifts {
 my $age=shift;
 my $interests=shift;
 my $pricegt=shift;
 my $pricelt=shift;
 my $nh=shift||1;
 my $mh=20;
 my $offset = ($nh-1) * $mh;
 my ($agecond,$intcond,$pricecond,$cond);
  $cond=GT::SQL::Condition->new('Gifts.LinkID','=',\'Products.P_LinkID','Gifts.P_ID','=',\'Products.ProductID','Links.isValidated','=','Yes');
 if ($interests)
  {$intcond = GT::SQL::Condition->new ('Interests', '=', $interests, 'Interests','=','All');
   $intcond->bool('or');
 }
 if ($age)
  {$agecond = GT::SQL::Condition->new( 'Age', '=', $age,'Age','=','All');
   $agecond->bool('or');
 }
 if ($pricelt or $pricegt){
 $pricecond = GT::SQL::Condition->new('P_Price','>=',$pricelt,'P_Price','<=',$pricegt);
 }
 my ($lastpage,@gifts,$ids,@oldgifts,$cond1);
# my $tb = $DB->table('Gifts');
# my @ids= select ('Distinct P_ID',$agecond,$intcond,$pricecond);
 my $table = $DB->table('Gifts','Products','Links');
 $table->select_options("ORDER BY Vote_for - Vote_against DESC, P_Hits ASC","LIMIT $offset, $mh");
 my $gifts = $table->select( [ 'Distinct P_ID','Links.*' ,'Products.*'],$cond,$agecond,$intcond,$pricecond)->fetchall_hashref;
my $total=$table->select('Distinct P_ID',$agecond,$intcond,$pricecond,$cond)->rows || 0;
if (($total-$offset)<=$mh){
$lastpage=1;
}
return {Gifts=>$gifts,Total=>$total,Giftsold=>\@oldgifts};
}


sub subcats {
### Added to get subcategory data
my $display;
my $category;
$category->{ID}='108';

my $subcat_ids = []; my $relate_ids = [];
#$display{category_loop} = [$category];
my $sth = $DB->table('Category')->select ( { FatherID => $category->{ID} }, ['ID'] );
$sth->rows() and ($subcat_ids = $sth->fetchall_arrayref);
$sth = $DB->table('CatRelations')->select ( { CategoryID => $category->{ID} }, ['RelatedID','RelationName'] ) or die $GT::SQL::error;
$sth->rows() and ($relate_ids = $sth->fetchall_arrayref);
if (@$subcat_ids || @$relate_ids) {
       my %rel = map { $_->[0] => $_->[1] } @$relate_ids;
       my $ids = '(' . join (",", map { $_->[0] } @$subcat_ids, @$relate_ids) . ')';
       $DB->table('Category')->select_options ("ORDER BY Name DESC");
       $sth = $DB->table('Category')->select ( GT::SQL::Condition->new ('ID', 'IN', \$ids) );
       while (my $cat = $sth->fetchrow_hashref) {
           if (exists $rel{$cat->{ID}}) {
                 $cat->{Related} = 1;
                 $cat->{RelationName} = $rel{$cat->{ID}};
           }
           push @{$display->{category_loop}}, $cat;
       }
       $display->{category} =  Links::SiteHTML::display ('print_cat', $display->{category_loop});
}
else {
       $display->{category} = '';
       shift @{$display->{category_loop}}; # The loop var shouldn't have the root cat.
}
return $display->{category};
}
1;
