# ==================================================================
# Plugins::MostPopular - Auto Generated Program Module
#
#   Plugins::MostPopular
#   Author  : Virginia Lo
#   Version : 1.0
#   Updated : Tue Sep  4 11:23:30 2007
#
# ==================================================================
#

package Plugins::MostPopular;
# ==================================================================

use strict;
use GT::Base;
use GT::Plugins qw/STOP CONTINUE/;
use Links qw/:objects/;

# Inherit from base class for debug and error methods
@Plugins::MostPopular::ISA = qw(GT::Base);

# Your code begins here.


# PLUGIN HOOKS
# ===================================================================


sub jump_link {
# -----------------------------------------------------------------------------
# This subroutine will be called whenever the hook 'jump_link' is run.  You
# should call $PLG->action(STOP) if you don't want the regular
# 'jump_link' code to run, otherwise the code will continue as normal.
#
    $PLG->action(STOP);
    my $links = $DB->table('Links');
    my $id = $IN->param('ID') || $IN->param('Detailed');
    my $action = $IN->param('action') || '';
    my $goto = '';
    my $rec = {};

    if ($CFG->{framed_jump} and $id and $action eq 'jump_frame') {
        my $error;
        if ($id !~ /^\d+$/) {
            $error = Links::language('JUMP_INVALIDID', $id);
        }
        else {
            $rec = $links->select({ ID => $id }, VIEWABLE)->fetchrow_hashref;
            unless ($rec) {
                $error = Links::language('JUMP_INVALIDID', $id);
                $rec = {};
            }
            elsif ($CFG->{build_detailed}) {
                $rec->{detailed_url} = "$CFG->{build_detail_url}/" . $links->detailed_url($id);
            }
        }
        print $IN->header();
        print Links::SiteHTML::display('jump_frame', { error => $error, %$rec });
        return;
    }

# If we are chosing a random link, then get the total and go to one at random.
    if (lc $id eq "random") {
        my $offset = int rand $links->count(VIEWABLE);
        $links->select_options("LIMIT 1 OFFSET $offset");
        my $sth = $links->select(qw/ID URL/ => VIEWABLE);
        ($id, $goto) = $sth->fetchrow_array;
    }
    elsif (defined $id) {
        if ($id !~ /^\d+$/) {
            print $IN->header();
            print Links::SiteHTML::display('error', { error => Links::language('JUMP_INVALIDID', $id) });
            return;
        }

# Find out if we're going to be displaying a file
        my $col = $IN->param('v') || $IN->param('dl') || $IN->param('view') || $IN->param('download');

        if ($col) {
# in this case, we need to know from what table we want to load our data from.
# It will by default pull information from the Links table, however if the
# DB=tablename option is used, it will apply the request to that table instead
            my $table_name = $IN->param('DB') || 'Links';

            unless ($table_name =~ m/^\w+$/) {
                print $IN->header();
                print Links::SiteHTML::display('error', { error => Links::language('FILE_TABLEFORMAT' ) });
                return;
            };

            if ($table_name ne 'Links') {
                eval { $links = $DB->table($table_name) };
                if ($@) {
                    print $IN->header();
                    print Links::SiteHTML::display('error', { error => Links::language('FILE_TABLE', $table_name, $GT::SQL::error) });
                    return;
                }
            }

            my $fh;
            eval { $fh = $links->file_info($col, $id); };
            if ($fh) {
                if ($IN->param('v') or $IN->param('view')) {    # Viewing
                    print $IN->header($IN->file_headers(
                        filename => $fh->File_Name,
                        mimetype => $fh->File_MimeType,
                        inline   => 1,
                        size     => $fh->File_Size
                    ));
                }
                else {                                          # Downloading
                    print $IN->header($IN->file_headers(
                        filename => $fh->File_Name,
                        mimetype => $fh->File_MimeType,
                        inline   => 0,
                        size     => $fh->File_Size
                    ));
                }
                binmode $fh;
                while (read($fh, my $buffer, 65536)) {
                    print $buffer;
                }
                return 1;
            }
            else {
                print $IN->header();
                print Links::SiteHTML::display('error', { error => Links::language('FILE_UNKNOWN', $id) });
                return;
            }
        }
# Jump to a URL, bump the hit counter.
        else {
            $rec = $links->select({ ID => $id }, VIEWABLE)->fetchrow_hashref;
            unless ($rec) {
                print $IN->header();
                print Links::SiteHTML::display('error', { error => Links::language('JUMP_INVALIDID', $id) });
                return;
            }
            $goto = $rec->{URL};

            my $clicktrack = $DB->table('ClickTrack');
            my $customdb = $DB->table('ClickTrack_Custom');

            my $rows = $clicktrack->count({ LinkID => $id, IP => $ENV{REMOTE_ADDR}, ClickType => 'Hits' });
            unless ($rows) {
                eval {
                    $clicktrack->insert({ LinkID => $id, IP => $ENV{REMOTE_ADDR}, ClickType => 'Hits', Created => \"NOW()" });
                    $customdb->insert({ click_linkid => $id, click_date => \"NOW()" });
                    $links->update({ Hits => \"Hits + 1", Timestmp => $rec->{Timestmp} }, { ID => $id }, { GT_SQL_SKIP_INDEX => 1 });
                };
            }
        }
    }
# Oops, no link.
    else {
        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')) {
        $goto = Links::transform_url("$CFG->{build_detail_url}/" . $links->detailed_url($id));
    }
    ($goto =~ m,^\w+://,) or ($goto = "http://$goto");

    unless (defined $goto) {
        my $error = ($IN->param('ID') eq 'random') ? Links::language('RANDOM_NOLINKS') : Links::language('JUMP_INVALIDID', $id);
        print $IN->header();
        print Links::SiteHTML::display('error', { error => $error });
        return;
    }

    if ($goto) {
        if ($CFG->{framed_jump} and not ($CFG->{build_detailed} and $IN->param('Detailed'))) {
            unless (keys %$rec) {
                $rec = $links->select({ ID => $id }, VIEWABLE)->fetchrow_hashref;
            }
            $rec->{detailed_url} = "$CFG->{build_detail_url}/" . $links->detailed_url($id) if $CFG->{build_detailed};
            print $IN->header();
            print Links::SiteHTML::display('jump', { destination => $goto, %$rec });
            return;
        }
        else {
            print $IN->redirect($goto);
        }
    }
    else {
        print $IN->header();
        print Links::SiteHTML::display('error', { error => Links::language('JUMP_INVALIDID', $id) });
        return;
    }
}

sub generate_popular_links {
    my $mh = shift || 5;
    if ($GLinks::MOSTPOP) {
        return $GLinks::MOSTPOP;
    }
                     
    my $today = GT::Date::date_get();
    require Links::Plugins;
    my $cfg = Links::Plugins::get_plugin_user_cfg('MostPopular');
    my $last_x_days = $cfg->{last_x_days} || 14;
    my $from_date = GT::Date::date_sub($today, $last_x_days);
    my $to_date = GT::Date::date_sub($today, 0);
    require GT::SQL::Condition;
  #my $cond = GT::SQL::Condition->new('click_date', '>=', $from_date, 'click_date','<=', $to_date);
    my $cond = GT::SQL::Condition->new('Mod_Date', '>=', $from_date, 'Mod_Date','<=', $to_date);
  #my $db = $DB->table('ClickTrack_Custom');
	my $db = $DB->table('Links');
    my $linksdb = $DB->table('Links');
    use Data::Dumper;
    #$db->select_options('GROUP by click_linkid','ORDER BY count desc',"Limit $mh");	
	$db->select_options('ORDER BY Hits DESC',"Limit $mh");
  #my $sth = $db->select($cond, ['count(*) as count', 'click_linkid']);
    my $sth = $db->select($cond, ['ID']);
	my @loop;
    while (my $row = $sth->fetchrow_hashref()) {
        my $link = $linksdb->get($row->{ID});
        $link = Links::SiteHTML::tags('link',$link);
        push @loop, { %$link, %$row };
    }

    $GLinks::MOSTPOP = { MostPopularLinks => \@loop, FromDate => $from_date, ToDate => $to_date };
    return $GLinks::MOSTPOP;
}

# Always end with a 1.
1;
