package Stat::Affiliate;

use strict;

use Apache::Constants qw/:common REDIRECT/;
use Apache::Session::Oracle;
use Apache::Cookie;

use vars qw/$dbh $debug/;

use constant SESSION_COOKIE => 'sessionid';

$debug = 0;

sub handler {

    my $r = shift;

    # Hi, I'm a new web surfer.  I've just clicked thru the banner.
    # Please give me a session so the webmaster gets proper credit.

    # parse session_id
    my $session_id = parse_session_id();

    return DECLINED if $r->header_only;
    # create session
    create_session($r) or return DECLINED;

    # all done
    $r->header_out(Location => "http://www.exitexchange.com/");
    return REDIRECT;

}

sub parse_session_id {
    my %cookies = Apache::Cookie->fetch;
    my ($session_id) = $cookies{ +SESSION_COOKIE }->value if exists $cookies{ +SESSION_COOKIE };

    $session_id = $session_id ? $session_id : undef;
}

sub get_dbi_handle {
    DBI->connect(My::dbi_connect_string, My::dbi_pwd_fetch) or return undef;
}

sub create_session {
    my $r = shift;
    my $session_id = shift;
    my ($referer, %session);

    $referer = $r->path_info();
    $referer =~ s/^\///;
    $referer =~ /^\d+$/ or return undef;

    $dbh ||= get_dbi_handle() or return undef;
    local $dbh->{AutoCommit} = 0;
    tie %session, 'Apache::Session::Oracle', $session_id, { Handle => $dbh, Commit => 1};
    $session_id = $session{_session_id}; # save a copy

    _set_cookie( $r, SESSION_COOKIE, $session{_session_id} );

    $session{referer} ||= $referer; # preserve prior entries

    untie %session;

    return $session_id;
}

sub _set_cookie {
    my ($r, $name, $value, $path, $exp) = @_;
    $path ||= '/';
    $exp ||= '+10y';

    my $cookie = Apache::Cookie->new( $r,
				      -name => $name,
				      -value => $value,
				      -path => $path,
				      -domain => ".$ENV{DOMAIN}",
				      -expires => $exp,
				    );

    if ($debug > 1) {
 	warn "set_cookie: ", $cookie->as_string, "\n";
    }

    $cookie->bake;

}

1;
