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

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

my $self = 'emailStudent.pl';


# my $sssvmail = "SummerSchoolfortheSoloVoice\@gmail.com";


eval require "../etc/admin.conf.root";
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;

# Load configuration values of interest
my $sth = $dbh->prepare("select datavalue from conf_system where dataname = ?");
foreach my $dv ( qw( doctype tchcss tchpage )) {
    $sth->execute($dv);
    my $datavalue = $sth->fetchrow;
    eval $datavalue;
    if ( $@ ) {
	print "Error: $@<br>\n";
	die "Error: $@\n";
    }
}

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} ) {
    showStartPage();

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

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


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

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

    # find who to email for each student.
    my @emailwho;
    foreach my $key ( keys %arr ) {
	if ( $key eq 'emailstudent' ) { 
	    push @emailwho, 'email';
	    delete $arr{$key};
	} elsif ( $key eq 'emailpar1' ) { 
	    push @emailwho, 'par1_email'; 
	    delete $arr{$key};
	} elsif ( $key eq 'emailpar2' ) { 
	    push @emailwho, 'par2_email'; 
	    delete $arr{$key};
	}
    }

    if ( not @emailwho ) {
	print qq{<h3>No Email Recipients Selected!</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    # foreach my $key (keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    
    # Get teacher's email address.
    my $userid = $ENV{'REMOTE_USER'};
    my $sth = $dbh->prepare("select email from staff where userid = ?");
    $sth->execute($userid);
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my $tchEmail = $sth->fetchrow;

    my $sth = $dbh->prepare("select * from studentall where studnum = ?");
    my %email; # list of all emails to send to.
    
    foreach my $studnum ( sort {$a <=> $b} keys %arr ) {
	# Get the student record
	$sth->execute($studnum);
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;
	my %r = %$ref;

	foreach my $field ( @emailwho ) {
	    $email{ $r{$field} } = 1;
	    print "Field:$field Email:$r{$field}<br>\n";
	}
    }
    
    my $em = join(',',keys %email);

    print qq{[ <a href="mailto:$tchEmail?bcc=$em" target="_blank">Send Email</a> ]\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


#-------------
sub showReportOLD { 
#-------------

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

    # open passed database
    my $dbtype = 'mysql';
    my $dbase = $arr{db};
    my $dsn = "DBI:$dbtype:dbname=$dbase";
    my $dbh = DBI->connect($dsn,$user,$password);
    $dbh->{mysql_enable_utf8} = 1;
    delete $arr{db};


    my $combineemail = $arr{combineemail};
    delete $arr{combineemail};

    my $first = 1;
    my $count = 1;

    my $sth = $dbh->prepare("select * from student where id = ?");

    if ( $combineemail ) { 
	print '[ <a href="mailto:'. $sssvmail. '?bcc=';
	foreach my $id ( keys %arr ) {
	    $sth->execute($id);
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my $ref = $sth->fetchrow_hashref;
	    my %r = %$ref;

	    if ( not $r{email} ) { next; }
	    if ( not $first ) { print q{,}; } else { $first = 0; }
	    print qq{$r{firstname} $r{lastname} <$r{email}>};
	}
	print '" target="_blank">Send Combined Email</a> ]';

    } else {

	foreach my $id ( keys %arr ) {
	    $sth->execute($id);
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my $ref = $sth->fetchrow_hashref;
	    my %r = %$ref;

    
	    if ( $first ) { # print header
		print qq{<table cellspacing="0" border="1" cellpadding="3">\n};
		print qq{<tr><th>Name</th><th>Email</th><th>Email Link</th><th>Password</th></tr>\n};
		$first = 0;
	    }

	    print qq{<tr><td class="la">$count. <b>$r{lastname}</b>, $r{firstname}</td><td>$r{email}</td>};
	    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{<td>$r{password}</td></tr>\n};

	    $count++;

	}

	print qq{</table>\n};
    }

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

} # end of showReportOLD




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


    # Get the userid and then homerooms and/or courses.
    my $userid = $ENV{'REMOTE_USER'};

    # Get homerooms, if any
    my @homerooms;
    my $sth = $dbh->prepare("select field_value from staff_multi 
       where userid = ? and field_name = 'homeroom'");
    $sth->execute($userid);
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $homeroom = $sth->fetchrow ) {
	push @homerooms, $homeroom;
    }

    # Get Courses;
    my %courses;
    my $sth = $dbh->prepare("select * from subject where teacher = ?");
    $sth->execute($userid);
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;
	$courses{"$r{startrptperiod}$r{description}$r{subjsec}"} = $ref;
    }

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

    print qq{<div><input type="submit" value="Continue"></div>\n};
    
    my $first = 1;
    
    # Homerooms
    if ( @homerooms ) {
	print qq{<table cellpadding="3" cellspacing="0" border="0" };
	print qq{style="float:left;border:1px solid gray;margin:0.5em;">\n};
	print qq{<tr><th>Select Homeroom</th></tr>\n};

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

    if ( @homerooms and %courses ) { # OR
	print qq{<div style="float:left;font-weight:bold;margin:1em;">OR</div>\n};
    }
    

    # Courses
    if ( %courses ) {
	print qq{<table cellpadding="3" cellspacing="0" border="0" };
	print qq{style="float:left;border:1px solid gray;margin:0.5em;">\n};
	print qq{<tr><th>Select Course</th></tr>\n};

	foreach my $key ( sort keys %courses ) {
	    my %r = %{ $courses{$key}};
	    print qq{<tr><td><input type="checkbox" name="C:$r{subjsec}" value="1">};
	    print qq{$r{description} ($r{subjsec})</td></tr>\n};
	}
	print qq{</table>\n};
	$first = 0;
    }

    if ( $first ) {
	print qq{<h3>No Homerooms or Courses Found!</h3>\n};
    } 

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

    print qq{<tr><td><input type="checkbox" name="emailstudent" value="1">Email Student</td></tr>\n};
    print qq{<tr><td><input type="checkbox" name="emailpar1" value="1">Email Parent 1</td></tr>\n};
    print qq{<tr><td><input type="checkbox" name="emailpar2" value="1">Email Parent 2</td></tr>\n};
    print qq{</table>\n};

    
    # Check Next Page?
    print qq{<div>Check Next Page of Students? <input type="checkbox" name="check" value="1"></div>\n};
    

    if ( not $first ) {
	print qq{<br clear="left"><input type="submit" value="Continue">\n};
    }
    
    print qq{</form>\n};
    print qq{</body></html>\n};

    exit;

}


#-----------------
sub selectStudents {
#-----------------

    # foreach my $key (sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    # Passed Homeroom and/or Courses;
    
    my $checked;
    if ( $arr{check} ) {
	$checked = qq{checked="checked"};
    }
    delete $arr{check};

    # Check for courses/homeroom
    my (@homerooms, @courses);
    foreach my $key ( keys %arr ) {
	my ($type,$val ) = split(':', $key);
	if ( $val ) {
	    if ($type eq 'C') {
		push @courses, $val;

	    } elsif ( $type eq 'H' ) {
		push @homerooms, $val;
	    }
	    delete $arr{$key};
	}
    }

    # only up to 3 email recipients left in %arr; pass these in hidden form values.
#    print "ARR:", %arr, "<br>\n";
#    print "Courses:@courses<br>\n";
#    print "Homeroom:@homerooms<br>\n";

    
    my %students; # collect student numbers (studnum)
    
    if ( @courses ) {
	my $sth = $dbh->prepare("select distinct studnum from eval where subjcode = ?");

	foreach my $subjsec ( @courses ) {
    	    $sth->execute( $subjsec );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    while ( my $studnum = $sth->fetchrow ) {
		$students{$studnum} = 1;
	    }
	}
    }

    if ( @homerooms ) {
	my $sth = $dbh->prepare("select studnum from student where homeroom = ?");

	foreach my $homeroom ( @homerooms ) {
    	    $sth->execute( $homeroom );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    while ( my $studnum = $sth->fetchrow ) {
		$students{$studnum} = 1;
	    }
	}
    }

    # now have all students in %students hash.

    # Create a sort hash and hash to hold name.
    my (%sort,%name);
    
    my $sth = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");

    foreach my $studnum ( keys %students ) {
	$sth->execute( $studnum );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname) = $sth->fetchrow;
	$sort{"$lastname$firstname$studnum"} = $studnum;
	$name{$studnum} = qq{<b>$lastname</b>, $firstname};
    }
    

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

    foreach my $key ( keys %arr ) { # put in who to email (emailstudent,emailpar1, emailpar2)
	print qq{<input type="hidden" name="$key" value="1">\n};
    }

    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th>Select Students</th></tr>\n};
    print qq{<tr><td class="la"><input type="submit" value="Continue"></td></tr>\n};

    my $count = 1;
    
    foreach my $key ( sort keys %sort ) {
	my $studnum = $sort{$key};

	print qq{<tr><td class="la">$count. <input type="checkbox" name="$studnum" value="1" $checked> \n};
	print qq{$name{$studnum} ($studnum)</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;
}
