#!/usr/bin/perl
#  Copyright 2001-2020 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',
	   'Grade' => 'Grade',
	   'Not Found' => 'Not Found',
	   'Error' => 'Error',
	   'Continue' => 'Continue',
	   'Month' => 'Month',
	   'Set' => 'Set',
	   'Select' => 'Select',
	   'Update' => 'Update',
	   'Updated' => 'Updated',
	   'Deleted' => 'Deleted',
	   'Record' => 'Record',
	   'Added' => 'Added',
	   'Home Room' => 'Home Room',
	   'Missing' => 'Missing',
	   'Value' => 'Value',
	   'Homerooms' => 'Homerooms',
	   
	   );

use DBI;
use CGI;
use CGI::Session;
use Time::JulianDay;
use Number::Format qw(:all);
use Cwd;

my $self = 'viewCycleDays.pl';

# Get current dir so know what path for config files.
my ($configpath, $teachermode );
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $teachermode = 1;
    $configpath = '..'; # go back one to get to etc.
} else {
    $configpath = '../..'; # go back two to get to etc.
}


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


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


# Load Configuration Variables;
my $sth = $dbh->prepare("select id, datavalue from conf_system where filename = 'admin'");
$sth->execute;
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
while (	my ($id, $datavalue) = $sth->fetchrow ) {
    eval $datavalue;
    if ( $@ ) {
	print "$lex{Error}: $@<br>\n";
	die "$lex{Error}: $@\n";
    }
}

# Teachermode
if ( $teachermode ) { # running on teacher site
    $css = $tchcss;
    $homepage = $tchpage;
#    $downloaddir = $tchdownloaddir;  # not needed in this script.
#    $webdownloaddir = $tchwebdownloaddir;
}


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

# my %periodmap = (1 => 'AM', 2 => 'PM');


my $title = "View Cycle Days";
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{<meta HTTP-EQUIV="Pragma" CONTENT="no-cache">\n};
print qq{$chartype\n</head><body style="padding:1em 2em;">\n};

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

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

#foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
# Values passed: page, date, and then any school databases;


if ( not $arr{page} ) {
    showStartPage();
    
} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    showCycleDays();
    
}



#----------------
sub showCycleDays {
#----------------

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

    eval require "../../lib/libschedule.pl"; # has calcCycleDay
    if ( $@ ) {
	print $lex{Error}. " $@<br>\n";
	die $lex{Error}. " $@\n";
    }

    
    if ( not $arr{month} ) {
	print qq{<h3>$lex{Missing} $lex{Value}. Go Back to Previous Page</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    my $month = $arr{month};
    my ($yr,$mo) = split('-', $arr{month});
    if ( length( $mo ) == 1 ) { $mo = '0'. $mo; }
    delete $arr{month};


    
    # Find dow for first of the month; check that not before school start
    my $startdate = "$yr-$mo-01";
    my $startjd = julian_day( split('-', $startdate) );
    my $startdow = day_of_week($startjd); # needed for correct calendar
    
    my $schoolstartjd = julian_day( split('-', $schoolstart) );
    if ( $startjd < $schoolstartjd ) {
	$startjd = $schoolstartjd;
	$startdate = join('-',inverse_julian_day($startjd));
    }

    
    my $startCycleDay = findDayInCycle( $startdate, $dbh );
    # used to trigger first day of the calendar display of DIC.
    while ( not $startCycleDay ) {
	$startjd++;
	$startdate = join('-',inverse_julian_day($startjd));
	$startCycleDay = findDayInCycle( $startdate, $dbh );
    }
    
        
    my ($sy,$sm,$sd) = split('-',$startdate);
    my $startday = $sd; # when we start the calendar fill for DayInCycle.
    
    
    print qq{<div style="margin:1em;"><b>Days per cycle</b>: $g_DaysPerCycle</div>\n};
#    print qq{<div> Cycle Day:$cycleDay</div>\n};
    
    my %reset;
    if ( %g_ResetCycleDate ) {
	print qq{<table cellspacing="0" border="1" cellpadding="4" };
	print qq{style="border:1px solid gray;margin:1em;float:left;">\n};
	print qq{<caption style="font-size:144%;font-weight:bold;">};
	print qq{Reset of Day in Cycle </caption>\n};
	print qq{<tr><th>Date</th><th>Cycle Day</th></tr>\n};
    
	foreach my $date ( sort keys %g_ResetCycleDate ) {
	    print qq{<tr><td>$date</td><td>$g_ResetCycleDate{$date}</td></tr>\n};
	    $reset{$date} = $g_ResetCycleDate{$date};
	}
	print qq{</table>\n};
    }

    
    # Find last day of the month (eomday)
    my $nextmonth = $mo + 1;
    my $tempyear = $yr;
    if ( $nextmonth == 1 ) { $tempyear++; }
    my $eomjd = julian_day($tempyear,$nextmonth,'1');
    my @temp = inverse_julian_day( $eomjd - 1 );
    my $eomday = $temp[2];

    
    # Set number of rows in the calendar
    my $rowcount = 5; # 5 rows in the calendar.
    my $totalcells = $eomday + $startdow; # total cells required in calendar.
    if ( $totalcells > 36 ) { $rowcount = 6; }  # to accomodate all the dates in the month.
    
    # Add Style settings for calendar
    print qq{<style>\n.caldate { font-size:120%;font-weight:bold; }</style>\n};

    
    # Get the days closed (>0.999) in the month.
    my %dayclosed;
    my $sth = $dbh->prepare("select date, dayincycle from dates 
      where month(date) = ? and  year(date) = ? and dayfraction > 0.999");
    $sth->execute( $mo, $yr );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my ($date,$dic) = $sth->fetchrow ) {
	$dayclosed{$date} = $dic; # $dic is whether is or isn't dayin cycle (0 or 1)
    }
    
    
    print qq{<table cellspacing="0" border="1" cellpadding="4" };
    print qq{style="border:1px solid gray;margin:1em;float:left;">\n};
    print qq{<caption style="font-size:144%;font-weight:bold;">};
    print qq{Day in Cycle $month[$mo], $yr</caption>\n};

    
    # Days of the Week Header
    print qq{<tr>};
    foreach my $da (0..6) { # day 1 (Sunday) and 7 (Saturday) not used, of course.
	print qq{<th>$dow[$da + 1]</th>};
    }
    print qq{</tr>\n};

    my ($calday, $caldate); # set and updated through the month.
    
    foreach my $row (1..$rowcount) {
	print qq{<tr>};
	foreach my $col (0..6) {

	    # Set the starting calendar day
	    if ($row == 1 and $col == $startdow ) {
#		print qq{Row:$row  COL:$col StartDOW:$startdow<br>\n};
		$calday = 1; 
	    }

	    # Reset caldate from calday
	    my $tempday = $calday;
	    if ( length $tempday == 1 ) { $tempday = '0'. $tempday; }
	    if ( $calday ) { $caldate = qq{$yr-$mo-$tempday}; }
	    
#	    print "CALDATE:$caldate<br>\n";

	    # weekend or closed
	    if ( $col == 0 or $col == 6 or exists $dayclosed{$caldate} ) {
		print qq{<td style="background-color:#DDD;">};
		print qq{<span>$calday</span></td>\n};
		if ( $dayclosed{$caldate} == 1 and $calday >= $startday ) {
		    $cyclecount++; # it IS a Day In cycle.
		    if ( $reset{$caldate} ) { # allow reset on this date, too.
			$cyclecount = $reset{$caldate};
		    }
		}
		
	    } else { # a week day
		
		print qq{<td><span class="caldate">$calday</span><br>};
		if ( $calday ) { # becomes undefined after end of month, etc.
		    if ( $calday > $startday ) { # First day we just use the current value
			$cyclecount++;
		    } elsif ( $calday == $startday ) {
			$cyclecount = $startCycleDay;
		    }
		    
		    if ( $reset{$caldate} ) {
			$cyclecount = $reset{$caldate};
		    } 

		    # update count to remove excess cycledays
		    if ( $cyclecount > $g_DaysPerCycle ) {
			$cyclecount = $cyclecount - $g_DaysPerCycle;
		    }

		    if ( $g_DaysPerCycle == 1 ) {
			$cyclecount = 1; # always!
		    }

		    
		    print qq{<div style="color:green;font-weight:bold;};
		    print qq{text-align:center;font-size:144%;">};
		    print qq{$cyclecount</div>\n};
		}
		    
		print qq{</td>\n};
		
#		print qq{<br>R:$row C:$col</td>};
	    }
	    if ($calday) { $calday++; }
	    if ( $calday > $eomday ) { $calday = ''; $caldate = ''; }
	}
	print qq{</tr>\n};
    }
    
    print qq{</table>};
    print qq{</body></html>\n};

    exit;

}



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

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

    my @tim = localtime(time);
    my $cyear = @tim[5] + 1900;
    my $cmonth = @tim[4] + 1;
    # my $cday = @tim[3];
    # my $currdate = "$cyear-$cmonth-$cday";
    # my $currjd = julian_day( split('-', $currdate) );
    my $curryrmo = "$cyear-$cmonth";

    
    # Setup Year-Months.
    my @months;
    my %months;

    my ($sy, $sm, $sd) = split('-', $schoolstart); # schoolstart is global var from config.
    $sm =~ s/^0//;
    my $yrmo = "$sy-$sm";
    push @months, $yrmo;
    $months{$yrmo} = "$s_month[$sm]-$sy";

    for my $i (1..10) {
	my $mo = $sm + $i;
	my $yr = $sy;
	if ( $mo > 12 ) {
	    $mo = $mo - 12;
	    $yr++;
	}
	my $yrmo = "$yr-$mo";
	push @months, $yrmo;
	$months{$yrmo} = "$s_month[$mo]-$yr";
    }

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

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

    print qq{<tr><th class="bcn">$lex{Select} $lex{Month}</th></tr>\n};
    
    foreach my $mo ( @months ) {
	my $checked;
	if ( $mo eq $curryrmo ) { $checked = qq{checked="checked"}; }
	print qq{<tr><td><input type="radio" name="month" value="$mo" $checked> $mo</td></tr>\n};
    }
  
    print qq{<tr><td><input type="submit" value="$lex{Continue}"></td></tr>\n};
    print qq{</table></form>\n};
    
    print qq{</body></html>\n};

    exit;

}
