#!/usr/bin/perl

=begin -------------------------------------------------------------------------
list of requests referred to histopathology - authorised previous day
=cut ---------------------------------------------------------------------------

use strict;
use warnings;

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

################################################################################
my @recipients = qw( douglas sinclair bagguley raj );
my $duration = 1; # how many working days since authorisation date
################################################################################

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 $sql_lib = $tools->sql_lib();
my $config  = $tools->config(); 
my $dbix    = $tools->dbix();

my $query = $sql_lib->retr('histopathology_referrals');
my $result = $dbix->query($query, $duration)->hashes; # warn Dumper $result;

exit unless @$result;

my $message = join "\n", map {
    sprintf 'H%s/%s',  $_->{request_number}, $_->{year} - 2000;
} @$result;

my $date = $tools->date_subtract( days => $duration )->ymd; # warn $date;

my %mail = (		
    subject => "Histopathology referrals ($date)",
    message => $message,
	config  => $config,
); # warn Dumper \%mail; exit;

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