#!@PERL@

use strict;
use warnings;

use lib '@CGIBINDIR@';
use civs_common;
use CGI qw(:standard -utf8);
$CGI::POST_MAX = @MAX_UPLOAD_SIZE@;

use Digest::MD5 qw(md5_hex);
use DB_File;
use URI::Escape;

use Socket;
use IO::Handle;
use election;

my $thisurl = $civs_bin_path."/add_voters@PERLEXT@";

my $activate_url = "@PROTO@://".$thishost.$civs_bin_path."/opt_in@PERLEXT@";
my $mail_mgmt_url = "@PROTO@://".$thishost.$civs_bin_path."/mail_mgmt@PERLEXT@";

my $new_addresses = param('new_addresses');
my $new_addresses_file = upload('new_addresses_file');
my $resend = (param('resend') || 'no') eq 'yes';
my @errors = ();

if ($new_addresses_file &&
    VerifyUpload($new_addresses_file, \@errors, "file of voter addresses")) {
    while (<$new_addresses_file>) {
        $new_addresses .= "\n" . $_;
    }
}
my @new_addresses = split /[\r\n]+/, $new_addresses;

HTML_Header($tx->CIVS_Adding_Voters, 'add_voters.js');
CIVS_Header($tx->Adding_voters);

my $control_key = param('key');
CheckControlKey($control_key);
my $authorization_key = param('akey');
CheckAuthorizationKeyForAddingVoter($authorization_key);

if (!IsStarted || IsStopped) {
    print h1($tx->Error),
	p($tx->Sorry_voters_can_only_be_added_to_poll_in_progress);
    exit 0;
}

if ($#new_addresses >= @MAX_VOTER_ADD@) {
    push @errors, li($tx->Too_many_voters_added);
}
if (GetEmailLoad(time()) >= @MAX_EMAIL_LOAD@) {
    push @errors, $tx->Too_much_email;
}

if ($#errors >= 0) {
    print h1($tx->Error), ul(@errors);
    exit 0;
}

GetPrivateHostID;

# Send all of the voters their keys
my @mail_failures = @{SendKeys($authorization_key, \@new_addresses, $resend)};

$num_auth = $num_auth || 0;

print p($tx->Total_of_x_voters_authorized($num_auth)), $cr;

if ($#mail_failures >= 0) {
    print p($tx->see_the_failure_table($activate_url, $mail_mgmt_url)), $cr;
}

my $url = "$civs_bin_path/control@PERLEXT@?id=$election_id&key=$control_key";
$url .= "&akey=$authorization_key" if defined($authorization_key);
print p("<a href=\"$url\">", $tx->Go_back_to_poll_control, '</a>'), $cr;

my (@not_activated, @opted_out);

if ($#mail_failures >= 0) {
    my @rows = Tr(th($tx->Address), th($tx->Reason));
    foreach my $rowref (@mail_failures) {
        my ($failure_type, $addr) =  @{$rowref};
        push @rows, Tr(td($addr), td($tx->mail_failure_reason($failure_type, $addr)));
        if ($failure_type eq 'not activated') {
            push @not_activated, $addr;
        } elsif ($failure_type eq 'opted_out') {
            push @opted_out, $addr;
        }
    }
    print div({-class => "centering"}, div({-id => 'mail_failures'},
        button(-id => 'download_failures', -value => $tx->download_failures,
               -onclick => 'export_failure_table()'), $cr,
        button({
            -value => $tx->Email_voters_who_have_not_activated,
            -onclick => 'document.forms.email_not_activated.submit()'
        }), $cr,
        table({-id => 'failure_table'}, @rows)));
    print start_form(
        {
            -name => 'email_not_activated',
            -method => 'POST',
            -action => 'mailto:' . uri_escape_utf8(join(',', @not_activated))
                                    . '?subject=' . uri_escape_utf8($tx->Activate_mail_subject)
                                    . '&body=' . uri_escape_utf8($tx->Activate_mail_body($email_addr, $name, $title, $activate_url)),
            -accept_charset => 'UTF-8'
        }), $cr,
    end_form(), $cr,
}

print end_html();
Log("$num_auth new voters added to $title ($election_id)");

exit 0;
