#!/usr/bin/perl

=begin -------------------------------------------------------------------------
emails list of cases registered during previous week for all locations
=cut ---------------------------------------------------------------------------

use strict;
use warnings;

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

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

use lib '/home/raj/perl5/lib/perl5';
use Data::Dumper;

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 $date    = $tools->time_now->dmy;
my $subject = "Cases registered week ending $date";
#-------------------------------------------------------------------------------

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

my $query = $sql_lib->retr('cases_registered');
    
my $result = $dbix->query($query, $duration);

my @rows;
while (my $ref = $result->array) { # warn Dumper $vars; next;
    push @rows, $ref;
}

my $msg = join "\n", map {
	sprintf "%-10s %-12s %-15s %-12s %-12s %s", map $_ ||= 'NULL', @{$_};
} @rows; # print $msg; exit;

my %mail = (		
	config  => $config,
	message => $msg,
	subject => $subject, 	
); # warn Dumper \%mail;

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