#!/usr/bin/perl
#
# $Id: Integro.pl,v 1.48 2005/11/07 16:36:06 ddoughty Exp $
#
# Source File: Integro.pl
# Get config
use FileHandle;
use Time::Local;
use Data::Dumper;
use IntegroLib;
require 'sitecfg.pl';
require 'testlib.pl';
require 'tstatlib.pl';
use strict;
use vars qw(%FORM %SESSION %CLIENT %TEST_SESSION %SUBTEST_QUESTIONS %TEST
	    %SUBTEST_SUMMARY %CANDIDATE %SUBTEST_ANSWERS %SYSTEM %REPORT
	    %SUBTEST_RESPONSES);
use vars qw($testcomplete $cgiroot $pathsep $dataroot );
&app_initialize;
$FORM{"idlist"} =~ tr/\000/,/ ; # Change separator for multiple values from NULL to comma.  HBI
&LanguageSupportInit();
#print STDERR Dumper(\%SESSION);
&get_client_profile($SESSION{'clid'});
&get_test_profile($CLIENT{'clid'}, $FORM{'tstid'});
# Make sure we have a valid session, and exit if we don't
if (not &get_session($FORM{'tid'})) {
    exit(0);
}
# Get the group filters, if any
my ($idlist,$groups);
if (exists $FORM{'grouping'} and $FORM{'grouping'} eq 'subset') {
    my @tmp = split(/,/,$FORM{'idlist'});
    @{$groups}{@tmp} = @tmp;
    $idlist = &getIdlist($CLIENT{'clid'},$FORM{'idlist'});
}
# Get the time stamp style
my $timestamp;
if ($FORM{'timestamp'} eq 'currenttime') {
    $timestamp = scalar(localtime(time));
} elsif ($FORM{"timestamp"} eq 'custom' and $FORM{'customtime'} ne '') {
    $timestamp = $FORM{'customtime'};
} elsif ($FORM{'timestamp'} eq 'mostrecent' and $FORM{'tstid'}) {
    my $file = join($pathsep,$testcomplete,"$CLIENT{'clid'}.$FORM{'tstid'}.history");
    my $fh = new FileHandle;
    if ($fh->open($file)) {
	my @history = map([split(/(?:<<>>|&)/,$_,4)],<$fh>);
	#print "
".Dumper(\@history)."
";
	if (defined $idlist) {
	    foreach (reverse @history) {
		if (exists $idlist->{$_->[2]}) {
		    $timestamp = scalar(localtime(toGMSeconds($_->[0])));
		    last;
		}
	    }
	} else {
	    $timestamp = scalar(localtime(toGMSeconds($history[$#history]->[0])));
	}
    } else {
	print STDERR "Could not open $file in Integro.pl\n";
    }
}
if (defined $timestamp) {
    $timestamp = "$timestamp
\n";
} else {
    $timestamp = "
\n";
}
# Generate the reports
if ($FORM{'reportname'} eq 'commeffect') {
    &CommEffectReport($idlist, $groups, $timestamp);
} elsif ($FORM{'reportname'} eq 'commeffectsummary') {
    &CommEffectSummary($idlist, $groups, $timestamp);
} elsif ($FORM{'reportname'} eq 'trustlevel') {
    &TrustLevelReport($idlist, $groups, $timestamp);
} elsif ($FORM{'reportname'} eq 'trustlevelsummary') {
    &TrustLevelSummary($idlist, $groups, $timestamp);
} elsif ($FORM{'reportname'} eq 'values') {
    &ValuesReport($idlist, $groups, $timestamp);
} elsif ($FORM{'reportname'} eq 'valuessummary') {
    &ValuesSummary($idlist, $groups, $timestamp);
} elsif ($FORM{'reportname'} eq 'comments') {
    &CommentsReport($idlist, $timestamp);
} elsif ($FORM{'reportname'} eq 'people') {
    &KindsOfPeopleReport($idlist, $groups, $timestamp);
} elsif ($FORM{'reportname'} eq 'peoplesummary') {
    &KindsOfPeopleSummary($idlist, $groups, $timestamp);
} else {
    &ReportChooser();
}
# There should only be function definitions beyond this point.
exit(0);
sub HTMLHeader {
    return "\n\n$_[0]\n".
	"\n\n".
	"\n";
}
sub HTMLHeaderPlain {
    return "\n\n$_[0]\n".
	"\n\n".
	"\n";
}
sub HTMLFooter {
    return "
Copyright (c) 2006, Integro Leadership Institute\n\n";
}
sub ReportChooser {
    # Links w/javascript for chosing report
    # Radio button to choose between all and select group(s)
    # Menu box to chose one or more groups
    my $groups = &getGroups($CLIENT{'clid'});
    my $js = "function parmsIntegro(oform,rpt) {\n\t".
	"oform.reportname.value=rpt;\n\t".
	"oform.action='/cgi-bin/creports.pl';\n\t".
	"oform.submit();\n};\n";
    $js .= "\nfunction commIntegro(oform) {\n\t".
	"oform.rptid.value='ACT-C-004';\n\t".
	"oform.rptdesc.value='Test Statistics by Test'\n\t".
	"oform.action='/cgi-bin/teststats.pl';\n\t".
	"oform.submit();\n};\n";
    my $orgname = $CLIENT{'clnmc'};
    my ($tstid) = grep((/(SAS01\S*)&/ && ($_=$1)),get_data("tests.$CLIENT{'clid'}"));
    if (not $tstid) {
	print HTMLHeader("Error! No Strategic Alignment Survey Found.");
	print "Error! No Strategic Alignment Survey Found.
\n";
	print HTMLFooter();
    }
    #print STDERR get_data("tests.$CLIENT{'clid'}");
    #print STDERR "Test ID = $tstid\n"; 
    print HTMLHeader("Integro Learning Custom Reports",$js);
    print "";
    print HTMLFooter();
}
# Also known as the Group Alignment report
sub CommEffectReport {
    my ($idlist,$groups,$timestamp) = @_;
    my $data = &CommEffectData($CLIENT{'clid'},$TEST{'id'},$idlist,$groups);
    my $claritysum = $data->{'organization'}->{'claritysum'};
    my $approvalsum = $data->{'organization'}->{'approvalsum'};
    my $histograms = $data->{'organization'}->{'histogram'};
    print HTMLHeaderPlain("Section 4 - Group Alignment Report");
    print "Section 4 - Group Alignment Report
\n";
    print "The degree to which Employees are Aligned with the Organization
\n";
    print "$FORM{'orgname'}
\n";
    if (defined $idlist) {
	my $groups = getGroups($CLIENT{'clid'});
	print "Groups: "
	    .join(", ",map($groups->{$_}->{'grpnme'},split(/,/,$FORM{'idlist'})))."
\n";
    } else {
	print "Organization-wide Report
\n";
    }
    print $timestamp;
    print "|  | Very Unclear | ".
	" | Moderately Unclear |  | Moderately Clear".
	" |  | Very Clear | Group Clarity".
	" | Group Approval | 
|---|
\n";
    # fill in the rows
    my $overall = {'clarity' => 0, 'approval' => 0};
    foreach my $row (qw(Purpose Values Vision Goals Procedures Roles)) {
	print "| $row";
	for my $i (0..6) {
	    print " | ";
	    if ($histograms->{$row}->{'Clarity'}->[$i]) {
		if ($histograms->{$row}->{'Approval'}->[$i]->[2]) {
		    print " ";
	}
	printf " ".
			"$histograms->{$row}->{'Approval'}->[$i]->[2] ";
		}
		if ($histograms->{$row}->{'Approval'}->[$i]->[1]) {
		    print "
  ".
			"$histograms->{$row}->{'Approval'}->[$i]->[1] ";
		}
		if ($histograms->{$row}->{'Approval'}->[$i]->[0]) {
		    print "
  ".
			"$histograms->{$row}->{'Approval'}->[$i]->[0]";
		}
	    } else {
		print " ";
	    }
	    print " | %.1f %%\n", $claritysum->{$row}->{'value'};
	printf " | %.1f %%\n", $approvalsum->{$row}->{'value'};
	print " | 
|---|
\n";
    }
    print "
\nPosition = Group Clarity
\nCountenance = Personal Approval
\n";
    print "Overall Group Alignment\n";
    printf "| Clarity | %.1f %% | 
|---|
\n", $data->{'organization'}->{'overallclarity'};
    printf "| Approval | %.1f %% | 
|---|
\n", $data->{'organization'}->{'overallapproval'};
    print "
\n";
    print HTMLFooter();
}
sub CommEffectSummary {
    my ($idlist,$groups,$timestamp) = @_;
    my $data = &CommEffectData($CLIENT{'clid'},$TEST{'id'},$idlist,$groups);
    $groups = getGroups($CLIENT{'clid'});
    print HTMLHeaderPlain("Section 4 - Group Alignment Summary");
    print "Section 4 - Group Alignment Summary
\n";
    print "The degree to which Employees are Aligned with the Organization
\n";
    print "$FORM{'orgname'}
\n";
    if (defined $idlist) {
	my $groups = getGroups($CLIENT{'clid'});
	print "Summary for Groups: "
	    .join(", ",map($groups->{$_}->{'grpnme'},split(/,/,$FORM{'idlist'})))."
\n";
    } else {
	print "Organization-wide Report
\n";
    }
    print $timestamp;
    print "\n";
    print "|  | Clarity | Approval | 
|---|
\n";
    print "| Overall";
    printf " | %.1f %%",$data->{'organization'}->{'overallclarity'};
    printf " | %.1f %% | 
\n", $data->{'organization'}->{'overallapproval'};
    if (exists $data->{'groups'}) {
	print "| Group Breakdown | 
|---|
\n";
	print "| Group | Clarity | Approval | 
|---|
\n";
	foreach my $grp (sort keys %{$data->{'groups'}}) {
	    print "| $groups->{$grp}->{'grpnme'}";
	    printf " | %.1f %%", $data->{'groups'}->{$grp}->{'overallclarity'};
	    printf " | %.1f %% | 
\n", $data->{'groups'}->{$grp}->{'overallapproval'};
	}
    }
    print "
\n";
    print HTMLFooter();
}
sub TrustLevelReport {
    my ($idlist,$groups,$timestamp) = @_;
    my $data = TrustLevelData($CLIENT{'clid'},$TEST{'id'},$idlist,$groups);
    my $histograms = $data->{'organization'}->{'histogram'};
    my $trust = $data->{'organization'}->{'trust'};
    print HTMLHeaderPlain("Section 2 - Group Trust Level Report");
    print "Section 2 - Group Trust Level Report
\n";
    print "The level of Trust Building behaviors
\n";
    print "$FORM{'orgname'}
\n";
    if (defined $idlist) {
	my $groups = getGroups($CLIENT{'clid'});
	print "Groups: "
	    .join(", ",map($groups->{$_}->{'grpnme'},split(/,/,$FORM{'idlist'})))."
\n";
    } else {
	print "Organization-wide Report
\n";
    }
    print $timestamp;
    print "|  |  | Group Trust Level | 
|---|
\n";
    my $baseurl = "/cgi-bin/bargraph.pl?labels=Low::::Medium::::High&title=Trust%20Level&ylabel=Respondents";
    $baseurl .= "&xdim=500&ydim=150";
    foreach my $row (qw(Congruence Openness Acceptance Reliability)) {
	print "| $row";
	print " | ";
	printf " {$row}})."\"> | %.1f%% | 
|---|
\n", $trust->{$row}->{'value'};
    }
    print "
\n";
    printf "Overall Group Trust Level = %.1f %%.
\n",$data->{'organization'}->{'overalltrust'};
    print HTMLFooter();
}
sub TrustLevelSummary {
    my ($idlist,$groups,$timestamp) = @_;
    my $data = TrustLevelData($CLIENT{'clid'},$TEST{'id'},$idlist,$groups);
    $groups = getGroups($CLIENT{'clid'});
    print HTMLHeaderPlain("Section 2 - Group Trust Level Summary");
    print "Section 2 - Group Trust Level Summary
\n";
    print "The level of Trust Building behaviors
\n";
    print "$FORM{'orgname'}
\n";
    if (defined $idlist) {
	my $groups = getGroups($CLIENT{'clid'});
	print "Summary for Groups: "
	    .join(", ",map($groups->{$_}->{'grpnme'},split(/,/,$FORM{'idlist'})))."
\n";
    } else {
	print "Organization-wide Summary
\n";
    }
    print $timestamp;
    print "\n";
    print "|  | Group Trust Level | 
|---|
\n";
    print "| Overall";
    printf " | %.1f %% | 
\n", $data->{'organization'}->{'overalltrust'};
    if (exists $data->{'groups'}) {
	print "| Group Breakdown | 
|---|
\n";
	print "| Group | Group Trust Level | 
|---|
\n";
	foreach my $grp (sort keys %{$data->{'groups'}}) {
	    print "| $groups->{$grp}->{'grpnme'}";
	    printf " | %.1f %% | 
\n", $data->{'groups'}->{$grp}->{'overalltrust'};
	}
    }
    print "
\n";
    print HTMLFooter();
}
# Aka Gap Analysis
sub ValuesReport {
    my ($idlist,$groups,$timestamp) = @_;
    my $data = &ValuesData($CLIENT{'clid'},$TEST{'id'},$idlist,$groups);
    print HTMLHeaderPlain("Section 3 - Values That Build Trust");
    print "Section 3 - Values That Build Trust
\n";
    print "The gap between Employee Expectation and the degree to 
which the Organization operates by these Values
\n";
    print "$FORM{'orgname'}
\n";
    if (defined $idlist) {
	my $groups = getGroups($CLIENT{'clid'});
	print "Groups: "
	    .join(", ",map($groups->{$_}->{'grpnme'},split(/,/,$FORM{'idlist'})))."
\n";
    } else {
	print "Organization-wide Report
\n";
    }
    $timestamp;
    printf "| Your Trust Values Gap Score is %.1f",$data->{'organization'}->{'gap'};
    #print " World Class Standard ?
 International Benchmark ?
 ";
    print "
 | 
\n";
    print "\n";
    print "The graphs below show the Personal Importance and Perceptions of Work Performance".
	" for each of the eight values.";
    print "|  | Gap | 
|---|
\n";
    my $baseurl = "/cgi-bin/bargraph.pl?labels=Personal%20Importance:Work%20Performance".
	"&xdim=500&ydim=60&hbar=1&ymax=11&ymin=0&yticknum=11";
    foreach ('Straightforwardness', 'Honesty', 'Receptivity', 'Disclosure', 'Respect',
	     'Recognition', 'Seeks Excellence', 'Keeps Commitments') {
	my $url;
	my $pinum = (int(10*$data->{'organization'}->{$_}->{'Personal Importance'}+0.5)/10);
	my $wpnum = (int(10*$data->{'organization'}->{$_}->{'Work Performance'}+0.5)/10);
	my $diff = $pinum - $wpnum;
	$diff = sprintf("%1.1f", $diff);
	$url = $baseurl."&values=".$pinum.":";
	$url = $url."&values2=:".$wpnum;
	print "| $_ | 
|---|
\n";
	#print "|  | $data->{'organization'}->{$_}->{'count'} | 
\n";
	print "|  | $diff | 
\n";
    }
    print "
\n";
    print HTMLFooter();
}
sub ValuesSummary {
    my ($idlist,$groups,$timestamp) = @_;
    my $data = &ValuesData($CLIENT{'clid'},$TEST{'id'},$idlist,$groups);
    $groups = getGroups($CLIENT{'clid'});
    print HTMLHeaderPlain("Section 3 - Values That Build Trust Summary");
    print "
Section 3 - Values That Build Trust Summary
\n";
    print "The gap between Employee Expectation and the degree to 
which the Organization operates by these Values
\n";
    print "$FORM{'orgname'}
\n";
    if (defined $idlist) {
	my $groups = getGroups($CLIENT{'clid'});
	print "Summary for Groups: "
	    .join(", ",map($groups->{$_}->{'grpnme'},split(/,/,$FORM{'idlist'})))."
\n";
    } else {
	print "Organization-wide Report
\n";
    }
    print $timestamp;
    print "\n";
    print "|  | Trust Values Gap | 
|---|
\n";
    print "| Overall";
    printf " | %.1f | 
\n", $data->{'organization'}->{'gap'};
    if (exists $data->{'groups'}) {
	print "| Group Breakdown | 
|---|
\n";
	print "| Group | Trust Values Gap | 
|---|
\n";
	foreach my $grp (sort keys %{$data->{'groups'}}) {
	    print "| $groups->{$grp}->{'grpnme'}";
	    printf " | %.1f | 
\n", $data->{'groups'}->{$grp}->{'gap'};
	}
    }
    print "
\n";
    print HTMLFooter();
}
sub KindsOfPeopleReport {
    my ($idlist,$groups,$timestamp) = @_;
    my $data = KindsOfPeopleData($CLIENT{'clid'},$TEST{'id'},$idlist,$groups);
    print HTMLHeaderPlain("Section 1 - Kinds of People");
    print "Section 1 - Kinds of People
\n";
    print "Employee behavior perceived by coworkers
\n";
    print "$FORM{'orgname'}
\n";
    if (defined $idlist) {
	my $groups = getGroups($CLIENT{'clid'});
	print "Groups: "
	    .join(", ",map($groups->{$_}->{'grpnme'},split(/,/,$FORM{'idlist'})))."
\n";
    } else {
	print "Organization-wide Report
\n";
    }
    print $timestamp;
    print "";
    my $url;
    if (exists $data->{'self'}) {
	my @self = @{$data->{'self'}}{'Rebellious','Compliant','Self-Directed'};
	$url = "/cgi-bin/piechart.pl?title=Self%20Perception&values=".
	    join(':',map(int($_+0.5),@self)).
	    "&labels=Rebellious:Compliant:Self-Directed";
	print "|  | 
\n";
    }
    if (exists $data->{'organization'}) {
	my @other = @{$data->{'organization'}}{'Rebellious','Compliant','Self-Directed'};
	$url = "/cgi-bin/piechart.pl?title=Perception%20of%20Others&values=".
	    join(':',map(int(10*$_+0.5)/10,@other)).
	    "&labels=Rebellious:Compliant:Self-Directed";
	print "|  | 
\n";
	print "
\n";
	print "Overall Group Values\n";
	foreach ('Rebellious','Compliant','Self-Directed') {
	    printf "| $_ | %.1f %% | 
|---|
\n", $data->{'organization'}->{$_};
	}
	print "
\n";
    } else {
	print "No valid Data
\n";
    }
    #print "".Dumper($data)."
\n";
    print HTMLFooter();
}
sub KindsOfPeopleSummary {
    my ($idlist,$groups,$timestamp) = @_;
    my $data = KindsOfPeopleData($CLIENT{'clid'},$TEST{'id'},$idlist,$groups);
    $groups = getGroups($CLIENT{'clid'});
    print HTMLHeaderPlain("Section 1 - Kinds of People Summary");
    print "Section 1 - Kinds of People Summary
\n";
    print "Employee behavior perceived by coworkers
\n";
    print "$FORM{'orgname'}
\n";
    if (defined $idlist) {
	my $groups = getGroups($CLIENT{'clid'});
	print "Summary for Groups: "
	    .join(", ",map($groups->{$_}->{'grpnme'},split(/,/,$FORM{'idlist'})))."
\n";
    } else {
	print "Organization-wide Report
\n";
    }
    print $timestamp;
    print "\n";
    print "|  | Rebellious | Compliant | Self-Directed | 
|---|
\n";
    print "| Overall";
    printf " | %.1f %%", $data->{'organization'}->{'Rebellious'};
    printf " | %.1f %%", $data->{'organization'}->{'Compliant'};
    printf " | %.1f %% | 
\n", $data->{'organization'}->{'Self-Directed'};
    if (exists $data->{'groups'}) {
	print "| Group Breakdown | 
|---|
\n";
	print "| Group | Rebellious | Compliant | Self-Directed | 
|---|
\n";
	foreach my $grp (sort keys %{$data->{'groups'}}) {
	    print "| $groups->{$grp}->{'grpnme'}";
	    printf " | %.1f %%\n", $data->{'groups'}->{$grp}->{'Rebellious'};
	    printf " | %.1f %%\n", $data->{'groups'}->{$grp}->{'Compliant'};
	    printf " | %.1f %% | 
\n", $data->{'groups'}->{$grp}->{'Self-Directed'};
	}
    }
    print "
\n";
    print HTMLFooter();
    
}
sub CommentsReport {
    my ($idlist)  = @_;
    my @filelist = &get_test_result_files($testcomplete, $CLIENT{'clid'},$TEST{'id'});
    my @comments;
    for (my $i=0; $i<=59; $i++) {$comments[$i] = [];}
    my @questions = map([split(/&/,$_)],&get_question_list($TEST{'id'},$CLIENT{'clid'}));
    foreach (@questions) {$_->[4] =~ s/:::.*$//;}
    foreach my $file (@filelist) {
	my $user = $file;
	$user =~ s/.$TEST{'id'}$//;
	$user =~ s/^$CLIENT{'clid'}.//;
	if (defined $idlist and not $idlist->{$user}) {
	    next;
	}
	my ($answers,$usercomm) = &get_survey_results( $CLIENT{'clid'}, $user, $TEST{'id'});
	for (my $i=1; $i<=58; $i++) {
	    if ($usercomm->[$i] == -1) {
		$comments[$i] = -1;
	    } elsif ($usercomm->[$i]) {
		push @{$comments[$i]},$usercomm->[$i];
	    }
	}
	if ($answers->[59]) {
	    push @{$comments[59]},$answers->[59];
	}
    }
    print HTMLHeaderPlain("Comments Report");
    print "Comments Report
\n";
    print "$FORM{'orgname'}
\n";
    if (defined $idlist) {
	my $groups = getGroups($CLIENT{'clid'});
	print "Groups: "
	    .join(", ",map($groups->{$_}->{'grpnme'},split(/,/,$FORM{'idlist'})))."
\n";
    } else {
	print "Organization-wide Report
\n";
    }
    print $timestamp;
    print "\n";
    for (my $i=1; $i <=59; $i++) {
	if ($comments[$i] == -1) {
	    # inactive question
	    next;
	}
	print "
\n";
	print "$questions[$i]->[0] - $questions[$i]->[4]\n";
	if (@{$comments[$i]}) {
	    print "
\n";
	    foreach (@{$comments[$i]}) {
		print "- $_\n";
	    }
	    print "
\n";
	} else {
	    print "\n";
	}
	print "\n";
    }
    print "
\n";
    #print "".Dumper(\@questions,\@comments)."
\n";
    print "".HTMLFooter();
}