#!/usr/bin/perl

=begin -------------------------------------------------------------------------
unreported records > 14 calendar days after registration date
=cut ---------------------------------------------------------------------------

use strict;
use warnings;

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

################################################################################
my @recipients = qw( douglas bagguley raj );
my $duration = 14; # how many calendar days since registration
################################################################################

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 @rows = sprintf "%-10s %-7s %s / %s\n", qw(LabNo Days Location Presentation);

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

RESULT:
while (my $ref = $result->hash) { # warn Dumper $ref; next;
	# skip if le x days since report:
    next RESULT if $ref->{delta} <= $duration;
	
    # put labno in brackets if Outreach:
    $ref->{labno} = ( sprintf '[%s]', $ref->{labno} )
		if $ref->{presentation} eq 'Outreach';

	my @fields = qw( labno delta location presentation );
    push @rows, sprintf "%-10s | %s | %s :: %s", @{$ref}{@fields};
} # warn Dumper \@rows;

my %mail = (		
	config  => $config,
    subject => "Request > $duration days unreported",
    message => join "\n", @rows,
); # warn Dumper \%mail;

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