#!/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',
	   'Main' => 'Main',
	   'Date' => 'Date',
	   'Topic' => 'Topic',
	   'Description' => 'Description',
	   'Edit' => 'Edit',
	   'Delete' => 'Delete',
	   'Required Field Missing' => 'Required Field Missing',
	   'Record Updated' => 'Record Updated',
	   'Contact' => 'Contact',
	   'Are you sure' => 'Are you sure',
	   'Record' => 'Record',
	   'Yes' => 'Yes',
	   'Deleted' => 'Deleted',
	   'Update' => 'Update',
	   'Announcements' => 'Announcements',
	   'Top' => 'Top',
	   'Type' => 'Type',
	   'No Record(s) Found' => 'No Record(s) Found',
	   'Unable to open template file' => 'Unable to open template file',

	   );

my $self = 'announcedeled.pl';

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


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

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


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


# Set Page Title
my $title = "$lex{Edit}/$lex{Delete} $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 ( $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="$homepage">$lex{Main}</a> ]\n};
print qq{<h1>$title</h1>\n};


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

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

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


    my $sth = $dbh->prepare("select * from announce
      order by adate ");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }


    my $first = 1;

    while ( my $ref = $sth->fetchrow_hashref ) { # load records

	my %rec;
	%rec = %$ref;

	if ( $first ) {
	    # Start Table
	    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
	    print qq{<tr><th>$lex{Date}</th><th>$lex{Topic}</th><th>Author</th><th>$lex{Description}</th>};
	    print qq{<th>$lex{Top}</th><th>$lex{Type}</th><th></th><th></th></tr>\n};		
	    $first = 0;
	}

    
	print qq{<tr><td class="la">$rec{adate}</td>};
	print qq{<td class="la">$rec{atopic}</td>\n};
	print qq{<td class="la">$rec{author}</td>\n};	
	print qq{<td class="la">$rec{adesc}</td>\n};

	if ( $rec{topstay} ) { $rec{topstay} = $lex{Yes}; }
	print qq{<td class="la">$rec{topstay}</td>\n};

	print qq{<td class="la">$rec{atype}</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 ( $first ) {
	print qq{<h3>$lex{'No Record(s) Found'}</h3>\n};
    }


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

}


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

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

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

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


    # print top of form, then $text, then bottom of page.
    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="$arr{id}">\n};
    print qq{<input type="submit" value="$lex{Update}">\n};


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

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


     # Create hash for fieldnames 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@> 

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

    # Current Record Value
    my %fieldvals = %{ $ref };
    
    # get replacement values for fields
    foreach my $fieldid ( keys %fieldnames ) {
	$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, qq{\n};

    print qq{<input type="submit" value="$lex{Update}">\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 writeRecord {
#---------------

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

    # get record id and remove from the hash.
    my $id = $arr{id};
    delete $arr{id};


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


    # Check for any checkbox formtypes, reset to NULL if not found.
    my $sth = $dbh->prepare("select fieldid, fieldname from meta 
      where tableid = ? and formtype = 'checkbox'");
    $sth->execute( 'announce' );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my ($fieldid, $fieldname) = $sth->fetchrow ) {
	if ( not $arr{"$fieldid"} ) { # checkbox turned off... reset to NULL
	    my $sth = $dbh->prepare("update announce set $fieldid = NULL where id = ?");
	    $sth->execute( $id );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	}
    }

    # Update passed values.
    foreach my $fieldid ( keys %arr ) {
	my $sth = $dbh->prepare("update announce set $fieldid = ? where id = ?");
	$sth->execute( $arr{"$fieldid"}, $id );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    }


    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 Record
    my $sth = $dbh->prepare("select * from announce where id = ?");
    $sth->execute( $id );
    my $ref = $sth->fetchrow_hashref;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

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

    print qq{<tr><td class="bra">$lex{Topic}};
    print qq{</td><td class="la">$ref->{atopic}</td></tr>\n};

    print qq{<tr><td class="bra">$lex{Date}};
    print qq{</td><td class="la">$ref->{adate}</td></tr>\n};

    print qq{<tr><td class="bra">$lex{Description}};
    print qq{</td><td class="la">$ref->{adesc}</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="topic" value="$ref->{topic}">\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 announce where id = ?");
    $sth->execute( $arr{id} );


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

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

    exit;

}


