#!/usr/bin/perl
#  Copyright 2001-2018 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.


my %lex = ('Error' => 'Error',
	   'Add' => 'Add',
	   'Main' => 'Main',
	   'Continue' => 'Continue',
	   'Required Field Missing' => 'Required Field Missing',
	   'Record(s) Stored' => 'Record(s) Stored',
	   'Unable to open template file' => 'Unable to open template file',
	   'Announcements' => 'Announcements',
	   
	   );

my $self = 'announceadd.pl';

use DBI;
use CGI;


# Set Date
my @tim = localtime(time);
my $year = $tim[5] + 1900;
my $month = $tim[4] + 1;
my $day = $tim[3];
if (length($month) == 1){ $month = '0'.$month;}
if (length($day) == 1){ $day = '0'.$day;}
my $currdate = "$year-$month-$day";


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


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


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


# Set Page Title
my $title = "$lex{Add} $lex{Announcements}";

# HTML Page Header
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" 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 qq{$chartype\n</head><body style="padding: 1em 2em;">\n};

print qq{[ <a href="$homepage">$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 {
#----------------


    # Start Form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<div style="padding:0.5em 0"><input type="submit" value="$lex{Continue}"></div>\n};


    # Load Meta Library
    eval require "../../lib/libmeta.pl";
    if ( $@ ) {
	print $lex{Error}. " $@<br>\n";
	die $lex{Error}. " $@\n";
    }


    # Read in Template
    unless (open (FH,"<../../template/announce.tpl")) {
	print $lex{'Unable to open template file'},"$!\n";
	die $lex{'Unable to open template file'},"$!\n";
    }
    my $formtext;
    { local $/; $formtext = <FH>; close FH;}


    # Create hash for fieldnames, ordering from meta.
    my $sth = $dbh->prepare("select fieldid, fieldname from meta where tableid = ?");
    $sth->execute( 'announce' );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my %fieldnames = ();
    while ( my ( $fieldid, $fieldname ) = $sth->fetchrow ) {
	$fieldnames{$fieldid} = $fieldname;
    }

    # Now put replacement text back in.
    $formtext =~ s{\<\*(.*?)\*\>}
      { exists( $fieldnames{$1} ) 
		? $fieldnames{$1} 
	        : $1
      }gsex;
    # Formtext is now ready for multiple use; only contains <@fieldid@> values.
    # now parse for form entry replacement elements  <@name@> 

    # Extract fields from template
    my @fields;
    # NOTE: Changed to non-greedy match with ? below
    while ( $formtext =~ m/\<\@(.*?)\@\>/g){
	push @fields, $1;
    }

    my $text = $formtext; # formtext contains original form.

    # Current Record Value
    my %fieldvals = %{ $ref };
    $fieldvals{adate} = $currdate;


    # get replacement values for fields
    foreach my $fieldid ( @fields ) {
	$values{$fieldid} = metaInputField('announce', $fieldid, $fieldvals{$fieldid}, $dbh, $studnum );
    }

    # Fiddle to get data popup working, by putting in id attribute
    $values{'adate'} =~ s/name="adate"/name="adate" id="date"/;


    # now put field values back into $text variable...
    $text =~ s{ \<\@(.*?)\@\> }
    { exists($values{$1}) 
	  ? $values{$1} 
          : "$values{$1}-$1"
    }gsex;

    print $text,"\n";


    print qq{<div style="padding:0.5em 0">};
    print qq{<input type="submit" value="$lex{Continue}"></div>\n};
    print qq{</form>\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 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
    my $sth = $dbh->prepare("select fieldid, fieldname from meta where tableid = ? and required = 'Y'");
    $sth->execute( 'announce' );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my ($fieldid, $fieldname) = $sth->fetchrow ) {
	if ( not $arr{"$fieldid"} ) {
	    print qq{<h3>$lex{'Required Field Missing'}: $fieldname ($fieldid)</h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}
    }
    

    my @fields;
    my @values;
    my @qst;

    foreach my $key ( keys %arr) {
	push @fields, $key;
	push @values, $arr{$key};
	push @qst, '?';
    }

    my $fields = join(',',@fields);
    my $qst = join(',',@qst);

    my $sth = $dbh->prepare("insert into announce ( $fields ) values( $qst )");
    $sth->execute( @values );


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

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

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

    exit;

} # End of writeRecords
