#!/usr/bin/perl

=begin -------------------------------------------------------------------------
emails XL list of specified trial cases every quarter 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 rawstron hillmen raj bagguley );
################################################################################

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

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

my $cfg_file = "$Bin/../lib/settings.cfg"; 
my $settings = Config::Auto::parse($cfg_file); # warn Dumper $settings;
my $trials   = $settings->{invoiced_trials}; # warn Dumper $trials;

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

#-------------------------------------------------------------------------------
my $duration = 3; # months # ***** needs to match entry in library.sql *****

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

my $subject  = sprintf 'Trial cases for %s.%s to %s.%s',
	$start->month_abbr, $start->year, $end->month_abbr, $end->year; # warn $subject; exit;
my $filename = 'trial_cases.xls';

# xl file headers:
my @headers = qw( request_number year trial_name presentation registered specimen );
#-------------------------------------------------------------------------------

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

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

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

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

# 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) {
	my $xl = Spreadsheet::WriteExcel::Simple->new;
	$xl->write_bold_row(\@headers);
	$xl->write_row($_) for @data; # $xl->save("trial_cases.xls"); exit;
	
	$mail{attachment} = $xl->data;
    $mail{filename}   = $filename;	
}
else {
	$mail{message} = sprintf 'No trial cases for 3 months to %s.%s',
        $end->month_abbr, $end->year;
} 

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