#!/usr/bin/perl
#  Copyright 2001-2021 Leslie Richardson

#  This file is part of Open Admin for Schools.

#  Open Admin for Schools is free software; you can redistribute it 
#  and/or modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2 of 
#  the License, or (at your option) any later version.

my %lex = ('Report' => 'Report',
	   'Audit' => 'Audit',
	   'Main' => 'Main',
	   'Student' => 'Student',
	   'Name' => 'Name',
	   'Room' => 'Room',
	   'Error' => 'Error',
	   'Continue' => 'Continue',
	   'Select' => 'Select',
	   'Blank=All' => 'Blank=All',
	   'No Records Found' => 'No Records Found',

	   'Script Name' => 'Script Name',
	   'User' => 'User',
	   'Script' => 'Script',
	   'Table' => 'Table',
	   'Date' => 'Date',
	   'Difference' => 'Difference',
	   'Add' => 'Add',
	   'Delete' => 'Delete',
	   'Select by' => 'Select by',

	   );

my $self = 'auditview.pl';

use DBI;
use CGI;



# Read config variables
eval require "../etc/admin.conf";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@\n";
}

my $q = new CGI;
my %arr = $q->Vars;
print $q->header( -charset, $charset );

my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);
$dbh->{mysql_enable_utf8} = 1;


# calc current date
my @tim = localtime(time);
my $year = @tim[5] + 1900;
my $month = @tim[4] + 1;
my $day = @tim[3];
my $currdate = "$year-$month-$day";


# HTML Start
my $title = "$lex{Audit} $lex{Report}";
print qq{$doctype\n<html><head><title>$title</title>
<link rel="stylesheet" href="$css" type="text/css">\n};

if ( not $arr{page} ) {
    print qq{<link rel="stylesheet" type="text/css" media="all" };
    print qq{href="/js/calendar-blue.css" title="blue">\n};
    print qq{<script type="text/javascript" src="/js/calendar.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/lang/calendar-en.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/calendar-setup.js"></script>\n};
}

print qq{$chartype\n</head><body>\n};
print qq{[ <a href="$homepage">$lex{Main}</a> ]\n};

print qq{<h1>$title</h1>\n};


if ( not $arr{page} ) {
    showStartPage();

} else {
    delete $arr{page};
    showReport();
}



#-------------
sub showReport {
#-------------

    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n"; }

    my $select;
    if ( $arr{select} ) { # we have a selection
	if ( $arr{mode} eq 'homeroom' ) {
	    my $grp = $dbh->quote( $arr{select} );
	    $select = "where homeroom = $grp";
	} elsif ( $arr{mode} eq 'grade' ) {
	    my $grp = $dbh->quote( $arr{select} );
	    $select = "where grade = $grp";
	}
    }


    my $sortorder;


    $sth = $dbh->prepare("select * from audit $select order by tstamp desc");
    $sth->execute;
    if ( $DBI::errstr ) {print $DBI::errstr; die $DBI::errstr; }


    my $first = 1;

    while ( my $aref = $sth->fetchrow_hashref ) {

	my %a = %$aref;

	if ( $first ) { # print heading.
	    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
	    print qq{<tr><th>$lex{User}</th><th>$lex{Script}</th><th>$lex{Table} (id)</th>\n};
	    print qq{<th>$lex{Date}</th><th>$lex{Difference}</th></tr>\n};
	    $first = 0;
	}

	print qq{<tr><td>$a{userid}<br>$a{ipaddr}</td><td>$a{scriptname}</td>};
	print qq{<td>$a{tablename} };
	if ( $a{tableid} ) { print qq{ ($a{tableid}) } };
	print qq{</td>\n};
	print qq{<td>$a{tstamp}</td>};

	my $diff;
	my $blank = qq{<span style="color:red;">Blank</span>};
	
	if ( not $a{startval} and $a{endval} ) { # A Record was added
	    $diff = qq{<div style="font-weight:bold;">Add Record</div>\n};
	    eval $a{endval};
	    if ( $@ ) {
		print $lex{Error}. " $@<br>\n";
		die $lex{Error}. " $@\n";
	    }
	    my $count;
	    foreach my $key ( sort keys %endval ) {
		if ( $endval{$key} ) {
		    $diff .= qq{<div><b>$key</b>: $endval{$key}</div>\n};
		    $count++;
		}
		if ($count > 6 ) { last; }
	    }


	} elsif ( $a{startval} and not $a{endval} ) { # A Record was deleted.
	    $diff = qq{<div style="font-weight:bold;">Delete Record</div>\n};
	    
	    eval $a{startval};
	    if ( $@ ) {
		print $lex{Error}. " $@<br>\n";
		die $lex{Error}. " $@\n";
	    }
	    
	    if ( $startval{lastname} ) {
		$diff .= qq{<div><b>Lastname</b>: $startval{lastname}</div>\n};
		delete $startval{lastname};
	    }
	    if ( $startval{firstname} ) {
		$diff .= qq{<div><b>Firstname</b>: $startval{firstname}</div>\n};
		delete $startval{firstname}
	    }
	    
	    my $count;
	    foreach my $key ( sort keys %startval ) {
		if ( $key eq 'id' or $key eq 'studid' ) { next; }
		if ( $startval{$key} ) {
		    $diff .= qq{<div><b>$key</b>: $startval{$key}</div>\n};
		    $count++;
		}
		if ( $count > 5 ) { last; }
	    }

	} else { # figure out the diff by analysis
	    $diff = qq{<div style="font-weight:bold;">Edit Record</div>\n};
	    
	    # eval both into active hashes: %startval, %endval
	    eval $a{startval};
	    if ( $@ ) {
		print $lex{Error}. " $@<br>\n";
		die $lex{Error}. " $@\n";
	    }

	    eval $a{endval};
	    if ( $@ ) {
		print $lex{Error}. " $@<br>\n";
		die $lex{Error}. " $@\n";
	    }

	    foreach my $key ( keys %startval ) {
		if ( $key eq 'id' or $key eq 'studid' ) { next; }

		if ( $startval{$key} ne $endval{$key} and exists $endval{$key} ) {
		    if ( not $startval{$key} ) { $startval{$key} = $blank; }
		    if ( not $endval{$key} ) { $endval{$key} = $blank; }
		    $diff .= "<div><b>$key</b>: $startval{$key} => $endval{$key}</div>";
		}
	    }

	}

	print qq{<td>$diff</td></tr>\n};

    } # audit record loop


    if ( $first ) {
	print qq{<h3>$lex{'No Records Found'}</h3>\n};

    } else {
	print qq{</table>\n};
    }

    print qq{</body><html>\n};
    exit;


} # end of showReport



#----------------
sub showStartPage {
#----------------


    # Get Script Names
    my @names;
    my $sth = $dbh->prepare("select distinct scriptname from audit 
			    where scriptname is not null order by scriptname");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $name  = $sth->fetchrow ) {
	push @names, $name;
    }

    # print qq{<h3>Script Names</h3>\n};
    # foreach my $v ( @names ) { print qq{$v<br>\n}; }

    # Select by Script Name
    # Form Start
    print qq{<form action="$self" method="post"> \n};
    print qq{<input type="hidden" name="page" value="1">\n};

    print qq{<h3>$lex{'Select by'} $lex{'Script Name'}</h3>\n};
    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};


    print qq{<tr><td class="ra">$lex{'Script Name'}</td>};
    print qq{<td><select name="scriptname"><option></option>};

    foreach my $name ( @names ) {
	print qq{<option>$name</option>\n};
    }
    print qq{</select></td></tr>\n\n};
    print qq{<tr><td></td><td class="la"><input type="submit" value="$lex{Continue}"></td></tr>\n};
    print qq{</table></form><p></p>\n};



    # Select by Date Range.
    # Form Start
    print qq{<form action="$self" method="post"> \n};
    print qq{<input type="hidden" name="page" value="1">\n};

    print qq{<h3>$lex{'Select by'} $lex{Date}</h3>\n};
    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};

    print qq{<tr><td class="ra">$lex{'Start Date'}</td>\n};
    print qq{<td class="la"><input type="text" name="startdate" id="sdate" };
    print qq{size="10" value="$schoolstart">\n};
    print qq{<button type="reset" id="start_trigger">...</button></td></tr>\n};

    print qq{<tr><td class="ra">$lex{'End Date'}</td>\n};
    print qq{<td class="la"><input type="text" name="enddate" id="edate" };
    print qq{size="10" value="$currdate">\n};
    print qq{<button type="reset" id="end_trigger">...</button></td></tr>\n};

    print qq{<tr><td></td><td class="la"><input type="submit" value="$lex{Continue}"></td></tr>\n};
    print qq{</table></form>\n};

    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :    "sdate", 
        ifFormat       :    "%Y-%m-%d",
        button         :    "start_trigger",
        singleClick    :    false,
        step           :    1
    });

    Calendar.setup({
        inputField     :    "edate",
        ifFormat       :    "%Y-%m-%d",
        button         :    "end_trigger",
        singleClick    :    false,
        step           :    1
    });
   </script>\n};

    print qq{</body></html>\n};

    exit;

} # end of showStartPage

