#!/usr/bin/perl

=begin -------------------------------------------------------------------------
generates list of LTH patients without NHS numbers registered during past 7 days
=cut ---------------------------------------------------------------------------

use strict;
use warnings;

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

############ recipients from contacts.lib ######################################
my @recipients = qw( lynda.blythe.secure raj.secure );
my $duration = 7; # over past number of days
################################################################################

BEGIN {
    use FindBin qw($Bin); # warn $Bin;
    use lib "$Bin/../../../lib";
}

use Data::Dumper;
use LIMS::Local::ScriptHelpers;

#-------------------------------------------------------------------------------
my $date    = DateTime->today->dmy;
my $subject = "Missing NHS numbers for week ending $date";
#-------------------------------------------------------------------------------

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

my $contacts = $tools->get_contacts();
my $sql_lib  = $tools->sql_lib();
my $config   = $tools->config(); 
my $dbix     = $tools->dbix();

my @rows = [ qw(LabNo LastName FirstName DoB PatNo Date Location) ]; # col headers

my $query = $sql_lib->retr('null_nhs_number');
    
my $result = $dbix->query($query, $duration);    
    
while (my $ref = $result->array) { # warn Dumper $vars; next;
    push @rows, $ref;
}

my $msg = join "\n", map {
	sprintf "%-9s %-12s %-10s %-10s %-8s %-11s %s", map $_ ||= 'NULL', @{$_};
} @rows; # print $msg; exit;

my %mail = (		
	config  => $config,
	message => $msg,
	subject => $subject, 	
); # warn Dumper \%mail;
    
RECIPIENT:
foreach my $recipient (@recipients) {
	my $email = $contacts->{$recipient} or next RECIPIENT; # in case doesn't exist
    next RECIPIENT if $JUST_TESTING && $email !~ /ra\.jones/;
	$mail{recipient} = $email; # warn Dumper $mail{recipient}; next;

	my $rtn = LIMS::Model::Email->send_message(\%mail);
	warn "Error in $0: $rtn" if $rtn;
}

