#!/usr/bin/perl

=begin -------------------------------------------------------------------------
unscreened requests > 2 working days after registration
=cut ---------------------------------------------------------------------------

use strict;
use warnings;

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

################################################################################
my @recipients = qw( douglas bagguley raj );
my $duration = 2; # how many working days since registration 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 $str = '%-8s %s %-8s %s %s';
my @rows = sprintf "$str\n", qw(LabNo Registered Specimen Days Source);

my $query = $sql_lib->retr('unscreened_requests');
my $result = $dbix->query($query);

while (my $vals = $result->hash) { # warn Dumper \@vals;
	# calculate working days since registration (delta):
    my $from  = DateTime::Format::MySQL->parse_date($vals->{registered})->ymd;
	my $to    = $tools->time_now->ymd;
	
	my $delta = $vals->{delta}
		= LIMS::Local::Utils::delta_business_days($from, $to);	
	next unless $delta > $duration; # warn $delta;
	
    my $row = sprintf $str,
		@{$vals}{ qw(labno registered specimen delta location) };
    push @rows, $row;
} # warn Dumper \@rows;

my %mail = (		
	config  => $config,
    subject => "Requests > $duration days unscreened",
    message => join "\n", @rows,
); # warn Dumper [\%mail, \@recipients]; exit;

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