#!/usr/bin/perl

=begin -------------------------------------------------------------------------
emails XL list of MDS diagnoses (new & follow-up) over past week
=cut ---------------------------------------------------------------------------

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

use strict;
use warnings;

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

############ recipients from contacts.lib ######################################
my @recipients = qw( lth.trials.secure raj.secure );
my $duration = $opt_d || 7; # over past number of days
################################################################################

use lib '/home/raj/perl5/lib/perl5';
use Data::Dumper;
use Spreadsheet::WriteExcel::Simple;

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 $today    = $tools->time_now->subtract( days => $duration - 7)->dmy;
my $from     = $tools->date_subtract( days => $duration )->dmy;
my $subject  = "MDS diagnoses [$from to $today]"; # warn $subject; exit;
my $filename = 'mds.xls';

# xl file headers:
my @headers = qw( lab_number last_name first_name case_number nhs_number dob
	location diagnosis authorised status );
#-------------------------------------------------------------------------------

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

my @rows;

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

my $result = $dbix->query($query, $duration);
while (my $row = $result->array) { # warn Dumper $row; next;
    push @rows, $row;
}

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

if (@rows) {
	my $xl = Spreadsheet::WriteExcel::Simple->new;
	$xl->write_bold_row(\@headers);
	$xl->write_row($_) for @rows;

	$mail{attachment} = $xl->data;
    $mail{filename}   = $filename;
}
else {
	$mail{message} = q!No MDS/CMML diagnoses were made during this period.!;
}

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