#! /usr/bin/perl
#  Copyright 2001-2020 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',
	   'Missing' => 'Missing',
	   
	   );

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

use DBI;
use CGI;
use Cwd;


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

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


=head

# redundant until doing direct db load
# my @fieldnames = qw( g_jquery_url g_jquery_ui_url ); 
my $sth = $dbh->prepare("select datavalue from conf_system where dataname = ?");
foreach my $var ( qw( g_jquery_url g_jquery_ui_url )) {
    $sth->execute( $var );
    my $datavalue = $sth->fetchrow;
    eval $datavalue;
    if ( $@ ) {
	print qq{$lex{Error}: $@<br>\n};
	die "$lex{Error}: $@\n";
    }
}
=cut


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

# setup for teacher site, if called from there.
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $css = $tchcss;
    $homepage = $tchpage;
    $downloaddir = $tchdownloaddir;
    $webdownloaddir = $tchwebdownloaddir;
}


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

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 jQuery libs, css

    print qq{<link rel="stylesheet" href="$g_JqueryUiCss">\n};
    
    print qq{<script type="text/javascript" src="$g_jquery_url">};
    print qq{</script>\n};

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


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

if ( not $arr{page} ) {
    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="hidden" name="page" value="3">\n};
    print qq{<input type="submit" value="$lex{Delete} Templates">\n};
    print qq{</form></div>\n};
} else {
    print qq{</div>\n}; # close div.
}


print qq{<h1>$title</h1>\n};


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

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

    foreach my $key ( sort keys %arr ) {

	my $fullname = $templatepath . $key;

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

    }

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

    print qq{</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 qq{$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 qq{<h3>$lex{Delete} $lex{Template}</h3>\n};
    
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="4">\n};    

    print qq{<div><input type="submit" value="$lex{Delete} $lex{Template}"></div>\n};

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


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

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

    exit;

}




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

    # Debug Option
    # foreach my $key ( sort keys %arr ) { print qq{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, check for missing values
    my %width = ();
    foreach my $key ( keys %arr ) {
	if ( $key =~ m/wid\_(.*)/) {
	    if ( $arr{$key} =~ m/\D/ or not $arr{$key} ) { # non digit or missing
		print qq{<h3><span style="color:red;">$lex{Width} $lex{Error}</span>: };
		print qq{$key -> $arr{$key}</h3>\n};
		print qq{</body></html>\n};
		exit;
	    }
	    $width{ $1 } = $arr{$key};
	    delete $arr{$key};
	} 
    }

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


    # Open File
    unless ( open ( FH,">", $templatepath. $filename )) {
	print qq{$lex{Error} $lex{Template}: $!\n};
	die qq{$lex{Error} $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 qq{html::<table cellspacing="0" cellpadding="3" border="1">};
	print FH qq{::</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 qq{<h3>$lex{Template}: $filename $lex{Created}</h3>\n};

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


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

}


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

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

    # Check for Missing Fields
    my $hasfields;
    foreach my $key ( sort keys %arr ) { 
	if ( $key =~ m/tc\_.*/ ) { next; }
	$hasfields = 1;
    }
    if ( not $hasfields ) {
	print qq{<h3>$lex{Error}: $lex{Fields} $lex{Missing}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    if ( not $arr{'tc_description'} ) {
	print qq{<h3>$lex{Error}: $lex{Description} $lex{Missing}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    if ( not $arr{'tc_reporttype'} ) {
	print qq{<h3>$lex{Error}: $lex{Report} $lex{Type} $lex{Missing}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    if ( $arr{'tc_reporttype'} eq 'PDF' and not $arr{'tc_pdftype'} ) {
	print qq{<h3>$lex{Error}: PDF $lex{Type} $lex{Missing}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    # 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 qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};

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


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

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

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

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

	    foreach my $key ( sort keys %arr ) {

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

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

	    }


	} else { # multicol

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

	} # end of pdf - multicol

	print qq{</table>\n};

    } # additional PDF options.


    # start of Sorting section.
    print qq{<h3>$lex{Drag} $lex{Fields} = $lex{Change} $lex{Order} (Top is Leftmost Field)</h3>\n};
    print qq{<table style="border:1px solid gray;padding:0.5em;"><tr><td>\n};
    print qq{<div id="sortstudent">\n};

    foreach my $key ( sort keys %arr ) {

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

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

    } 
    print qq{</div></td></tr></table>\n};
    # end of Sorting section.


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

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

    # Javscript Function for Sorting.
    print q{<script>
  $(function(){  //ready handler

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

 });
</script>
};


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

} # end of selectOptions




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

    # Start Form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="hidden" name="tc_reporttype" value="HTML">\n};
    # above, only create HTML reports now

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

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

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

    # Now only HTML reports, as above.
    # Report Type: pdf or html
#    print qq{<tr><td class="bra">$lex{Type}</td>\n};
#    print qq{<td><select name="tc_reporttype"><option></option>\n};
#    print qq{<option>PDF</option><option>HTML</option></select></td></tr>\n};

    
    # PDF Type: tabular or multicolumn
#    print qq{<tr><td class="bra">PDF $lex{Type}</td>\n};
#    print qq{<td><select name="tc_pdftype"><option></option>\n};
#    print qq{<option>$lex{Tabular}</option>};
#    print qq{<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 qq{<tr><td class="bra">};
    print qq{$lex{Select} $lex{Fields}</td><td><hr></td></tr>\n};


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


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

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

    exit;

}
