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

#  This file is part of Open Admin for Schools.

# To Do: Fix use of index arrays here, use named vars instead.

my %lex = ('Attendance' => 'Attendance',
	   'Phone' => 'Phone',
	   'Report' => 'Report',
	   'No Student(s) Found' => 'No Student(s) Found',
	   'Main' => 'Main',
	   'Name' => 'Name',
	   'HRm' => 'HRm',
	   'Grade' => 'Grade',
	   'Emergency' => 'Emergency',
	   'Parent 1' => 'Parent 1',
	   'Parent 2' => 'Parent 2',
	   'Gr' => 'Gr',
	   'Yesterday' => 'Yesterday',
	   'Today' => 'Today',
	   'Error' => 'Error',
	   'Date' => 'Date',
	   'Missing Value' => 'Missing Value',
	   
	   );


use DBI;
use CGI;
use Time::JulianDay;

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


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


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




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

if ( not $arr{page} ) { # load javascript library
    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>\n};

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

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


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

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

}


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

    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    # passed date and qdate (if qdate is clicked, otherwise only date comes through).

    my $date;
    if ( $arr{qdate} ) { # yesterday or today.
	if ( $arr{qdate} eq $lex{Today} ) {
	    $date = $currdate;
	} else { # yesterday
	    my $currjd = julian_day(split('-', $currdate));
	    my $yesterdayjd = $currjd - 1;
	    $date = join('-', inverse_julian_day( $yesterdayjd ));
	}
    } else {
	$date = $arr{date};
    }

    if ( not $date ) {
	print qq{<h3>$lex{Error}: $lex{'Missing Value'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


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

    my $datejd = julian_day(split('-', $date));
    my $dow = day_of_week($datejd) + 1;
    my $currabsdate = "$dow[$dow], $date";


    # Create mapping hash between name and the array index variable of value.
    my %m;
    my $sth = $dbh->prepare("select fieldid, arrayidx from meta where tableid = 'student' 
  order by arrayidx");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while (my ($fi,$idx) = $sth->fetchrow) {
	$m{$fi} = $idx;
    }

    # find students on that day.
    my $sth = $dbh->prepare("select distinct a.studentid, s.lastname, s.firstname 
     from attend as a, studentall as s 
     where s.studnum = a.studentid
     and absdate = ?
     group by studentid order by s.lastname, s.firstname");
    # and reason $sql{like} '%$absentString%'
    
    $sth->execute( $date );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }



    my $first = 1;

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

	if ( $first ) {
	    print qq{<h4>$currabsdate</h4>\n};
	    print qq{<table border="1" cellpadding ="3" cellspacing="0">\n};
	    print qq{<tr><th>$lex{Name}<br>$lex{HRm}- $lex{Grade}</th><th>$lex{'Parent 1'}</th>};
	    print qq{<th>$lex{'Parent 2'}</th><th>$lex{Emergency}</th></tr>\n};
	    $first = 0;
	}

	



	
	my $sth = $dbh->prepare("select * from student where studnum = ?");
	$sth->execute( $studnum );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;
	
	my $wd;	
	if ( not $ref->{lastname} ) { # no record in student, check studentwd
	    $sth = $dbh->prepare("select * from studentwd where studnum = ?");
	    $sth->execute( $studnum );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    
	    $wd = qq{<span style="color:red;">WD</span>\n};
	    $ref = $sth->fetchrow_hashref;
	    
	}

	my %r = %$ref;

	
	print qq{<tr><td style="vertical-align:top;"><b>$r{lastname}</b>, $r{firstname} $r{initial}<br>\n};
	print qq{<b>$lex{HRm}:</b>$r{homeroom} <b>$lex{Gr}:</b>$r{grade}</td>\n};

	$parent1name = qq{$r{par1_firstname} $r{par1_lastname}};
	$parent2name = qq{$r{par1_firstname} $r{par1_lastname}};

	# Parent 1
	print qq{<td style="vertical-align:top;">};
	if ($r{relation1}) { print qq{<b>$r{relation1}</b> }; }
	print qq{$parent1name H:$r{hphone1}<br>W:$r{wphone1} C:$r{cell1}</td>\n};

	# Parent 2
	print qq{<td style="vertical-align:top;">};
	if ($r{relation2}) { print qq{<b>$r{relation2}</b> }; }
	print qq{$parent1name H:$r{hphone2}<br>W:$r{wphone2} C:$r{cell2}</td>\n};

	# Emergency
	print qq{<td style="vertical-align:top;">};
	if ( $r{emrelation} ) { print qq{<b>$r{emrelation}</b> }; }
	print qq{$r{emname} H:$r{emhphone} <br>W:$r{emwphone}  C:$r{emcell}</td></tr>\n};

    }

    if ( $first ) {
	print qq{<h3>$lex{'No Student(s) Found'} - $currabsdate</h3>\n};
	
    } else {
	print qq{</table>\n};
    }


    print "</table></body></html>\n";

    exit;

} # end of showReport




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

    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">\n};

    print qq{<tr><td class="la"><input type="submit" name="qdate" value="$lex{Today}"></td></tr>\n};
    
    print qq{<tr><td class="la"><input type="submit" name="qdate" value="$lex{Yesterday}"></td></tr>\n};
   
    print qq{<tr><td class="la"><input type="submit" value="$lex{Date}">\n};
    print qq{<input type="text" name="date" id="date" size="10">};
    print qq{<button type="reset" id="start_trigger">...</button>};
    print qq{</td></tr>\n};

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

    
    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :  "date", // id of the input field
        ifFormat       :  "%Y-%m-%d", // format of the input field
        button         :  "start_trigger", // trigger for the calendar (button ID)
        singleClick    :  false,        // double-click mode
        step           :  1             // show all years in drop-down boxes 
    });

   </script>\n};

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

    exit;

}
