#!/usr/bin/perl
#  Copyright 2001-2023 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.

# Dual Run Script:  cgi and tcgi

%lex = ('Withdrawn Students' => 'Withdrawn Students',
	'Main' => 'Main',
	'Top' => 'Top',
	'No Records Found' => 'No Records Found',
	'All Records' => 'All Records',
	'Error' => 'Error',
	'Continue' => 'Continue',
	'Lastname' => 'Lastname',
	'Birthdate' => 'Birthdate',
	'Grade' => 'Grade',
	'Homeroom' => 'Homeroom',
	'Sort by' => 'Sort by',
	'Select by' => 'Select by',
	'View' => 'View',
	'Students' => 'Students',
	'Select by' => 'Select by',
	'OR' => 'OR',
	'Show Withdrawn' => 'Show Withdrawn',
	
);

use DBI;
use CGI;
use Cwd;

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

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


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);


my $mode;  # normal or withdrawn mode
my $table = 'student';
if ( $arr{table} eq 'wd' ) {
    $mode = 'wd';
    $table = 'studentwd';
}

my ($sec, $min, $hour, $mday, $mon, $year, $wday, 
    $yday, $iddst) = localtime(time);
$year = $year + 1900;
$mon++;
$wday++;
my $currdate = "$dow[$wday], $month[$mon] $mday, $year";


# Get current dir so know what CSS to display;
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $css = $tchcss;
    $homepage = $tchpage;
}


# Display top of page
my $title = "$lex{View} $lex{Students}";

print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
if ($mode eq 'wd') { 
    print qq{<style type="text/css">th { background-color:#707;} h1 { color:#707; }</style>\n};
}

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

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

   
# Show start page if only beginning.
if ( not $arr{page} ) {
    showStartPage();

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


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

    # foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    # Passed: grade, homeroom, student, showwithdrawn
    

    # Read in Template
    eval open (FH,"<../template/student.tpl");
    if ( $@ ) {
	print $lex{Error}. " $@<br>\n";
	die $lex{Error}. " $@\n";
    }

    # Slurp data
    my $formtext;
    { local $/; $formtext = <FH>; close FH;}

    # Create hash for fieldnames from meta.
    my $sth = $dbh->prepare("select fieldid, fieldname, required from meta where tableid = ?");
    $sth->execute( student );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my %fieldnames;
    while ( my ( $fieldid, $fieldname, $required ) = $sth->fetchrow ) {
	if ( $required ) { # has any value
	    $fieldname = qq{<span style="font-weight:bold;">$fieldname</span>};
	}
	$fieldnames{$fieldid} = $fieldname;
    }

    # Now put replacement text back in.
    $formtext =~ s{\<\*(.*?)\*\>}
    { exists( $fieldnames{$1} ) 
	? $fieldnames{$1} 
	: $1
    }gsex;


    my $table = 'student';
    if ( $arr{showwithdrawn} ) { $table = 'studentall'; }

    # Passed: grade, homeroom, or student;
    my $sth;
    if ( $arr{grade} ) {
	$sth = $dbh->prepare("select * from $table where grade = ? order by lastname, firstname");
	$sth->execute( $arr{grade} );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

    } elsif ( $arr{homeroom} ) {
	$sth = $dbh->prepare("select * from $table where homeroom = ? order by lastname, firstname");
	$sth->execute( $arr{homeroom} );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	
    } elsif ( $arr{student} ) {
	$sth = $dbh->prepare("select * from studentall where studnum = ?");
	$sth->execute( $arr{student} );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	
    } else {
	print qq{<h3>Missing Value</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    my $first = 1;

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

	my %rec = %$ref;
	my $text = $formtext; # make a copy to use.

	# Check for a picture and picture mode (ShowStudentPicture)
	if ( $r_ShowStudentPicture ) { # put in a table value with a picture link.
	    if ( $rec{pic} ) {
		my $pictureform = qq{<div><img style="width:250px;" src="/pic-big/}. $rec{studnum}.
		    qq{.jpg"></div>\n};
		$text =~ s/\<a name=\"picture\"\>\<\/a\>/$pictureform/;
	    }
	}
	
	# now put field values back into $text variable...
	$text =~ s{ \<\@(.*?)\@\> }
	{ exists($rec{$1}) 
	? $rec{$1} 
	: "$rec{$1}-$1"
        }gsex;

	print qq{<hr><div style="background-color:#EEE;border 1px solid black;padding:1em;">};
	print $text, qq{\n};
	print qq{</div>\n};

	$first = 0;

    }

    if ( $first ){ # no records found
	print qq{<div style="font-size:150%;font-weight:bold;">$lex{'No Records Found'}</div>\n};
    
    } else {
	print qq{</table>\n};
	print qq{[ <a href="#top">$lex{'Top'}</a> ]\n};
    }

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

    exit;

}



#----------------
sub showStartPage { # Entry Values for Custom Script
#----------------

    my (@homerooms, @grades );
    # Get Homerooms
    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;
    }
    @homerooms = sort {$a <=> $b} @homerooms;

    # Get Grades
    $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;


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

    if ( $arr{table} ) { # for withdrawn mode.
	print qq{<input type="hidden" name="table" value="wd">\n};
    }

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

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

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


    # Select Homeroom
    print qq{<tr><td class="bra">$lex{'Select by'} $lex{Homeroom}</td>};
    print qq{<td><select name="homeroom"><option></option>\n};
    foreach my $hr ( @homerooms ) {
	print qq{<option>$hr</option>\n};
    }
    print qq{</select></td></tr>\n};


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

    # Student Number
    print qq{<tr><td class="bra">Local Student Number</td>};
    print qq{<td><input type="text" name="student" style="width:6ch;"></td></tr>\n};
    
    # Withdrawn
    print qq{<tr><td class="bra">$lex{'Show Withdrawn'}</td>};
    print qq{<td><input type="checkbox" name="showwithdrawn" value="1"></td></tr>\n};

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

    exit;

}
