#!/usr/bin/perl

=begin -------------------------------------------------------------------------
sends a list of requests (non-trial) where referrer or source unknown
runs weekly, and on 1st day of month (substitutes 7 day for 1 month in sql)
=cut ---------------------------------------------------------------------------

use strict;
use warnings;

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

#-------------------------------------------------------------------------------
my @recipients = qw(douglas sinclair bagguley raj); # for non-secure info
#-------------------------------------------------------------------------------

use lib '/home/raj/perl5/lib/perl5';
use Data::Dumper;
use DateTime::Format::MySQL;

use FindBin qw($Bin); # warn $Bin;
use lib $Bin . '/../../../lib';
use LIMS::Local::ScriptHelpers;

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

my $cfg_file = "$Bin/../lib/settings.cfg";
my $settings = Config::Auto::parse($cfg_file); # warn Dumper $settings;

# get tools from LIMS::Local::ScriptHelpers:
my $sql_lib = $tools->sql_lib();
my $config  = $tools->config(); 
my $dbix    = $tools->dbix();

my $today = $tools->time_now();

# organisation codes NOT required in activity data:
my $skip_orgs = $settings->{skip_organisation_codes}; # warn Dumper $skip_orgs;

my $query = $sql_lib->retr( 'national_code_unknown' );

# email subject line:
my $subject = 'Unknown national codes for '; # duration appended below
my $duration; # days or months - set below:

# check date - if 1st of month, change '7 day' to '1 month' in query:
if ($today->day == 1) {
	$query =~ s/(INTERVAL \?) DAY/$1 MONTH/;
	$duration = 1; # months
    
    my $yesterday = $tools->date_subtract( days => 1 );
    $subject .= join '.', $yesterday->month_abbr, $yesterday->year;
}
else {
	$duration = 7; # days
    $subject .= 'week ending ' . $today->dmy('.');
}

my $result = $dbix->query($query, $duration);

my @rows;
while (my $vars = $result->hash) { # warn Dumper $vars; next;
    my $lab_no = sprintf '%s%s/%s',
        $config->{lab_number_prefix},
        $vars->{request_number},
        $vars->{year} - 2000;

    my $row = sprintf '%-10s %-12s %s',
        $lab_no,
        DateTime::Format::MySQL->parse_datetime($vars->{created_at})->dmy,
        $vars->{display_name};

    $row .= ' [WILL NOT BE BILLED]' if
        grep { $vars->{organisation_code} eq $_ } @$skip_orgs;

    push @rows, $row;
}

my $message_body = @rows
    ? ( join "\n", @rows )
    : 'No unknown national codes';

my %mail = (		
	config  => $config,
	message => $message_body,
	subject => $subject, 	
); # warn Dumper \%mail; # next;
    
$tools->send_mail(\%mail, \@recipients);
