#!/usr/bin/perl

=begin -------------------------------------------------------------------------
alerts trial contact of newly registered trial cases
=cut ---------------------------------------------------------------------------

use Getopt::Std;
getopts('d:'); # days
our($opt_d); # warn $opt_d; exit;

use strict;
use warnings;

my $JUST_TESTING = 0; # email to ra.jones only

############ recipients from contacts.lib ######################################
my %trials = (
    'SCTU MaPLe'    => ['uhs.maple.secure'], # expects arrayref of recipients
    'SCTU REMoDl-B' => [
        qw(lth.remodlb.secure sharon.barrans.secure southampton.ctu.secure) ],
);

my $duration = $opt_d || 1; # days ago
################################################################################

use lib '/home/raj/perl5/lib/perl5';
use Data::Printer;

use FindBin qw($Bin); # warn $Bin;
use lib "$Bin/../../../lib";
use LIMS::Local::ScriptHelpers;

my $tools = LIMS::Local::ScriptHelpers->new();
$tools->test_only($JUST_TESTING);

# get tools from LIMS::Local::ScriptHelpers:
my $sql_lib = $tools->sql_lib();
my $config  = $tools->config();
my $dbix    = $tools->dbix();

# get date yesterday - handles BST:
my $yesterday = $tools->date_subtract(days => $duration)->dmy('/'); # warn $yesterday; exit;
# get sql statment:
my $requests = $sql_lib->retr('new_trial_cases_alert'); # p $requests;
# email message body row format:
my $row_format = "%-8s %-12s %-12s %-12s %-11s %-10s %-7s %s\n";

while ( my($trial_name, $recipients) = each %trials ) { # p $trial_name;
    my $cases = $dbix->query($requests, $duration, $trial_name)->arrays; # AoA
    if (@$cases) { # p $cases;
        no warnings 'uninitialized'; # ie missing fields
        # email subject line:
        my $subject = "$trial_name cases registered at HMDS on $yesterday";
        my $message_body = sprintf $row_format,
            qw( LabNo LastName FirstName DoB UnitNumber NHSNumber Sample Source );
        $message_body .= sprintf $row_format, @$_ for @$cases; # p $message_body;
        $recipients = [ 'raj.secure' ] if $JUST_TESTING;

        my %mail = (
            config  => $config,
            message => $message_body,
            subject => $subject,
        ); # p %mail; exit;

        $tools->send_mail(\%mail, $recipients);
    }
}
