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

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

my %lex = ('Select' => 'Select',
	   'Lastname, Firstname' => 'Lastname, Firstname',
	   'Homeroom, Lastname, Firstname' => 'Homeroom, Lastname, Firstname',
	   'Grade, Lastname, Firstname' => 'Grade, Lastname, Firstname',
	   'Sort by' => 'Sort by',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Continue' => 'Continue',
	   'Error' => 'Error',
	   'Separate with Spaces' => 'Separate with Spaces',

	   'Parent' => 'Parent',
	   'Student' => 'Student',
	   'Email' => 'Email',
	   'Next Page' => 'Next Page',
	   'Check' => 'Check',
	   
	   
	   
	);




my $self = 'rptemail.pl';


# Get current dir so know what path for config files.
my $teachermode;
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $teachermode = 1;
}

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);

# Load configuration values of interest
my $sth = $dbh->prepare("select datavalue from conf_system where dataname = ?");
foreach my $dv ('doctype','css','homepage','tchcss','tchpage','charset') {
    $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;


if ( $teachermode ) { # running on teacher site
    $css = $tchcss;
    $homepage = $tchpage;
}


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

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


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

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

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



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

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

    my $myemail = $arr{myemail};
    if ( not $myemail ) {
	print qq{<h3>Missing Your Email Address</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    delete $arr{myemail};
    
    my $selStudent = $arr{selStudent};
    delete $arr{selStudent};

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

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

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

    
    # $checked is already defined at top, if selected in startpage.
    # only groups left in %arr now.

    my (%sort, %student, @grp);# list of the groups (homeroom or grade)
    foreach my $key ( keys %arr ) {
	my ($group, $val) = split(':', $key);
	push @grp, $val;
	
	my $sth;
	if ( $group eq 'G' ) {
	    $sth = $dbh->prepare("select lastname, firstname, studnum, grade, homeroom, 
               email, par1_email, par2_email from student where grade = ?");
	    $sth->execute( $val );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

	} else { # homeroom
	    $sth = $dbh->prepare("select lastname, firstname, studnum, grade, homeroom,
               email, par1_email, par2_email from student where homeroom = ?");
	    $sth->execute( $val );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	}

	# Loop through the students
	while ( my $ref = $sth->fetchrow_hashref ) {
	    my %r = %$ref;
	    $sort{"$r{lastname}$r{firstname}$r{studnum}"} = $r{studnum};
	    $student{$r{studnum}} = $ref;
	}
    }

    my $desc = join(',', sort @grp);
    print qq{<h3>Student Group $desc</h3>\n};
    

    # Setup the form and start of table.
    print qq{<form action="$self" method="post" enctype="multipart/form-data">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="hidden" name="myemail" value="$myemail">\n};

=head    
    # Start table.
    print qq{<table cellpadding="3" border="0" cellspacing="0" style="float:left;margin:0 1em;">\n};

    # Entry Values
    print qq{<tr><td class="bla">$lex{Subject} <input type="text" name="subject" style="width:30em;">};
    print qq{</td></tr>\n};

    print qq{<tr><td class="bla">$lex{Message} Format <select name="messageformat">};
    print qq{<option value="html">HTML</option><option value="text">Text</option></select></td></tr>\n};
    
    print qq{<tr><td class="bla">$lex{Message}<br><textarea name="message" rows="10" cols="60">};
    print qq{</textarea></td></tr>\n};

    print qq{<tr><td class="bla">$lex{'Attach File'} <input type="file" name="filename"></td></tr>\n};

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

    print qq{<div style="margin:0.5em;"><input type="submit" value="$lex{Continue}"></div>\n};
    
    print qq{<table cellpadding="3" border="1" cellspacing="0">\n};
    
    my $first = 1;
    foreach my $key ( sort keys %sort ) {
	my $studnum = $sort{$key};
	my %r = %{$student{$studnum}};
	
	if ( $first ) {
	    print qq{<tr><th>$lex{Student}</th><th>Gr/HR</th><th>$lex{Student}<br>$lex{Email}</th>\n};
	    print qq{<th>$lex{Parent} 1<br>$lex{Email}</th><th>$lex{Parent} 2<br>$lex{Email}};
	    print qq{</th></tr>\n};


	    $first = 0;
	}

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

	# Grade / Form / Homeroom
	my $gr = $r{grade};
	if ( $schoolmode == 1 ) {
	    my $val = $g_FormMap{$gr};
	    if ( not $val ) { $val = $gr; }
	    if ( $val =~ m/F|f/ ) { # we are adding form.
		$val =~ s/F|f/Frm/;
	    }
	    $gr = $val;
	}
	print qq{<td>$gr};
	if ( $r{homeroom} ) { print qq{,$r{homeroom}}; }
	print qq{</td>};
	

	print qq{<td>};
	if ( $r{email} and $selStudent ) {
	    print qq{ <input type="checkbox" name="$studnum:S:$r{email}" value="1" $checked> $r{email}};
	}
	
	print qq{</td><td>};
	
	if ( $r{par1_email} and $selPar1 ) {
	    print qq{ <input type="checkbox" name="$studnum:P1:$r{par1_email}" value="1" $checked>};
	    print qq{$r{par1_email}};
	}
	
	print qq{</td><td>};
	
	if ( $r{par2_email} and $selPar2 ) {
	    print qq{<input type="checkbox" name="$studnum:P2:$r{par2_email}" value="1" $checked>};
	    print qq{$r{par2_email}};
	}
	print qq{</td></tr>\n};
    }

    print qq{</table>\n};
    print qq{<div style="margin:0.5em;"><input type="submit" value="$lex{'Continue'}"></div>\n};
    
    print qq{</form></body></html>\n};
    
    exit;

}


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

    # foreach my $key (sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    my $myemail = $arr{myemail};
    delete $arr{myemail};
    $myemail =~ s/@/\@/; # escape the @ symbol. 
    
    my %emails;
    foreach my $key ( sort keys %arr  ) {
	my ($sn,$fld,$mail) = split(':', $key);
	$emails{$mail} = 1;
    }

    my $ecount = scalar keys %emails;
        
    my $em = join(',',keys %emails);

    my $elength = length($em);

    print qq{<div>Emails added: $ecount  Length:$elength characters</div>\n};
    

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


    # 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" cellspacing="0" border="0" };
    print qq{style="margin-bottom:0.4em; border:1px solid gray;padding:0.3em;">\n};

    # Sender Email
    print qq{<tr><td class="bra">Your Email Address</td>};
    print qq{<td class="la"><input type="text" style="width:30ch;" name="myemail"></td></tr>\n};

    
    # Grades
    print qq{<tr><td class="bra">$lex{Select} $lex{Grade}};
    if ( $schoolmode == 1 ) {
	print qq{/$lex{Forms}};
    }
    print qq{</td>};
    print qq{<td class="la">};
    
    foreach my $gr ( sort {$a <=> $b} @grades ) {
	my $displaygrade = $gr;
	if ( $schoolmode == 1 ) { # British mode
	    my $val = $g_FormMap{$gr};
	    if ( not $val ) { $val = $gr; }
	    if ( $val =~ m/F|f/ ) { # we are adding form.
		$val =~ s/F|f/$lex{Form} /;
	    }
	    $displaygrade = $val;
	}
	print qq{<input type="checkbox" name="G:$gr" value="1">$displaygrade };
    }
    print qq{</td></tr>\n};

   
    print qq{<tr><td class="bra">$lex{OR}</td><td></td></tr>\n};
    
    # Homeroom
    print qq{<tr><td class="bra">$lex{Select} $lex{Homeroom}</td>};
    print qq{<td class="la">\n}; 
    foreach my $hr ( sort {$a <=> $b} @homerooms ) {
	print qq{<input type="checkbox" name="H:$hr" value="1">$hr };
    }
    print qq{</td></tr>\n};

    print qq{<tr><td colspan="2" style="border-bottom:1px solid gray"></td></tr>\n};

    # Select which emails
    print qq{<tr><td class="bra">$lex{Select} $lex{Email}</td><td class="la">\n};
    print qq{<input type="checkbox" name="selStudent" value="1"> };
    print qq{<b>$lex{Student}<br>\n};

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

    print qq{<input type="checkbox" name="selPar2" value="1"> };
    print qq{ $lex{Parent} 2</b></td></tr>\n};

    print qq{<tr><td colspan="2" style="border-bottom:1px solid gray"></td></tr>\n};
    
    # Check next page?
    print qq{<tr><td class="bra">$lex{Check} $lex{'Next Page'}?</td><td class="la">\n};
    print qq{<input type="checkbox" name="checked" value="checked"></td></tr>\n};

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

}
