#!/usr/bin/perl
#  Copyright 2001-2020 Leslie Richardson

use DBI;
use CGI;
use Number::Format qw(:all);

my %lex = ('Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Main' => 'Main',
	   'Select' => 'Select',
	   'Values' => 'Values',
	   'Group' => 'Group',
	   'Parent' => 'Parent',
	   'Subject' => 'Subject',
	   'Message' => 'Message',
	   'Continue' => 'Continue',
	   'Student' => 'Student',
	   'Checked' => 'Checked',
	   'Email Sent' => 'Email Sent',
	   'Error' => 'Error',
	   'Email' => 'Email',
	   'Next Page' => 'Next Page',
    );

my $self = 'emailTeacher.pl';


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

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

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


# Page Header.
my $title = "Email Students/Parents";
print "$doctype\n<html><head><title>$title</title>\n";
print qq{<link rel="stylesheet" href="$tchcss" type="text/css">\n};

print qq{[ <a href="$tchpage">Main</a> ]\n};
print qq{<h1>$title</h1>\n};


if ( not $arr{page} ) { # Select Groups and which emails to do (Student, Parents)
    showStartPage();

} elsif ( $arr{page} == 1 ) { # Select Students, Parents / Set Message, Attachment
    delete $arr{page};
    selectRecipients();

} elsif ( $arr{page} == 2 ) { # post the Mail
    delete $arr{page};
    showReport();
}


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

    my (@homerooms, @grades );
    # Get Homerooms
    my $sth = $dbh->prepare("select distinct homeroom from student 
      where homeroom is not NULL and homeroom != ''");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $hr = $sth->fetchrow ) {
	push @homerooms, $hr;
    }
    @homerooms = sort {$a <=> $b} @homerooms;

    # Get Grades
    $sth = $dbh->prepare("select distinct grade from student 
      where grade is not NULL and grade != ''");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $gr = $sth->fetchrow ) {
	push @grades, $gr;
    }
    @grades = sort {$a <=> $b} @grades;

=head    
    print qq{<table cellpadding="3" cellspacing="0" border="0" };
    print qq{style="margin-bottom:0.4em; border:1px solid gray;padding:0.3em;">\n};
    
    print qq{<tr><td class="bra">Current Grades</td>};
    print qq{<td style="la">};
    foreach my $gr ( @grades ) {
	print "$gr ";
    }
    print qq{</td></tr>\n};

    print qq{<tr><td class="bra">Current Homerooms</td>};
    print qq{<td>};
    foreach my $hr ( @homerooms ) {
	print qq{$hr };
    }
    print qq{</td></tr>\n};
    print qq{</table>\n};
=cut
    
    
    # Setup the form and start of table.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<table cellpadding="3" border="0" cellspacing="0">\n};


    # Grades;
    print qq{<table cellpadding="3" cellspacing="0" border="0" };
    print qq{style="float:left;border:1px solid gray;margin:0.5em;"};
    print qq{<tr><th>Select<br>Grades</th></tr>\n};

    foreach my $gr ( @grades ) {
	print qq{<tr><td><input type="checkbox" name="G:$gr" value="1">$gr</td></tr>\n};
    }
    print qq{</table>\n};

    # Homerooms;
    print qq{<table cellpadding="3" cellspacing="0" border="0" };
    print qq{style="float:left;border:1px solid gray;margin:0.5em;"};
    print qq{<tr><th>Select<br>Homerooms</th></tr>\n};

    foreach my $hr ( @homerooms ) {
	print qq{<tr><td><input type="checkbox" name="H:$hr" value="1">$hr</td></tr>\n};
    }
    print qq{</table>\n};

    # Rest of Options.
    print qq{<table cellpadding="3" cellspacing="0" border="0" };
    print qq{style="float:left;border:1px solid gray;margin:0.5em;padding:0.5em;"};
    
    print qq{<tr><td class="bra">$lex{Select}</td><td class="la">\n};
    print qq{<input type="checkbox" name="selStudent" value="1"> };
    print qq{$lex{Student} $lex{Email}<br>\n};

    print qq{<input type="checkbox" name="selPar1" value="1"> };
    print qq{ $lex{Parent} 1 $lex{Email}<br>\n};

    print qq{<input type="checkbox" name="selPar2" value="1"> };
    print qq{ $lex{Parent} 2 $lex{Email}<br>\n};

    print qq{<tr><td colspan="2"><hr></td></tr>\n};
    
    print qq{<tr><td class="bra">$lex{'Next Page'}<br>$lex{Checked}?</td><td class="la">\n};
    print qq{<input type="checkbox" name="checked" value="checked"></td></tr>\n};

    print qq{<tr><td></td><td class="la">};
    print qq{<input type="submit" value="$lex{Continue}">};
    print qq{</td></tr>\n};

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

    exit;

}



#-------------------
sub selectRecipients { # Choose students/parents to email to and put in message
#-------------------

    # foreach my $key ( sort keys %arr) { print qq{K:$key V:$arr{$key}<br>\n}; }
    # passed 3 email selects, checked, then grades or homerooms as G:* or H:*

    
    my $checked;
    if ( $arr{checked} ) {
	$checked = qq{checked="checked"};
	delete $arr{checked};
    }

    my $studmail = $arr{selStudent};
    my $par1mail = $arr{selPar1};
    my $par2mail = $arr{selPar2};
    delete $arr{selStudent};
    delete $arr{selPar1};
    delete $arr{selPar2};
    
    # foreach my $key ( sort keys %arr) { print qq{K:$key V:$arr{$key}<br>\n}; }

    foreach my $key ( sort keys %arr ) {
	my ($group, $value ) = split(':', $key);
	if ( $group eq 'G' ) {
	    push @grades, $value;
	} elsif ( $group eq 'H' ) {
	    push @homerooms, $value;
	} else {
	    print qq{<h3>Error: No value for $key</h3>\n};
	}
    }

    
    my %groups;
    @{$groups{homeroom}} = @homerooms;
    @{$groups{grade}} = @grades;
    
    
    # Start Form / Table.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};

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

    foreach my $type ( keys %groups ) {

	my $sth = $dbh->prepare("select lastname, firstname, studnum, email, par1_email, 
				par2_email from student 
				where $type = ? order by lastname, firstname");

	my @group = @{ $groups{$type} };
	
        foreach my $group ( @group ) {
	    $sth->execute( $group );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    my $first = 1;

	    # Loop through the students
	    while ( my ($lastname, $firstname, $studnum, $email, $par1_email, $par2_email ) =
		    $sth->fetchrow ) {

		if ( $first ) {
		    print qq{<table cellpadding="3" border="1" cellspacing="0" };
		    print qq{style="border:1px solid gray;margin:0.5em;float:left;">\n};
		    my $temptype = ucfirst($type);
		    print qq{<caption style="font-weight:bold;font-size:120%;">};
		    print qq{$temptype $group</caption>\n};
		    print qq{<tr><th>$lex{Student}</th><th>$lex{Student}<br>$lex{Email}</th>\n};
		    print qq{<th>$lex{Parent} 1<br>$lex{Email}</th>};
		    print qq{<th>$lex{Parent} 2<br>$lex{Email}</th></tr>\n};
		    
		    $first = 0;
		}

		print qq{<tr><td class="ra"><b>$lastname</b>, $firstname ($studnum)</td>\n};

		# NOTE: parent 1 is 1, parent 2 is 2 and student is 3 in
		# the values below prepended with studnum

		print qq{<td>};
		if ( $email and $studmail ) {
		    print qq{ <input type="checkbox" name="$studnum:3" value="1" $checked> $email};
		}
		print qq{</td><td>};
		
		if ( $par1_email and $par1mail ) {
		    print qq{ <input type="checkbox" name="$studnum:1" value="1" $checked>};
		    print qq{$par1_email};
		}
		print qq{</td><td>};
		
		if ( $par2_email and $par2mail ) {
		    print qq{<input type="checkbox" name="$studnum:2" value="1" $checked>};
		    print qq{$par2_email};
		}
		print qq{</td></tr>\n};
	    } # end of student loop
	    print qq{</table>\n};
	} # end of group (grade or homeroom value)
    } # end of all homerooms or grades.


    # Print Submit Row
    print qq{<br clear="left">\n};
    print qq{<p><input type="submit" value="$lex{'Continue'}"></p>\n};
    
    print qq{</form></body></html>\n};
    
    exit;

}


#-------------
sub showReport { 
#-------------

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

    # Get Staff Member's Email
    my $userid = $ENV{'REMOTE_USER'};
    my $sth = $dbh->prepare("select firstname, lastname, emailwork from staff where userid = ?");
    $sth->execute( $userid );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my ($firstname, $lastname, $staffemail) = $sth->fetchrow;
    if ( not $staffemail ) {
	print qq{<h3>No Work Email Address Found. Please add to staff record</h3>\n};
    }

    print qq{<h3>Staff Member $firstname $lastname - $staffemail</h3>\n};

    
    # NOTE: parent 1 is 1, parent 2 is 2 and student is 3 in
    # the values
    my %emailmap = ( 1 => 'par1_email', 2 => 'par2_email', 3 => 'email' );

    my @email; # emails to send
    foreach my $key (keys %arr ) {
	
	my ($studnum, $index) = split(':', $key);
	my $field = $emailmap{$index};
#	print "Field:$field Index:$index SN:$studnum
	
	my $sth = $dbh->prepare("select $field from student where studnum = ?");
	$sth->execute( $studnum );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
        my $emailaddress = $sth->fetchrow;
	push @email, $emailaddress;
    }

   
    my $em = join(',',@email);

    print "<div>Email To: $em</div>\n";
    
    print qq{<div style="font-size:150%;margin:1em;">};
    print qq{[ <a href="mailto:$staffemail?bcc=$em" target="_blank">Send Email</a> ]</div>\n};


# Example: print qq{<td><a href="mailto:$r{email}?subject=SSSV%20Confirmation&body=Dear%20$r{firstname}%2C%20%0D%0AYour%20password%20is%20$r{password}." target="_blank">Email Confirmation</a></td>};

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

} # end of showReport


=head

#--------------------
sub selectReceipients {
#--------------------

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

    print qq{<p><form action="$self" method="post">\n};
    print qq{<input type="hidden" name="check" value="1">\n};
    print qq{<input type="submit" value="Check all Contacts"></form></p>\n};
    
    my $checked;
    if ( $arr{check} ) {
	$checked = qq{checked="checked"};
    }
    delete $arr{check};


    my $dbtype = 'mysql';
    my %email;

    # open passed database and get student info.
    my $dsn = "DBI:$dbtype:dbname=$dbase";
    my $dbh = DBI->connect($dsn,$user,$password);
    $dbh->{mysql_enable_utf8} = 1;


    my $sth = $dbh->prepare("select * from member where lastname is not NULL 
        and lastname != '' order by lastname, firstname");
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	$sth->execute;
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $count = 1;

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

	    my %r = %$ref;
	    if ( not $r{email} ) { next; }
	    $email{$r{email}} = {'lastname' => $r{lastname}, 
				 'firstname' => $r{firstname}, 
				 db => $db, 
				 'id' => $r{id} };
	}



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

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

    my $count = 1;
    
    # Sort by db;
    my %sorted;
    foreach my $em ( keys %email ) {
	my $ln = $email{$em}{lastname};
	my $fn = $email{$em}{firstname};
	my $db = $email{$em}{db};
	$sorted{"$db$ln$fn"} = $em;
#	print qq{LN:$ln FN:$fn DB:$db<br>\n};

    }

    foreach my $key ( sort keys %sorted ) {
	my $em = $sorted{$key};
	my %r = %{ $email{$em}};

	print qq{<tr><td class="la">$count. <input type="checkbox" name="$em" value="1" $checked> \n};
	print qq{<b>$r{lastname}</b>, $r{firstname}</td></tr>\n};

	$count++;

    }

    print qq{<tr><td class="la"><input type="submit" value="Continue"></td></tr>\n};

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

    exit;
}

=cut
