#!/usr/bin/env perl

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

use strict;
use warnings;

use Getopt::Std;
getopts('d:t'); # days, testing
our($opt_d,$opt_t); # warn $opt_d; exit;

# emails only 'service_email' addr in config
my $JUST_TESTING = $opt_t || 0;  # email to ra.jones only

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

use lib '/home/raj/perl5/lib/perl5';
use Data::Printer;

use FindBin qw($Bin); # warn $Bin;
use lib $Bin . '/../../../lib';
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 @trial = my @non_trial
    = 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) { # p $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} =~ /Outreach/;

	my @fields = qw( labno delta location presentation );
    if ( $ref->{trial_case} ) { # boolean 1 or undef
        push @trial, sprintf "%-10s | %s | %s :: %s", @{$ref}{@fields};
    }
    else {
        push @non_trial, sprintf "%-10s | %s | %s :: %s", @{$ref}{@fields};
    }
} # p @trial; p @non_trial;

{
    my $subject = sprintf 'Non-trial requests >%s days unreported [%s]',
        $duration, scalar @non_trial;
    my %mail = (
        config  => $config,
        subject => $subject,
        message => join "\n", @non_trial,
    ); # p %mail;
    $tools->send_mail(\%mail, \@recipients);
}
{
    my $subject = sprintf 'Clinical trial requests >%s days unreported [%s]',
        $duration, scalar @trial;
    my %mail = (
        config  => $config,
        subject => $subject,
        message => join "\n", @trial,
    ); # p %mail;
    $tools->send_mail(\%mail, \@recipients);
}
