#!/usr/local/bin/perl -w

BEGIN {
	push( @INC, '.' );
}

use strict;

use Utils;
use User;
use Proforma;
use CGI qw/unescapeHTML :standard/;
use Template;

my $q = new CGI;

my $user = new User( 1, 1, $q, $q->cookie("CGISESSID") || undef );
my $dbh = $user->dbh();

$| = 1;
cgiHeader($user);

#my $state = $q->param("state");

my $vars = {
	list => [],
};


my @proformas;

my $sth = $dbh->prepare("select * from proformas");
$sth->execute();
while ( my $ref = $sth->fetchrow_hashref() ) {
	my ( $id, $date, $visible, $mutable );

	$id      = $ref->{id};
	$date    = $ref->{date};
	$visible = ( $ref->{visible} eq "Y" );
	$mutable = ( $ref->{mutable} eq "Y" );

	my $p = new Proforma( undef, -1, $date, $visible, $mutable );
	$p->setId($id);

	push( @proformas, $p );
}
$sth->finish();

@proformas =
  sort { return dateOK( $b->date() ) <=> dateOK( $a->date() ); } @proformas;

foreach my $proforma (@proformas) {
	if ( $proforma->visible() ) {
		my $sth = $dbh->prepare( "select * from reports where uid=? and proforma_id=?");
		$sth->execute($user->uid(), $proforma->id());

		if ( my $ref = $sth->fetchrow_hashref() ) {
			my $entry = {
				title => escapeHTML(dateToTitle($proforma->date())),
				body  => formatForWeb(escapeHTML($ref->{body})),
			};

			if ( $proforma->mutable() ) {
				$entry->{editLink} =
				  "manageReport.pl?action=modify&id=" . $ref->{id};
			}

			push( @{$vars->{list}}, $entry );
		} elsif ($proforma->mutable()) {
			my $entry = {
				title => escapeHTML(dateToTitle($proforma->date())),
			};

			if ( $proforma->mutable() ) {
				$entry->{createLink} = "manageReport.pl?pid=" . $proforma->id();
			}

			push( @{$vars->{list}}, $entry );

		} else {
			my $entry = {
				title => escapeHTML(dateToTitle($proforma->date())),
				body => '<em>No survey entered</em>',
			};

			push( @{$vars->{list}}, $entry );
		};
	}
}

$vars->{admin} = 1 if ($user->admin());

my $template = new Template();
$template->process('tt/show_main_list.tt', $vars) || die "Template process failed: ", $template->error(), "\n";
