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

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

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

sub main {
    my $self = shift;

    # /refer?referrer=referrer-id&destination=destination-id:
    #    check destination is known. If it isn't, map it to destination 0.
    #    does user have cookie?
    #    no:
    #        create new tracking id, associated with referrer and destination (in original, and download if appropriate).
    #        send new cookie with tracking id and redirect to verification
    #    yes:
    #        this is another referral for someone already referred.
    #        if destination is download:
    #           update the tracking entry to have this destination-id as the download if there isn't one already.
    #        redirect to destination

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

    #    check destination is known. If it isn't, map it to destination 0.
    my $uri = $self->{database}->getDestination($destination);
    if (not defined $uri) {
        $destination = 0;
        $uri = $self->{database}->getDestination($destination) || $self->{config}->{home};
    }

    #    does user have cookie?
    my $cookie = $self->getCookie();

    if (not defined $cookie) {
        #    no:
        #        create new tracking id, associated with referrer and destination (in original, and download if appropriate).
        my $id = $self->{database}->newReferral($referrer, $ENV{REMOTE_ADDR}, time);
        $self->{database}->updateReferralSetDestination($referrer, $destination);
        #        send new cookie with tracking id and redirect to verification
        $self->setCookie($id);
        foreach ($referrer, $id, $destination) {
            $_ = encode_entities($_);
        }
        $self->{http}->redirect("verify?referrer=$referrer&user=$id&destination=$destination");
    } else {
        #    yes:
        #        this is another referral for someone already referred.
        #        if destination is download:
        #           update the tracking entry to have this destination-id as the download if there isn't one already.
        $self->{database}->updateReferralSetDestination($cookie, $destination);
        #        redirect to destination
        $self->{http}->redirect($uri);
    }

}
