#!/usr/bin/perl

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

use strict;
use warnings;

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

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

BEGIN {
    use FindBin qw($Bin); # warn $Bin;
    use lib (
        "$Bin/../../../lib",
        '/home/raj/perl5/lib/perl5',
    );
}

use Data::Dumper;
use LIMS::Local::ScriptHelpers;
use Spreadsheet::WriteExcel::Simple;

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

#-------------------------------------------------------------------------------
my $today    = $tools->time_now->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);
