#!/usr/local/bin/perl
# ==================================================================
# Links SQL - Pay Per Click Plugin
#
#   Website  : http://gossamer-threads.com/
#   Support  : http://gossamer-threads.com/scripts/support/
#   CVS Info : 087,069,092,093,081 
#   Revision : $Id: ppc_jump.cgi,v 1.5 2002/03/08 01:21:39 mel Exp $
# 
# Copyright (c) 2001 Gossamer Threads Inc.  All Rights Reserved.
# Redistribution in part or in whole strictly prohibited. Please
# see LICENSE file for full details.
# ==================================================================

    use strict;
    use lib '/home/hsasia/public_html/cgi-bin/admin';
    use Links qw/$USER $IN $DB $CFG/;
    use Links::SiteHTML;
    use Links::Plugins;

    local $SIG{__DIE__} = \&Links::fatal;
    Links::init('admin');
    Links::init_user(); 
    
    main();

sub main {
# --------------------------------------------------------------
# Redirect user to either random url, or given id.
#
    my ($db, $click_db, $delete_by, $total, $offset, $id, $ppc, $sth, $rec);
    $db   = $DB->table('Links');
    $id   = $IN->param('ID') || $IN->param('Detailed');
    $ppc = '';
    my $from = $IN->param('From');

# If we are chosing a random link, then get the total and go to one at random.
    if (lc $id eq "random") {
        $total  = $db->total() - $db->count({ isValidated => 'No' });
        $offset = int rand $total;
        $db->select_options ("LIMIT $offset, 1");
        $sth = $db->select ( { isValidated => 'Yes' }, ['URL'] );
        ($ppc) = $sth->fetchrow_array;
    }
# Otherwise, if we have a link, let's look it up.
    elsif (defined $id) {
        if ($id !~ /^\d+$/) {
            print $IN->header();
            print Links::SiteHTML::display ('error', { error => Links::language ('JUMP_INVALIDID', $id) });
            return;
        }
        $rec = $db->get ($id);
        if (! $rec or ($rec->{isValidated} eq 'No')) {
            print $IN->header();
            print Links::SiteHTML::display ('error', { error => Links::language ('JUMP_INVALIDID', $id) });
            return;         
        }
        $ppc = $rec->{URL};

        my $ip   = $ENV{REMOTE_HOST} || $ENV{REMOTE_ADDR} || 'None';
        my $click_db = $DB->table ('ClickTrack');
        my $rows = $click_db->count ( { LinkID => $id, IP => $ip, ClickType => 'Hits' } );
        if (! $rows) {
            $db->update ( { Hits => \"Hits + 1" }, { ID => $id }, { GT_SQL_SKIP_INDEX => 1 } );
            $click_db->insert ( { LinkID => $id, IP => $ip, ClickType => 'Hits', Created => \"NOW()"} );
        }

#-----  Mod for ppc plugin
    my $cfg = Links::Plugins::get_plugin_user_cfg('PPC');  
    $from ||='Category';
    if ($from eq 'Category') {
        my $bid_table = $DB->table('Category_Bids','Links','Users');
        if (my $bid = $bid_table->select({Link_ID_FK => $id,Bid_Status => 'Validated'})->fetchrow_hashref) {
            $bid_table = $DB->table('Category_Bids');
            $bid_table->update(
                {Num_Clicks => \'Num_Clicks+1'},
                {Category_Bid_ID => $bid->{Category_Bid_ID}}
            );
            my $user = $DB->table('Bidders')->get($bid->{Bid_Username_FK});
            my $bidder_table = $DB->table('Bidders');
            my $click_table = $DB->table('Category_Clicks');
            my $c_table = $DB->table('Category_Clicks');
            $c_table->select_options('ORDER BY Time_Date DESC','LIMIT 1');

            my $click = $click_table->select({Remote_Host => $ip,Category_Bid_ID_FK => $bid->{Category_Bid_ID}})->fetchrow_hashref;
            $click->{Time_Date} ||= "0000-00-00 00:00:00";
            require GT::Date;
            my $unix_time = GT::Date::timelocal ( @{ GT::Date::_parse_format($click->{Time_Date}, '%yyyy%-%mm%-%dd% %hh%:%MM%:%ss%')} );
            my $now = time;
            if (((($now - 60 *  $cfg->{time_between_clicks}) > $unix_time) && $cfg->{limit_clicks}) || (!$cfg->{limit_clicks}) ) {
                my $remainder = $user->{Bid_Remainder}-$bid->{Bid};
                my $add_str = "Bid_Remainder - $bid->{Bid}";
                $bidder_table->update(
                    {Bid_Remainder => $remainder},
                    {Bid_Username => $bid->{Bid_Username_FK}}
                );
            
                $click_table->insert({
                    Category_Bid_ID_FK => $bid->{Category_Bid_ID},
                    Bid_Amount => $bid->{Bid},
                    Remote_Host => $ip,
                    Time_Date =>  \"NOW()",
                    Username => $USER->{Username}
                }) or die "Category_Bid_ID is $bid->{Category_Bid_ID}, $GT::SQL::error";
                if ($remainder <= 0) {
                    $DB->table('Category_Bids')->update({Bid_Status => 'Out of Funds'},{Bid_Username_FK => $bid->{Bid_Username_FK},Bid_Status => 'Validated'});
                    $DB->table('Keyword_Bids')->update({Bid_Status => 'Out of Funds'},{Bid_Username_FK => $bid->{Bid_Username_FK},Bid_Status => 'Validated'});
                    if ($cfg->{email_user_out_of_funds}) {
                        my $msg = GT::Template->parse('ppc_user_outoffunds_email.txt',{%$bid},{compress => 0,  root => "$CFG->{admin_root_path}/templates/$CFG->{build_default_tpl}"});
                        require GT::Mail;
                        $GT::Mail::error ||= ''; # Silence -w
                        GT::Mail->send (
                            smtp      => $CFG->{db_smtp_server},
                            sendmail  => $CFG->{db_mail_path},
                            from      => $cfg->{payments_email},
                            subject   => "Bidding Account Balance",
                            to        => $bid->{Email},
                            msg       => $msg,
                            debug     => $Links::DEBUG
                        ) or Links::fatal ("Unable to send mail: $GT::Mail::error");
                    }                     
                
                }
            }
        }
    }
    elsif ($from eq 'Search') {
        my $bid_table = $DB->table('Keyword_Bids','Links','Users');
        my $keywordid = $IN->param('Keyword_ID_FK');
        if (my $bid = $bid_table->select({Link_ID_FK => $id,Bid_Status => 'Validated', Keyword_ID_FK => $keywordid})->fetchrow_hashref) {
            $bid_table = $DB->table('Keyword_Bids');
            
            $bid_table->update(
                {Num_Clicks => \'Num_Clicks+1'},
                {Keyword_Bid_ID => $bid->{Keyword_Bid_ID}}
            );
            my $user = $DB->table('Bidders')->get($bid->{Bid_Username_FK});
            my $bidder_table = $DB->table('Bidders');
            my $click_table = $DB->table('Keyword_Clicks');
            my $c_table = $DB->table('Keyword_Clicks');
            $c_table->select_options('ORDER BY Time_Date DESC','LIMIT 1');

            my $click=$click_table->select({Remote_Host => $ip,Keyword_Bid_ID_FK => $bid->{Keyword_Bid_ID}})->fetchrow_hashref;
            $click->{Time_Date} ||= "0000-00-00 00:00:00";
            require GT::Date;
            my $unix_time=GT::Date::timelocal ( @{ GT::Date::_parse_format($click->{Time_Date}, '%yyyy%-%mm%-%dd% %hh%:%MM%:%ss%')} );
            my $now = time;
            if (((($now - 60 *  $cfg->{time_between_clicks}) > $unix_time) && $cfg->{limit_clicks}) || (!$cfg->{limit_clicks}) ) {
                my $remainder = $user->{Bid_Remainder}-$bid->{Bid};
                my $add_str = "Bid_Remainder - $bid->{Bid}";
                $bidder_table->update(
                    {Bid_Remainder => $remainder},
                    {Bid_Username => $bid->{Bid_Username_FK}}
                );
            
                $click_table->insert({
                    Keyword_Bid_ID_FK => $bid->{Keyword_Bid_ID},
                    Bid_Amount => $bid->{Bid},
                    Remote_Host => $ip,
                    Time_Date =>  \"NOW()",
                    Username => $USER->{Username}
                }) or die "Keyword_Bid_ID is $bid->{Keyword_Bid_ID}, $GT::SQL::error";
                if ($remainder <= 0) {
                    $DB->table('Category_Bids')->update({Bid_Status => 'Out of Funds'},{Bid_Username_FK => $bid->{Bid_Username_FK},Bid_Status => 'Validated'});
                    $DB->table('Keyword_Bids')->update({Bid_Status => 'Out of Funds'},{Bid_Username_FK => $bid->{Bid_Username_FK},Bid_Status => 'Validated'});
                    if ($cfg->{email_user_out_of_funds}) {
                        my $msg = GT::Template->parse('ppc_user_outoffunds_email.txt',{%$bid},{compress => 0,  root => "$CFG->{admin_root_path}/templates/$CFG->{build_default_tpl}"});
                        require GT::Mail;
                        $GT::Mail::error ||= ''; # Silence -w
                        GT::Mail->send (
                            smtp      => $CFG->{db_smtp_server},
                            sendmail  => $CFG->{db_mail_path},
                            from      => $cfg->{payments_email},
                            subject   => "Bidding Account Balance",
                            to        => $bid->{Email},
                            msg       => $msg,
                            debug     => $Links::DEBUG
                        ) or Links::fatal ("Unable to send mail: $GT::Mail::error");
                    }                     
                }
            }
        }
    
    }

#----   end of mod for ppc plugin
    }
# Oops, no link.
    else {
        print $IN->header();
        print Links::SiteHTML::display ('error', { error => Links::language ('JUMP_INVALIDID', $id) });
        return;         
    }
    if (! defined $ppc) {
        print $IN->header();
        print Links::SiteHTML::display ('error', { error => Links::language ('JUMP_INVALIDID', $id) });
        return;
    }

# Redirect to a detailed page if requested.
    if ($CFG->{build_detailed} and $IN->param('Detailed')) {
        $ppc = $CFG->{build_detail_url} . '/' . $id . $CFG->{build_index};
    }
    ($ppc =~ m,^(https?|ftp|mailto|news)://,) or ($ppc = "http://$ppc");
    if ($ppc) {
        print $IN->redirect ($ppc);
    }
    else {
        print $IN->header();
        print Links::SiteHTML::display ('error', { error => Links::language ('JUMP_INVALIDID', $id) });
        return;         
    }
}

