#!/usr/bin/perl

=begin -------------------------------------------------------------------------
emails details of NCG PNH cases screened, every 3 months, to specified recipients
=cut ---------------------------------------------------------------------------

use strict;
use warnings;

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

############ usernames from users table #######################################
my @recipients = qw( blythe raj );
################################################################################

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

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 $duration = 3; # months

my $start = $tools->date_subtract( months => $duration ); # date 3 months ago
my $end   = $tools->date_subtract( days => 1 ); # yesterday

my $subject = sprintf 'HMDS NCG PNH cases for %s.%s to %s.%s',
	$start->month_abbr, $start->year, $end->month_abbr, $end->year; # warn $subject; exit;
#-------------------------------------------------------------------------------

my $sql_lib = $tools->sql_lib();
my $config  = $tools->config(); 
my $dbix    = $tools->dbix();

# get SQL statements for query:
my $sql = $sql_lib->retr('ncg_pnh');

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

my @data;
while ( my @row = $result->list ) { # warn Dumper \@row; next;
    push @data, join ': ', @row;
}

# flag to Local::Mail::_verify_service_status() that msg safe to send:
$config->{_safe_message} = 1 if ! $config->{is_in_production_mode};

my %mail = (		
	config  => $config,
	subject => $subject,
); 

if (@data) {
	$mail{message} = join "\n", @data;
}
else {
	$mail{message} = 'No NCG PNH cases for 3 months to ' . $end->dmy;
} # warn Dumper \%mail; exit;

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