#!/usr/bin/perl

=begin -------------------------------------------------------------------------
request status = complete and updated_at = yesterday
=cut ---------------------------------------------------------------------------

use strict;
use warnings;

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

################################################################################
my @recipients = qw(); # admin contact **must be nhs.net** pushed below
my $duration = 1;
################################################################################

use lib '/home/raj/perl5/lib/perl5';
use Data::Dumper::Concise;
use HTML::Template;

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 $sql_lib = $tools->sql_lib();
my $config  = $tools->config(); # warn Dumper $config->{email_from};
my $dbix    = $tools->dbix();

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

my @rows = $dbix->query($query, $duration)->hashes; # warn Dumper @rows;
exit unless @rows;

push @recipients, $config->{email_from}; # sole contact - must be nhs.net

my $html = do { local $/; <DATA> };
my $yesterday = $tools->date_subtract( days => $duration )->dmy('.');

my $template = HTML::Template->new(scalarref => \$html, loop_context_vars => 1);
$template->param( ROWS => \@rows, DATE => $yesterday );
my $message_body = $template->output(); # warn $message_body;

my %mail = (		
    subject => 'Request status complete',
    message => $message_body,
    content => 'html',
	config  => $config,
); # warn Dumper [\%mail, \@recipients]; exit;

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

__DATA__
<html>
  <head>
    <title>Request Status Complete</title>
    <style>
        html { font-family: verdana, sans-serif; }
        h2 { color: #800000; }
        table { border-collapse: collapse; margin-left: 1em }
        td, th { border: solid 1px #c0c0c0; padding: 2px; font-size: 9pt; }
        #head { background-color: ActiveCaption; color: CaptionText; }
    </style>
  </head>
  <body>
    <h2>Request status complete on <!-- TMPL_VAR NAME=DATE --></h2>
    <table>
       <tr id="head">
          <th>ReqNum</th>
          <th>Year</th>
          <th>Name</th>
          <th>DoB</th>
          <th>Location</th>
          <th>Diagnosis</th>
       </tr>
    <!-- TMPL_LOOP NAME=ROWS -->
       <tr>
          <td><!-- TMPL_VAR NAME=request_number --></td>
          <td><!-- TMPL_VAR NAME=year --></td>
          <td>
            <!-- TMPL_VAR NAME=lastname -->,
            <!-- TMPL_VAR NAME=firstname -->
            <!-- TMPL_VAR NAME=middlename -->
          </td>
          <td><!-- TMPL_VAR NAME=dob --></td>
          <td><!-- TMPL_VAR NAME=location --></td>
          <td><!-- TMPL_VAR NAME=diagnosis --></td>
       </tr>
    <!-- /TMPL_LOOP -->
    </table>
  </body>
</html>
