#!/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 = ('Not Found' => 'Not Found',
	   'Password' => 'Password',
	   'User Id' => 'User Id',
	   'Please Log In' => 'Please Log In',
	   'Error' => 'Error',
	   'Homework' => 'Homework',
	   'Add' => 'Add',
	   'Main' => 'Main',
	   'Subject' => 'Subject',
	   'Date' => 'Date',
	   'Time' => 'Time',
	   'or' => 'or',
	   'Continue' => 'Continue',
	   'Cookie Duration' => 'Cookie Duration',
	   'Topic' => 'Topic',
	   'Description' => 'Description',
	   'Required Field Missing' => 'Required Field Missing',
	   'Record(s) Stored' => 'Record(s) Stored',
	   'New' => 'New',
	   'No Subjects Found' => 'No Subjects Found',
	   
	   );


my $self = 'hwkadd.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{Add} $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>
<link rel="stylesheet" href="$tchcss" type="text/css">\n};

if ( not $arr{page} ) { # load jQuery 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 q{<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/themes/base/ui.all.css" rel="stylesheet" type="text/css">};
}

# print qq{<style type="text/css">.flt { float:left; }</style>\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};
    writeRecords();

}



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

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

    if ( not %subjects ) {
	print qq{<h3>$lex{'No Subjects Found'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    # Start Form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\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"><option></option>\n};
    foreach my $key ( sort keys %subjects ) {
	print qq{<option value="$subjects{$key}">$key</option>\n};
    }
    print qq{</select></td></tr>\n};


    # Select the Due Date / Time (not yet)
    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">};
    print qq{<button type="reset" id="start_trigger">...</button>\n};
    print qq{</td></tr>\n};

    # print qq{<input type="text" id="datetime" name="datetime" size="10"></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></option>\n};

    while ( my $cat = $sth->fetchrow ) {
	print qq{<option>$cat</option>\n};
    }
    print qq{</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"></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};


    # script setup
#    print qq{<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>\n};
#    print qq{<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js"></script>\n};
#    print qq{<script src="jquery.ui.datetimepicker.min.js" type="text/javascript"></script>\n};

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

#    print  '$( function(){ $('#datetime'.datetimepicker() )}';
#    print  q{$('#datetime').datepicker() };

    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 writeRecords {
#---------------

    # 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("insert into plan_homework 
     ( subjsec, teacher, duedatetime, topic, description )
     values(?,?,?,?,? )");
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

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


    if (not $DBI::errstr ) {
	print qq{<h3>$lex{'Record(s) Stored'}</h3>\n};
    } else { 
	print qq{<h3>$lex{Error}: $DBI::errstr</h3>};
    }

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

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


    exit;

} # End of writeRecords
