#!/usr/bin/perl -wT
# -*- Mode: perl; tab-width: 4; indent-tabs-mode: nil; -*-
#
# Referrer Tracking: Verification

use strict;
use CGI::Carp;
use HTML::Entities;
use lib 'lib';

use vars '@ISA';
@ISA = qw(TheCommon);
require TheCommon;

sub main {
    my $self = shift;

    # /verify?referrer=referrer-id&user=tracking-id&destination=destination-id
    #    check that there is an entry for referred-id, tracking-id, destination-id (as original)
    #    check tracking-id matches what the user's cookie says
    #    if there is no cookie or if it doesn't match remove the entry in the database
    #    redirect to destination

    # /verify?referrer=referrer-id&user=tracking-id&destination=destination-id
    my $referrer = $self->{query}->param('referrer');
    my $user = $self->{query}->param('user');
    my $destination = $self->{query}->param('destination');

    #    check that there is an entry for referred-id, tracking-id, destination-id (as original)
    #    check tracking-id matches what the user's cookie says
    my $cookie = $self->getCookie();
    if ((not defined $cookie) or
        ($cookie ne $user) or
        (not $self->{database}->checkReferral($user, $referrer, $destination))) {
        #    if there is no cookie or if it doesn't match remove the entry in the database
        $self->{database}->removeReferral($user);
    }
    #    redirect to destination

    my $uri = $self->{database}->getDestination($destination);
    if (not defined $uri) {
        $uri = $self->{config}->{home};
    }
    $self->{http}->redirect($uri);

}
