#!/usr/bin/perl

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

use strict;
use warnings;

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

############ recipients from contacts.lib ######################################
my @recipients = qw( lynda.blythe.secure raj.secure sarah.bagguley.secure );
my $duration = 7; # over past number of days (but using YEARWEEK in query)
################################################################################

BEGIN {
    use FindBin qw($Bin); # warn $Bin;
    use lib (
        "$Bin/../../../lib",
        '/home/raj/perl5/lib/perl5',
    );
}

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

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

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

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

my $yml = $tools->get_yaml_file('nhs_number_exempt'); # warn Dumper $yml; exit;

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

my $query = $sql_lib->retr('null_nhs_number');
    
my $exempt = $yml->{clinical_trial}; # array of trial-names

my $result = $dbix->query($query, @$exempt);    
    
while (my $ref = $result->array) { # warn Dumper $ref; next;
    push @rows, $ref;
}

exit unless scalar @rows > 1; # warn Dumper \@rows; exit;

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;
    
$tools->send_mail(\%mail, \@recipients);
