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

#  This file is part of Open Admin for Schools.

# activityset.pl - set activities for a teacher, either part of a course, or not.


my %lex = ('Error' => 'Error',
	   'Continue' => 'Continue',
	   'Main' => 'Main',
	   'Description' => 'Description',
	   'Save' => 'Save',
	   'Edit' => 'Edit',
	   'Add' => 'Add',
	   'New' => 'New',
	   'Set' => 'Set',
	   'Activity' => 'Activity',
	   'Please Log In' => 'Please Log In',
	   'User Id' => 'User Id',
	   'Password' => 'Password',
	   'Cookie Duration' => 'Cookie Duration',
	   'Not Found' => 'Not Found',
	   'Title' => 'Title',
	   
	   );

my $self = 'activityset.pl';


use DBI;
use CGI;
use Data::Dumper;
use Time::JulianDay;
use CGI::Session;


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

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


my $q = CGI->new;
my %arr = $q->Vars;

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


my $sth = $dbh->prepare("select datavalue from conf_system where dataname = ?");
foreach my $var ( qw( doctype chartype charset tchcss tchpage g_jquery_url g_jquery_ui_url 
  g_AttendanceEntryMethod g_JqueryUiCss tchpage g_DaysPerCycle)) {
    $sth->execute( $var );
    my $datavalue = $sth->fetchrow;
    eval $datavalue;
    if ( $@ ) {
	print "$lex{Error}: $@<br>\n";
	die "$lex{Error}: $@\n";
    }
}

print $q->header( -charset, $charset );

my $userid = $ENV{'REMOTE_USER'};


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


=head
if ( $arr{page} == 1 ) { # load jQuery libs for setPeriods

    print qq{<link rel="stylesheet" href="$g_JqueryUiCss">\n};
    
    print qq{<link rel="stylesheet" href="/js/jquery.ui.timepicker.css" type="text/css">\n};

    print qq{<script type="text/javascript" src="$g_jquery_url">};
    print "</script>\n";

    print qq{<script type="text/javascript" src="$g_jquery_ui_url">};
    print "</script>\n";

    print qq{<script type="text/javascript" src="/js/jquery.ui.timepicker.js">};
    print "</script>\n";

}
=cut

    
print qq{$chartype\n</head><body>\n};

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


print qq{<h1>$title</h1>\n};
my $cycletext;
if ( $g_DaysPerCycle == 1 ) {
    $cycletext = "( Every Day is the same.)";
} elsif ( $g_DaysPerCycle == 5 or $g_DaysPerCycle eq 'w' or $g_DaysPerCycle eq 'W' ) {
    $cycletext = "( Weekly Cycle - Each monday the same, each tuesday, etc.)";
}
    
print qq{<h3>Days in a School Cycle - $g_DaysPerCycle <span style="font-size:80%;">$cycletext</span></h3>\n};

print qq{<div style="width:400px;border 1px solid gray;padding:0.4em;">};
print qq{An <b>Activity</b> is a period which is <b>Not</b> a
course, but may be a <b>part</b> of a course or may be <b>another type of
activity</b> not associated with a course, but does have an area of study
which you may set</div>\n};


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

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

} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    setActivity();
    
} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    writeActivity();
}


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

    # load existing activities, then display them in table with edit/delete options.
    my $sth = $dbh->prepare("select * from dbkactivity where userid = ?");
    $sth->execute( $userid );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    my (%activity, %sort);
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;
	$activity{ $r{id} } = $ref;
	$sort{"$r{title}$r{id}"} = $r{id};
    }


    
    # Display current activities, floated
    my $first = 1;
    foreach my $key ( sort keys %sort ) {
	my $id = $sort{$key};
	my %r = %{ $activity{$id} };

	if ( $first ) {
	    print qq{<table cellpadding="3" cellspacing="0" border="1">};
	    print qq{<caption style="font-weight:bold;font-size:120%;">Current Activities</caption>\n};
	    print qq{<tr><th>$lex{Title}</th><th>$lex{Description}</th><th></th></tr>\n};
	    $first = 0;
	}
	
	# Edit this Time Set
	print qq{<tr><td>$r{title}</td><td>$r{description}</td>\n<td>};
	
	print qq{<form action="$self" method="post">\n};
	print qq{<input type="hidden" name="page" value="1">\n};
	print qq{<input type="hidden" name="id" value="$r{id}">\n};
	print qq{<input type="submit" value="$lex{Edit}"></form>\n};

	print qq{</td></tr>\n};
	
    } # end of display current activities

    if ( not $first ) { # end the table
	print qq{</table><p></p>\n};
    }
    
    
    # Add new activity
    print qq{\n\n<div>\n};
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<table style="float:left;border:1px solid black;padding:0.4em;">\n};
    print qq{<tr><td>\n};
    print qq{<input type="submit" value="$lex{Add} $lex{New} $lex{Activity}">\n};
    print qq{Number of Activities <select name="actcount"><option></option>\n};
    foreach my $act ( 1..6 ) {
	print qq{<option>$act</option>};
    }
    print qq{\n</select></td></tr></table></form></div>\n};

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

    exit;

} # end of showStartPage



#--------------
sub setActivity {
#--------------

    # foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    # Passed: actcount - number of activities to add when adding.

    # Load Courses for this teacher
    my (%course,%csort);  # csort sorts by description of course.
    my $sth = $dbh->prepare("select * from subject where teacher = ?");
    $sth->execute( $userid );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $ref = $sth->fetchrow_hashref ) {
	$course{ $ref->{subjsec} } = $ref;
	$csort{"$ref->{description}$ref->{subjsec}"} = $ref->{subjsec};
    }

    # Get Max Terms from subjects
    my $sth = $dbh->prepare("select max(endrptperiod) from subject");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my $maxendterm = $sth->fetchrow;

    # Single record edit
    my %r;
    if ( $arr{id} ) { # edit a single record.
	$arr{actcount} = 1; # loop once.
	my $sth = $dbh->prepare("select * from dbkactivity where id = ?");
	$sth->execute( $arr{id} );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;
	%r = %$ref;
    } 
    
	
    # Form / Table Start
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="hidden" name="actcount" value="$arr{actcount}">\n};
    print qq{<input type="hidden" name="id" value="$arr{id}">\n};
    
    print qq{<div><input type="submit" value="$lex{Save}"></div><hr>\n};

    foreach my $count ( 1..$arr{actcount} ) {
	
	print qq{<table cellpadding="3" cellspacing="0" border="0" style="margin-bottom:1em;">\n};
	    
	print qq{<tr><td class="bra">Title</td><td class="la">};
	print qq{<input type="text" name="$count:title" maxlength="32"  size="12" };
	print qq{value="$r{title}"></td></tr>\n};
	
	print qq{<tr><td class="bra">Description</td><td class="la">\n};
	print qq{<textarea rows="2" cols="100" name="$count:description">};
	print qq{$r{description}</textarea></td></tr>\n};
	
	print qq{<tr><td class="bra">Start Term</td><td class="la">};
	print qq{<select name="$count:startterm"><option>$r{startterm}</option>};
	for my $trm ( 1..$maxendterm ) { print qq{<option>$trm</option>}; }
	print qq{</select></td></tr>\n};

	print qq{<tr><td class="bra">End Term</td><td class="la">};
	print qq{<select name="$count:endterm"><option>$r{endterm}</option>};
	for my $trm ( 1..$maxendterm ) { print qq{<option>$trm</option>}; }
	print qq{</select></td></tr>\n};

	print qq{<tr><td class="bra">Course</td>\n<td class="la">};
	print qq{<select name="$count:subjsec">};
	print qq{<option value="$r{subjsec}">$course{$r{subjsec}}{description} $r{subjsec}</option>};
	for my $key ( sort keys %csort ) {
	    my $subjsec = $csort{$key};
	    print qq{<option value="$subjsec">$course{$subjsec}->{description} ($subjsec)</option>}; 
	}
	print qq{<option></option></select> (if part of a course)</td></tr>\n};
	
	print qq{<tr><td class="bra">Other Activity Type</td>\n<td class="la">};
	print qq{<input type="text" name="$count:acttype" size="12" maxlength="32" };
	print qq{value="$r{acttype}">};
	print qq{ (if <b>not</b> part of a course)</td></tr>\n};

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


    print qq{<div><input type="submit" value="$lex{Save}"></div>\n};
    print qq{</form>\n};

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

}


#----------------
sub writeActivity {
#----------------

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

     
     my $id = $arr{id};
     delete $arr{id};
     if ( $id ) { # remove actcount, since we are only updating existing record.
	 delete $arr{actcount};
     }
     
     my $actcount = $arr{actcount};
     delete $arr{actcount};

     if ( not $actcount and not $id ) {
	 print qq{<h3>$lex{Error} - No Data Found</h3>\n};
	 print qq{</body></html>\n};
	 exit;
     }
     
     if ( $actcount ) { # adding activities
	 my $sth = $dbh->prepare("insert into dbkactivity (userid, title, description, 
           startterm,endterm,acttype,subjsec) values(?,?,?,?,?,?,?)");
	 
	 # join %arr hash into records
	 my %data;
	 foreach my $key ( keys %arr ) {
	     my ($count,$field) = split(':', $key );
	     $data{$count}{$field} = $arr{$key};
	 }

	 # Loop and add records.
	 for my $count ( 1 .. $actcount ) {
	     my %r = %{ $data{$count}};
	     
	     if ( $r{title} ) { # if we have a title, we will add the record.
		 $sth->execute( $userid, $r{title}, $r{description},$r{startterm}, $r{endterm}, 
				$r{acttype}, $r{subjsec});
		 if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		 
	     } else {
		 print qq{<h3>Missing Title. No Record Added.</h3>\n};
	     }
	 }
	 
     } elsif ( $id ) { # update the record.
	 
	 foreach my $key ( keys %arr ) {
	     my ($count,$field) = split(':', $key );
	     my $sth = $dbh->prepare("update dbkactivity set $field = ? where id = $id");
	     $sth->execute($arr{$key});
	     if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	 }

     }
	 
     
    print qq{<h3>Records Updated</h3>\n};

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

    exit;
}

