#!/usr/bin/perl
#  Copyright 2001-2024 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 = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Continue' => 'Continue',
	   'Select' => 'Select',
	   'Student' => 'Student',
	   'Homeroom' => 'Homeroom',
	   'Grade' => 'Grade',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',

	   );

use DBI;
use CGI;
use Cwd;

my $self = 'wrView.pl';
#my $editscript = 'wrEdit.pl'; # added directly
#my $deletescript = 'wrDelete.pl';

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


# Get current dir so know what CSS to display and shift settings.
if ( getcwd() !~ /tcgi/ ) { # we are in cgi
    $tchcss = $css;
    $tchpage = $homepage;
    $tchdownloaddir = $downloaddir;
    $tchwebdownloaddir = $webdownloaddir;
}


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

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


# Page Header
my $title = qq{View Writing Scores};
print qq{$doctype\n<html><head><title>$title</title>\n}; 
print qq{<link rel="stylesheet" href="$tchcss" type="text/css">\n};

if ( not $arr{page} ) { # calendar popup.
    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 style="padding:1em 2em;">\n};

print qq{[ <a href="$tchpage">$lex{Main}</a> ]\n};
print qq{<h1>$title</h1>\n};


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

} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    showScores();
}


#----------
sub fmtDate {
#----------

    my ( $year, $mon, $day ) = split /-/, shift;
    return "$year-$s_month[$mon]-$day";
}



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

    my @tim = localtime(time);
    my $year = $tim[5] + 1900;
    my $month = $tim[4] + 1;
    my $currdate = "$year-$month-$tim[3]";
    
    
    # Find by Student Group
    my (@homerooms, @grades );
    my $sth = $dbh->prepare("select distinct homeroom from student 
			    where homeroom is not NULL and homeroom != ''");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $hr = $sth->fetchrow ) {
	push @homerooms, $hr;
    }

    $sth = $dbh->prepare("select distinct grade from student 
			 where grade is not NULL and grade != ''");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $gr = $sth->fetchrow ) {
	push @grades, $gr;
    }
    @grades = sort {$a <=> $b} @grades;

    # Form start
    print qq{<form action="$self" method="post"> \n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<table cellpadding="3" cellspacing="0" border="0" };
    print qq{style="padding:0.5em;border:1px solid gray;float:left;">\n};

    # Select Grade
    print qq{<tr><td class="bra">$lex{Select} $lex{Grade}</td>\n};
    print qq{<td><select name="grade"><option></option>\n};
    foreach my $grade ( @grades ) {
	print qq{<option>$grade</option>\n};
    }
    print qq{</select></td></tr>\n};

    print qq{<tr><td colspan="2" class="cn">OR</td></tr>\n};


    # Select Homeroom
    my $sth = $dbh->prepare("select lastname, firstname from staff s, staff_multi sm 
      where s.userid = sm.userid and field_name = 'homeroom' and field_value = ?");

    print qq{<tr><td class="bra">$lex{Select} $lex{Homeroom}</td>\n};
    print qq{<td class="la"><select name="homeroom"><option></option>\n};
    foreach my $hr ( @homerooms ) {
	$sth->execute($hr);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname) = $sth->fetchrow;
	my $hrname = $hr;
	if ( $lastname ) { $hrname = "$hr - $firstname $lastname"; }

	print qq{<option value="$hr">$hrname</option>\n};
    }
    print qq{</select></td></tr>\n};

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

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

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

    print qq{</table></form></div>\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};


    
    # Find existing Records
    my $sth = $dbh->prepare("select distinct tgrade, count(*) from write_scores
       where to_days(tdate) > to_days('$schoolstart') and 
       to_days(tdate) < to_days('$schoolend') group by tgrade");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

    my $first = 1;
    while ( my ($grade,$count) = $sth->fetchrow ) {
	if ( $first ) {

	    print qq{<table cellpadding="3" cellspacing="0" border="1" style="float:left;margin:1em;">};
	    # print qq{<caption>School Year: $schoolstart to $schoolend</caption>\n};
	    print qq{<caption>Existing Records</caption>\n};
	    print qq{<tr><th>Grades</th><th>Rec Count</th></tr>\n};
	    $first = 0;
	}
	print qq{<tr><td>$grade</td><td>$count</td></tr>\n};
    }
    if ( not $first ) { # close table
	print qq{</table>\n};
    }

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

    exit;

} # end of showStartPage



#--------------
sub showScores {
#--------------

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

    # Grade or Homeroom
    my ($select, $value, $heading);
    $heading = 'All Students';
    if ( $arr{grade} ) {
	$select = 'where grade = ?';
	$value = $arr{grade};
	$heading = qq{Grade $arr{grade}};
	
    } elsif ( $arr{homeroom} ) {
	$select = 'where homeroom = ?';
	$value = $arr{homeroom};
	$heading = qq{Homeroom $arr{homerom}};
    }

    # Get Name, Student Number
    my $sth = $dbh->prepare("select lastname, firstname, studnum from student $select
       order by lastname, firstname");

    if ( $select ) {
	$sth->execute( $value );
    } else {
	$sth->execute;
    }
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

    
    print qq{<table cellpadding="3" cellspacing="0" border="0" };
    print qq{style="border:1px solid gray;padding:0.5em;margin:0.5em;">\n};
    print qq{<caption>$heading</caption>\n};


    my $sth1 = $dbh->prepare("select * from write_scores where studnum = ? and
      to_days(tdate) >= to_days( '$arr{startdate}' ) 
      and to_days(tdate) <= to_days( '$arr{enddate}')");
    
    print qq{<tr><th>$lex{Student}</th><th>Scores</th><th>Change</th></tr>\n};

    while ( my ( $lastname, $firstname, $studnum ) = $sth->fetchrow ) {

	print qq{<tr><td colspan="3" style="background-color:#DDD;">};
	print qq{<b>$lastname</b>, $firstname ($studnum)</td></tr>\n};
	
	# Get Scores
	$sth1->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $ref = $sth1->fetchrow_hashref ) {
	    my %r = %$ref; # score record for this student.
	    print qq{<tr><td>$r{tdate}</td><td>$r{score}</td>};
	    print qq{<td><form action="./wrEdit.pl" method="post" style="display:inline;" target="_blank">\n};
	    print qq{<input type="hidden" name="id" value="$r{id}">\n};
	    print qq{<input type="submit" value="Edit"></form>\n};

	    print qq{<form action="./wrDelete.pl" method="post" style="display:inline;" target="_blank">\n};
	    print qq{<input type="hidden" name="id" value="$r{id}">\n};
	    print qq{<input type="submit" value="Delete"></form>\n};

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

    print qq{</table>\n};

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

    exit;

} # end of showScores
