#!/usr/bin/perl
#  Copyright 2001-2026 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',
	   'Delete' => 'Delete',
	   
	   );

my $self = 'activitySet.pl';


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


my $prepath = q{../..};
if ( getcwd() =~ /ecgi/ ) { # we are in ecgi
    $prepath = q{..};
}

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

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

if ( getcwd() =~ /ecgi/ ) { # we are in ecgi
    $tchcss = $eacss;
    $tchpage = $eapage;
}


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

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


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

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

if ( not $arr{page} ) {
    my $cycletext = q{Days};
    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:60ch;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();
    
} elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    deleteActivity();
}


#----------------
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 Activity
	print qq{<tr><td>$r{title}</td><td>$r{description}</td>\n<td>};
	
	print qq{<form action="$self" method="post" style="display:inline;">\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{<form action="$self" method="post" style="display:inline;">\n};
	print qq{<input type="hidden" name="page" value="3">\n};
	print qq{<input type="hidden" name="id" value="$r{id}">\n};
	print qq{<input type="submit" value="$lex{Delete}"></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 value=""></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>\n};

    foreach my $count ( 1..$arr{actcount} ) {
	
	print qq{<table cellpadding="3" cellspacing="0" border="0" };
	print qq{style="margin-bottom:1em;border:2px solid black;padding:0.5ch;">\n};
	print qq{<caption style="font-weight:bold;text-align:left;">$count.</caption>\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>\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;
    if ( $arr{id} ) {
	$id = $arr{id};
	delete $arr{id};
    }
    
    # join %arr hash into records
    my %data;
    foreach my $key ( keys %arr ) {
	my ($count,$field) = split(':', $key );
	if ( not $field ) { next; } # no comma separator; not data group
	$data{$count}{$field} = $arr{$key};
    }

    # Test %data
#    foreach my $count ( sort keys %data ) {
#	foreach my $field ( sort keys %{ $data{$count}} ) {
#	    print qq{<div>Count:$count Field:$field VAL:$data{$count}{$field}</div>\n};
#	}
#    }

    foreach my $count ( sort keys %data ) {

	my (@fields, $fields, @values, $values);

	foreach my $field ( keys %{ $data{$count}} ) {
	    my $value = $data{$count}{$field};
	    push @fields, $field;
	    push @values, $value;

	}
	push @fields, 'userid';
	push @values, $userid;
	
	my $fields = join(',',@fields);
	
	if ( not $id ) { # add record
	    my $sth = $dbh->prepare("insert into dbkactivity ($fields) values(?,?,?,?,?,?,?)");
	    $sth->execute( @values );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

	} else { # we have an existing record. loop over field
	    foreach my $field ( @fields ) {
		my $value = shift @values;
#		print "Field:$field Value:$value<br>\n";
		my $sth = $dbh->prepare("update dbkactivity set $field = ? where id = $id");
		$sth->execute( $value);
		if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    }
	}	
    }
	
    print qq{<h3>Record(s) Added/Updated</h3>\n};

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

    exit;
    
} # end of writeActivity


#----------------
sub deleteActivity {
#----------------

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

    my $id;
    if ( $arr{id} ) {
	$id = $arr{id};
	delete $arr{id};
    }
    
    my $sth = $dbh->prepare("delete from dbkactivity where id = ?");
    $sth->execute( $id );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    print qq{<h3>Record Deleted</h3>\n};

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

    exit;
}
