#!/usr/bin/perl

=begin -------------------------------------------------------------------------
list of new, relapsed or all cases from variety of age ranges & diagnoses:
=cut ---------------------------------------------------------------------------

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

use strict;
use warnings;

use lib '/home/raj/perl5/lib/perl5';
use FindBin qw($Bin); # warn $Bin;
use Data::Printer;
use lib "$Bin/../../../lib";
use LIMS::Local::ScriptHelpers;

############ recipients from contacts.lib ######################################
my @recipients = map $_ . '.secure', qw(
    heather.hall
    rod.johnson
    amy.humphries
    cathy.burton
    raj
); # p @recipients;
################################################################################

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

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

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

# get date yesterday - handles BST:
my $yesterday = $tools->date_subtract(days => $delta_days)->dmy('/'); # warn $yesterday; exit;

# get sql statment:
my $sql = $sql_lib->retr('yhhn_potential_trial_cases'); # p $sql;
# email subject line:
my $subject = "Potential clinical trial cases [$yesterday]";
# template:
my $tt_file  = 'cron/potential_trial_cases.tt';

my @data = $dbix->query($sql, $delta_days)->hashes; # p @data;
exit 0 unless @data;

my @cols = qw(hmds_ref last_name first_name dob age nhs_number location
    diagnosis status);

my $message = do{
    my %args = ( data => \@data, cols => \@cols, date => $yesterday );
    $tools->process_template('cron/potential_trial_cases.tt', \%args);
};

my %mail = (
    content => 'html',
	config  => $config,
	message => $message,
	subject => $subject,
); # warn Dumper \%mail; exit;

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