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

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

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

sub main {
    my $self = shift;

    # /login?email=<email>&password=<password>
    #    display stats for that e-mail
    #    allow settings to be changed if password is valid

    my $email = $self->{query}->param('email');
    my $passwordGiven = $self->{query}->param('password');
    my($passwordReal, $id, $name) = $self->{database}->getUser($email);

    if (not defined $id) {
        return $self->{http}->error('404 Not Found', 'The e-mail address you provided is not registered.');
    }

    my($a, $b, $c) = $self->{database}->getReferralStatsForUser($email);
    foreach ($a, $b, $c) {
        $_ = 0 unless defined $_;
        $_ = encode_entities($_);
    }

    $self->{http}->page("Statistics for $name");
    $self->{http}->print(<<eof);
   <dl>
    <dt>Total number of unique clickthroughs:</dt>
    <dd>$a</dd>
    <dt>Referrals who went on to download something:</dt>
    <dd>$b</dd>
    <dt>Referrals who went on to register:</dt>
    <dd>$c</dd>
   </dl>
   <p>These numbers are, of course, only approximate.</p>
eof
    ; # reset fontlock

    if (defined $passwordGiven and $passwordGiven eq $passwordReal) {
        my $destinations = $self->{database}->getDestinations();
        if (@$destinations) {
            $self->{http}->print("<h2>Using Your Account</h2>\n");
            $self->{http}->print("<p>To refer people, use the appropriate link from the list below:</p>\n<dl>\n");
            my $prefix = $ENV{SCRIPT_URI};
            $id = uri_escape($id);
            $prefix =~ s/login$/refer?referrer=$id&destination=/;
            foreach (@$destinations) {
                my $refuri1 = encode_entities($prefix . uri_escape($_->{id}));
                my $refuri2 = encode_entities($refuri1);
                my $uri = encode_entities($_->{uri});
                $self->{http}->print("<dt>To link to: <a href=\"$uri\">$uri</a></dt>\n<dd>Use this HTML: <code>&lt;a href=\"<a href=\"$refuri1\">$refuri2</a>\"&gt;...&lt;/a&gt;</code></dd>");
            }
            $self->{http}->print("</dl>\n");
        }
        $self->{http}->print('<p>To change your settings, ask an administrator.</p>'); # XXX
    }

}
