#! /usr/bin/perl
#  Copyright 2001-2010 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; either version 2 of 
#  the License, or (at your option) any later version.



my %lex = ('Main' => 'Main',
	   'Template' => 'Template',
	   'Creator' => 'Creator',
	   'Description' => 'Description',
	   'Type' => 'Type',
	   'Select' => 'Select',
	   'Fields' => 'Fields',
	   'Error' => 'Error',
	   'Continue' => 'Continue',
	   'Column' => 'Column',
	   'Number' => 'Number',
	   'Width' => 'Width',
	   'Order' => 'Order',
	   'Tabular' => 'Tabular',
	   'Multicolumn' => 'Multicolumn',
	   'Reorder' => 'Reorder',
	   'Student Roster' => 'Student Roster',
	   'Report' => 'Report',
	   'Created' => 'Created',
	   'Delete' => 'Delete',
	   'Select' => 'Select',
	   'Deleted' => 'Deleted',
	   'Save' => 'Save',
	   'Drag' => 'Drag',
	   'Change' => 'Change',
	   'Order' => 'Order',
	   'View' => 'View',
	   'New' => 'New',
	   
	   );

my $self = 'templatecreator.pl';
my $templatepath = '../template/';
my $startTemplateDelete = 5;  # Starting Number for User Created Templates (to delete)

use DBI;
use CGI;


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

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


# Page Header
$title = "$lex{Template} $lex{Creator}";

print "$doctype\n<html><head><title>$title</title>
<link rel=\"stylesheet\" href=\"$css\" type=\"text/css\">\n";

if ( $arr{page} == 1 ) { # load jQuery libs
    print "<script type=\"text/javascript\" ";
    print "src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js\">";
    print "</script>\n";

    print "<script type=\"text/javascript\" ";
    print "src=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js\">";
    print "</script>\n";
}


print "$chartype\n</head><body style=\"padding:1em 3em;\">\n";
print "<div>[ <a href=\"$homepage\">$lex{Main}</a> ]\n";

print "<form action=\"$self\" method=\"post\" style=\"display:inline;\">\n";
print "<input type=\"hidden\" name=\"page\" value=\"3\">\n";
print "<input type=\"submit\" value=\"$lex{Delete} $lex{Template}\">\n";
print "</form></div>\n";

print "<h1>$title</h1>\n";


# Setup Database access
my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);
$dbh->{mysql_enable_utf8} = 1;


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

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

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

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

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


#-----------------
sub deleteTemplate {
#-----------------

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

    foreach my $key ( sort keys %arr ) {

	my $fullname = $templatepath . $key;

	my $result = unlink( $fullname );
	if ( $result ) {
	    print "<p>$key $lex{Deleted}</p>\n";
	}

    }

    print "<p>[ <a href=\"rptstudrost.pl\">$lex{'Student Roster'} $lex{Report}</a> | \n";
    print "<a href=\"$self\">$lex{Template} $lex{Creator}</a> | \n";
    print "<a href=\"$homepage\">$lex{Main}</a> ]</p>\n";

    print "</body></html>\n";
    exit;


}


#-------------------------
sub selectTemplateToDelete {
#-------------------------


    # Open the Report Templates
    my @files = glob($templatepath."rptstudrost*.tpl");

    for my $tplfile ( @files ) {
	# read each label file and get description
	unless ( open (FH,"<$tplfile")) {
	    print "$lex{Error} $lex{Template}: $!\n";
	    die "$lex{Error} $lex{Template}: $!\n";
	}

	# read first 2 lines of the template only.
	my $desc = <FH>;
	chomp $desc;
	$desc =~ s/\[//g;  # strip any opening square labels, just in case.

	my $modeline = <FH>;
	$modeline =~ s/^\s*//; # strip any leading spaces
	my ($mode, $fmtstart,$fmtend) = split /::/, $modeline;
	# ignore rest of the file, not required.

	$tplfile =~ s/^.*\///; # strip leading path
	push @desc, "$desc ($mode) [$tplfile]";
    }

    print "<h3>$lex{Delete} $lex{Template}</h3>\n";
    print "<table cellpadding=\"3\" cellspacing=\"0\" border=\"1\">\n";
    print "<tr><th>$lex{Template}</th><th>$lex{Select}</th></tr>\n";

    print "<form action=\"$self\" method=\"post\">\n";
    print "<input type=\"hidden\" name=\"page\" value=\"4\">\n";    


    foreach my $desc ( @desc ) {
	$desc =~ m/rptstudrost(.*)\.tpl/;
	my $num = $1;
	print "<tr><td>$desc</td><td>\n";
	if ( $num >= $startTemplateDelete ) {
	    print "<input type=\"checkbox\" name=\"rptstudrost$num.tpl\" value=\"1\">";
	}
	print "</td></tr>\n";
    }

    print "<tr><td colspan=\"2\" style=\"text-align:left;\">";
    print "<input type=\"submit\" value=\"$lex{Delete} $lex{Template}\"></td></tr>\n";
    print "</form></table>\n";
    print "</body></html>\n";

    exit;

}




#-----------------
sub createTemplate {
#-----------------

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


    my $reporttype = lc( $arr{tc_reporttype} );
    delete $arr{tc_reporttype};

    my $description = $arr{tc_description};
    delete $arr{tc_description};

    my $pdftype = lc( $arr{tc_pdftype} );
    delete $arr{tc_pdftype};

    my $colcount = $arr{tc_colcount};
    delete $arr{tc_colcount};


    my $filename;
    for my $i ( 0 .. 99 ) {
	if ( length $i == 1 ) { $i = '0'. $i; } # prepend a zero.
	$filename = 'rptstudrost'. $i. '.tpl';
	my $fullname = $templatepath. $filename;
	if ( -e $fullname ) { next; } # skip
	last; # we have a filename to use.
    }

    # 
    my @fields = split(",", $arr{sortorder} );
    foreach my $fld ( @fields ) {
	$fld =~ s/s\_//;
    }
    delete $arr{sortorder};


    # Extract the width keys
    my %width = ();
    foreach my $key ( keys %arr ) {
	if ( $key =~ m/wid\_(.*)/) {
	    $width{ $1 } = $arr{$key};
	    delete $arr{$key};
	} 
    }

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


    # Open File
    unless ( open ( FH,">", $templatepath. $filename )) {
	print $lex{Error}. q{ }. $lex{Template}.": $!\n";
	die $lex{Error}. q{ }. $lex{Template}.": $!\n";
    }

    # Write Description line - Line 1
    print FH $description. "\n";

    if ( $reporttype eq 'pdf' ) {

	if ( $pdftype eq 'tabular' ) {

	    # Write Type and Format Line - Line 2
	    print FH 'pdf::\begin{tabular}{|';
	    foreach my $fld ( @fields ) {
		print FH 'p{'. $width{ $fld }. 'mm}|';
	    }
	    print FH '}\hline::\end{tabular}'. "\n";

	    # Write the header line - Line 3
	    my $first = 1;
	    print FH '\rowcolor[gray]{0.85}';
	    foreach my $fld ( @fields ) {
		if ( not $first ) { print FH ' &'; } else { $first = 0; }
		print FH '{\bf <*'. $fld. '*>}';
	    }
	    print FH '\\\\ \hline'. "\n";

	     print FH "\n"; # blank line 4 and 5 for future expansion.
	     print FH "\n";


	    # Write the layout.
	    my $first = 1;
	    foreach my $fld ( @fields ) {
		if ( not $first ) { print FH ' &'; } else { $first = 0; }
		print FH '<@'. $fld. '@>';
	    }
	    print FH '\\\\ \hline'. "\n";


	} else { # pdftype is multicolumn

	    # Write Type and Format Line - Line 2
	    print FH 'pdf::\begin{multicols}{'. $colcount. '}::\end{multicols}'. "\n";

	    # Write blank header line - Line 3
	    print FH "\n";

	    print FH "\n"; # blank line 4 and 5 for future expansion.
	    print FH "\n";


	    # Write the layout.
	    foreach my $fld ( @fields ) {
		print FH '<*'. $fld. '*> <@'. $fld. '@>\\\\'. "\n";
	    }
	}

    } else { # HTML report type

	# Write Type and Format Line - Line 2
	print FH "html::<table cellspacing=\"0\" cellpadding=\"3\" border=\"1\">";
	print FH "::</table>::\n"; # no record count;

	# Write the header line - Line 3
	print FH '<tr>';
	foreach my $fld ( @fields ) {
	    print FH '<th><*'. $fld. '*></th>';
	}
	print FH '</tr>'. "\n";

	print FH "\n"; # blank line 4 and 5 for future expansion.
	print FH "\n";

	# Write the layout.
	print FH '<tr>';
	foreach my $fld ( @fields ) {
	    print FH '<td><@'. $fld. '@></td>';
	}
	print FH '</tr>'. "\n";

    }

    close FH;

    print "<h3>$lex{Template}: $filename $lex{Created}</h3>\n";

    print "<p>[ <a href=\"rptstudrost.pl?tpl=$filename\">$lex{View} $lex{New} $lex{Report}</a> |\n";
    print "<a href=\"$homepage\">$lex{Main}</a> ]</p>\n";


    print "</body></html>\n";
    exit;

}


#----------------
sub selectOptions {
#----------------

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

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


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

    # put in hidden keys
    foreach my $key ( sort keys %arr ) {
	print "<input type=\"hidden\" name=\"$key\" value=\"$arr{$key}\">\n"; 
    }


    if ( $arr{tc_reporttype} eq 'PDF' ) { # add more fields

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

	if ( $arr{tc_pdftype} eq $lex{Tabular} ) {

	    print "<tr><th>$lex{Fields}</th><th>$lex{Width}</th></tr>\n";

	    foreach my $key ( sort keys %arr ) {

		if ( $key =~ m/tc\_.*/ ) { next; }

		print "<tr><td class=\"bra\">$key</td>\n";
		print "<td><input type=\"text\" name=\"wid_$key\" size=\"4\">";
		print " mm </td></tr>\n";

	    }


	} else { # multicol

	    # get column count
	    print "<tr><td align=\"right\">$lex{Column} $lex{Number}</td>\n";
	    print "<td><input type=\"text\" name=\"tc_colcount\" size=\"5\">\n";
	    print "</td></tr>\n";

	} # end of pdf - multicol

	print "</table>\n";

    } # additional PDF options.


    # start of Sorting section.
    print  "<h3>$lex{Drag} $lex{Fields} = $lex{Change} $lex{Order}</h3>\n";
    print "<div id=\"sortstudent\">\n";

    foreach my $key ( sort keys %arr ) {

	if ( $key =~ m/tc\_.*/ ) { next; } # skip non field values

	my $id = 's_'. $key;
	print "<div id=\"$id\" style=\"padding:0.6em 0em;cursor:move;font-weight:bold;\">";
	print "$fieldnames{$key}</div>\n";

    } 
    print "</div>\n";
    # end of Sorting section.


    # Save Button
    print "<p><input type=\"submit\" value=\"$lex{Save}\"></p>\n";

    print "<input type=\"hidden\" id=\"inputsort\" name=\"sortorder\">\n";
    print "</form>\n";

    # Javscript Function for Sorting.
    print q{<script type="text/javascript">
  $(function(){  //ready handler

    $("#sortstudent").sortable({
      update: function () {
	var order =  $("#sortstudent").sortable('toArray');
	$("#inputsort").attr("value", order);
      },
      axis:'y'
    });

 });
</script>
};


  print "</body></html>\n";
  exit;

} # end of selectOptions




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


    # Start Form
    print "<form action=\"$self\" method=\"post\">\n";
    print "<input type=\"hidden\" name=\"page\" value=\"1\">\n";
    print "<table cellpadding=\"3\" cellspacing=\"0\" border=\"0\">\n";

    # Continue Button
    print "<tr><td class=\"cn\" colspan=\"2\">\n";
    print "<input type=\"submit\" value=\"$lex{Continue}\"></td></tr>\n";

    # Description
    print "<tr><td class=\"bra\">$lex{Description}</td>\n";
    print "<td><input type=\"text\" name=\"tc_description\" size=\"30\"></td></tr>\n";

    # Report Type: pdf or html
    print "<tr><td class=\"bra\">$lex{Type}</td>\n";
    print "<td><select name=\"tc_reporttype\"><option></option>\n";
    print "<option>PDF</option><option>HTML</option></select></td></tr>\n";

    # PDF Type: tabular or multicolumn
    print "<tr><td class=\"bra\">PDF $lex{Type}</td>\n";
    print "</td><td><select name=\"tc_pdftype\"><option></option>\n";
    print "<option>$lex{Tabular}</option>";
    print "<option>$lex{Multicolumn}</option></select></td></tr>\n";


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

    # Select Fields to Show
    print "<tr><td class=\"bra\">";
    print "$lex{Select} $lex{Fields}</td><td><hr></td></tr>\n";


    while ( my ( $fieldid, $fieldname ) = $sth->fetchrow ) {
	print "<tr><td></td><td class=\"bla\">\n";
	print "<input type=\"checkbox\" name=\"$fieldid\" value=\"1\"> $fieldname</td></tr>\n";
    }
    print "<tr><td colspan=\"2\"><hr></td></tr>\n";


    # Continue Button
    print "<tr><td align=\"center\" colspan=\"2\">\n";
    print "<input type=\"submit\" value=\"$lex{Continue}\"></td></tr>\n";
    print "</table></form>\n";

    print "</center></body></html>\n";

    exit;

}
