#!/usr/bin/perl

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

use Getopt::Std;
getopts('tm:'); # test, months
our($opt_m,$opt_t); # warn $opt_m; exit;

use strict;
use warnings;

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

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

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 $duration = $opt_m || 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 ) { # p @row; next;
    push @data, join ': ', @row;
}

{ # HTS myeloid tests:
    my $sql = $sql_lib->retr('ncg_hts');
    my $i   = $dbix->query( $sql, $duration )->list || 0;
    push @data, "HTS myeloid: $i";
} # p @data;

# 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;
} # p %mail; exit;

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