#!/usr/bin/perl
#  Copyright 2001-2024 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; version 2 of 
#  the License, only.

# Basic version with only simple form add.


my %lex = ('Please Log In' => 'Please Log In',
	   'Error' => 'Error',
	   'Homework' => 'Homework',
	   'Main' => 'Main',
	   'Subject' => 'Subject',
	   'Date' => 'Date',
	   'Time' => 'Time',
	   'Continue' => 'Continue',
	   'Topic' => 'Topic',
	   'Description' => 'Description',
	   'Edit' => 'Edit',
	   'Delete' => 'Delete',
	   'Due Date' => 'Due Date',
	   'New' => 'New',
	   'or' => 'or',
	   'Required Field Missing' => 'Required Field Missing',
	   'Record Updated' => 'Record Updated',
	   'Contact' => 'Contact',
	   'Subject-Section' => 'Subject-Section',
	   'Are you sure' => 'Are you sure',
	   'Record' => 'Record',
	   'Yes' => 'Yes',
	   'Deleted' => 'Deleted',
	   'Not Found' => 'Not Found',

	   );


my $self = 'hwkdeled.pl';

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


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


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


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


# Set Page Title
my $title = "$lex{Edit}/$lex{Delete} $lex{Homework}";


# Get Session
my $session = new CGI::Session("driver:$dbtype;serializer:FreezeThaw",
 undef,{Handle => $dbh}) or die CGI::Session->errstr;

if ( not $session->param('logged_in') ){

    $userid = $session->param('userid');
    print $q->header( -charset, $charset );
    print qq{<h1>$title</h1>\n};

    print qq{<form action="../tlogin.pl" method="post" style="padding:0 2em;">\n};
    print qq{<input type="hidden" name="script" value="homework/$self">\n};
    print qq{<input type="hidden" name="userid" value="$userid">\n};
    print qq{<input type="submit" value="$lex{'Please Log In'}">\n};
    print qq{</form>\n};

    exit;
}

my $userid = $session->param('userid');
my $duration = $session->param('duration');

$session->expire('logged_in', $duration );
print $session->header( -charset, $charset );


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

if ( $arr{page} == 1 ) { # load date picker 
    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><body style="padding: 1em 2em;">\n};

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


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

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

} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    writeRecord();

} elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    confirmDelete( $arr{id} );

} elsif ( $arr{page} == 4 ) {
    delete $arr{page};
    deleteRecord();
}



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

    # Get Subjects Taught
    my @subjects;
    my $sth = $dbh->prepare("select subjsec from subject where teacher = ? order by description");
    $sth->execute( $userid );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $subjsec = $sth->fetchrow ) {
	push @subjects, $subjsec;
    }

    my $sth1 = $dbh->prepare("select id, subjsec, duedatetime, topic, description from plan_homework 
      where subjsec = ? order by duedatetime");

    my $sth2 = $dbh->prepare("select description from subject where subjsec = ?");

    my $globalfirst  = 1; # test to see if any homework records, any subjects

    foreach my $subjsec ( @subjects ) {

	# find any records
	$sth1->execute( $subjsec );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

	my $first = 1;
	while ( my $ref = $sth1->fetchrow_hashref ) {
	    $globalfirst = 0; # if any homework records
	    if ( $first ) {
		# Get Description
		$sth2->execute( $subjsec );
		if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		my $desc = $sth2->fetchrow;
		print qq{<h1>$desc ( $subjsec )</h1>\n};

		# Start Table
		print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
		print qq{<tr><th>$lex{'Due Date'}</th><th>$lex{Description}</th><th></th><th></th></tr>\n};		
		$first = 0;
	    }

	    print qq{<tr><td class="la">$ref->{duedatetime}</td>};
	    print qq{<td class="la">$ref->{topic} ($ref->{description})</td>\n};

	    print qq{<td><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="$ref->{id}">\n};
	    print qq{<input type="submit" value="$lex{Edit}"></form></td>\n};

	    print qq{<td><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="$ref->{id}">\n};
	    print qq{<input type="submit" value="$lex{Delete}"></form></td>\n};

	    print qq{</tr>\n};
	}

	if ( not $first ) { print qq{</table>\n}; }

    } # end of subject loop

    if ( $globalfirst ) {
	print qq{<h1>$lex{Homework}: $lex{'Not Found'}</h1>\n};
    }


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

}





#-------------
sub editRecord {
#-------------

    my $id = shift;

    # Load Homework Record
    my $sth = $dbh->prepare("select * from plan_homework where id = ?");
    $sth->execute( $id );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my $ref = $sth->fetchrow_hashref;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

    # Load Subject
    my %subjects = ();
    $sth = $dbh->prepare("select description, subjsec from subject where teacher = ?");
    $sth->execute( $userid );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my ($description, $subjsec) = $sth->fetchrow ) {
	$subjects{$subjsec} = $description;
    }


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

    # Start Table
    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};

    # Select the Subject
    print qq{<tr><td class="bra">$lex{Subject}</td>\n};
    print qq{<td class="la"><select name="subjsec">};
    print qq{<option value="$ref->{subjsec}">$subjects{$ref->{subjsec}} ($ref->{subjsec})</option>\n};
    foreach  my $subjsec ( keys %subjects ) {
	if ( $subjsec eq $ref->{subjsec} ) { next; }
	print qq{<option value="$subjsec">$subjects{$subjsec} ($subjsec)</option>\n};
    }
    print qq{</select></td></tr>\n};


    # Select the Due Date / Time (eventually)
    my ($date, $time) = split(/\s+/, $ref->{duedatetime});
    print qq{<tr><td class="bra">$lex{Date}/$lex{Time}</td>\n};
    print qq{<td class="la"><input type="text" };
    print qq{name="date" id="date" size="10" value="$date">};
    print qq{<button type="reset" id="start_trigger">...</button>\n};
    print qq{</td></tr>\n};


    # Select an Existing Topic
    my @topics = ();
    my $sth = $dbh->prepare("select distinct topic from plan_homework order by topic");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    

    print qq{<tr><td class="bra">$lex{Topic}</td>\n};
    print qq{<td class="la"><select name="topic"><option>$ref->{topic}</option>\n};
    while ( my $cat = $sth->fetchrow ) {
	print qq{<option>$cat</option>\n};
    }
    print qq{<option></option></select> $lex{or} $lex{New} $lex{Topic} };
    print qq{<input type="text" name="newtopic" size="15"></td></tr>\n};


    # Add New Description
    print qq{<tr><td class="bra">$lex{Description}</td>\n};
    print qq{<td class="la">};
    print qq{<textarea name="description" cols="80" rows="4">$ref->{description}</textarea>\n};
    print qq{</td></tr>\n};

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


    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField  : "date",
        ifFormat    : "%Y-%m-%d",
        button      : "start_trigger",
        singleClick : false,
        step        : 1
    })};

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

    exit;
}


#---------------
sub writeRecord {
#---------------

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

    # Make sure it has the right fields filled in
    if ( not $arr{date} or not $arr{description} or not $arr{subjsec} ) {
	print qq{<h1>$lex{'Required Field Missing'}</h1>\n};
	print qq{</body></html>\n};
	exit;
    }

    if ( $arr{newtopic} ) {
	$arr{topic} = $arr{newtopic};
    }

    my $sth = $dbh->prepare("update plan_homework 
     set subjsec = ?,  duedatetime = ?, topic = ?, description = ? 
     where id = ?");
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    $sth->execute( $arr{subjsec}, $arr{date}, $arr{topic}, $arr{description}, $arr{id} );

    if (not $DBI::errstr ) {
	print qq{<h3>$lex{'Record Updated'}</h3>\n};
    } else { 
	print qq{<h3>$lex{Error}: $DBI::errstr<br>};
	print qq{$lex{Contact} $adminname };
	print qq{(<a href="mailto:$adminemail">$adminemail</a>)</h3>\n};
    }

    print qq{<p>[ <a href="$self">$title</a> ]</p>\n};
    print qq{</body></html>\n};

    exit;

} # End of writeRecord



#----------------
sub confirmDelete {
#----------------

    my $id = shift;

    # Load Homework Record
    my $sth = $dbh->prepare("select * from plan_homework where id = ?");
    $sth->execute( $id );
    my $ref = $sth->fetchrow_hashref;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

    # Load Subject Desc
    $sth = $dbh->prepare("select description from subject where subjsec = ?");
    $sth->execute( $ref->{subjsec} );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    my $description = $sth->fetchrow;


    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};

    print qq{<tr><td class="bra">$lex{Subject}};
    print qq{</td><td class="la">$description</td></tr>\n};

    print qq{<tr><td class="bra">$lex{'Subject-Section'}};
    print qq{</td><td class="la">$ref->{subjsec}</td></tr>\n};

    print qq{</table>\n};
    print qq{<h3>$lex{Delete} $lex{Record}: $lex{'Are you sure'}?</h3>\n};

    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="4">\n};
    print qq{<input type="hidden" name="id" value="$arr{id}">\n};
    print qq{<input type="hidden" name="name" value="$description">\n};
    print qq{<input type="submit" value="$lex{Yes}, $lex{Delete} $lex{Record}">\n};
    print qq{</form></body></html>\n};

    exit;

}



#---------------
sub deleteRecord {
#---------------

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

    my $sth = $dbh->prepare("delete from plan_homework where id = ?");
    $sth->execute( $arr{id} );

    if ($DBI::errstr) {
	print qq{<h3>$lex{Error}: $DBI::errstr</h3>\n};
    } else {
	print qq{<h3>$lex{Record} $lex{Deleted}: $arr{name}</h3>\n};
    }

    print qq{<p>[ <a href="$self">$title</a> ]</p>\n};
    print qq{</body></html>\n};

    exit;

}


