#!/usr/bin/perl

=begin -------------------------------------------------------------------------
alerts Southampton CTU of newly registered REMoDL-B trial cases:
=cut ---------------------------------------------------------------------------

use strict;
use warnings;

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

############ recipients from contacts.lib ######################################
my @recipients = qw(
    lth.remodlb.secure
    sharon.barrans.secure
    southampton.ctu.secure
); # raj.secure

################################################################################

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

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 => 1)->dmy('/'); # warn $yesterday; exit;

# get sql statment:
my $requests = $sql_lib->retr('new_remodlb_cases_alert');
# email subject line:
my $subject = "REMoDL-B cases registered at HMDS on $yesterday";
# email message body row format:
my $row_format = "%-8s %-12s %-12s %-12s %-11s %-10s %s\n";

my $cases = $dbix->query($requests)->arrays; # AoA

if (@$cases) {
    no warnings 'uninitialized'; # ie missing fields
    my $message_body = sprintf $row_format,
        qw( LabNo LastName FirstName DoB UnitNumber NHSNumber Source );
    $message_body .= sprintf $row_format, @$_ for @$cases;
    
	my %mail = (		
		config  => $config,
		message => $message_body,
		subject => $subject, 	
	); # warn Dumper \%mail; exit;
    
    $tools->send_mail(\%mail, \@recipients);
}

