#!/usr/bin/perl

=begin -------------------------------------------------------------------------
missing request forms from data-files dir > 2 working days after registration
runs Sun - Fri (skips Sat)
=cut ---------------------------------------------------------------------------

use strict;
use warnings;

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

################################################################################
my @recipients = qw( hmds.secure raj );
################################################################################

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 $config  = $tools->config();
my $dbix    = $tools->dbix();

# get date $duration working days ago:
my $date = _get_date(); # warn $date->dmy; exit;

# path to fileserver dir:
my $files_dir = $tools->path_to_app_root . '/static/files/leeds';

my $sql = q!SELECT request_number, year FROM requests WHERE
	DATE(created_at) = ? ORDER BY year, request_number!;
my $result = $dbix->query($sql, $date->ymd);

my @missing = ();
while ( my $vars = $result->hash ) { # warn Dumper $vars;
    my $file = _get_filename($vars); # warn Dumper $file;
    next if -e $file;
	my $request = join '/', $vars->{request_number}, $vars->{year} - 2000;
    push @missing, $request;
} # warn Dumper \@missing;

my $msg = join "\n", @missing;
my $subject = $msg ? 'Missing request forms' : 'No missing request forms';

my %mail = (
    message => $msg || '\o/',
	config  => $config,
    subject => $subject . ' registered ' . $date->dmy,
); # warn Dumper \%mail; exit;

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

sub _get_date { # doesn't consider public holidays
    my $dt = $tools->time_now;

	# adjust date according to working days:
	my %adjust = ( # day 1 = Monday:
		1 => 4, # Mon subtract 4 days (registered on Thu)
		2 => 4, # Tue subtract 4 days (registered on Fri)
		3 => 2, # Wed subtract 2 days (registered on Mon)
		4 => 2, # Thu subtract 2 days (registered on Tue)
		5 => 2, # Fri subtract 2 days (registered on Wed)
		7 => 1, # Sun subtract 1 day  (registered on Sat)
	);

	my $n = $adjust{$dt->day_of_week}; # warn $n;
	$dt->subtract( days => $n );

    return $dt;
}

sub _get_filename {
	my $vars = shift;

    my $req_num = $vars->{request_number};
    my $yyyy    = $vars->{year};
    my $yy      = $vars->{year} - 2000;

    # 1-99 = 0, 100-199 = 1, 200-299 = 2, etc
    my $i = int $req_num / 100; # warn $i;

    my $min = 100 * $i || 1; # default to 1 if 0; 1, 100, 200, 300, etc
    my $max = 100 * $i + 99; # 99, 199, 299, etc

    my $filename = sprintf '%s/%s/%s-%s/%s/%s_%05d_request_form.pdf',
		$files_dir, $yyyy, $min, $max, $req_num, $yy, $req_num;

    return $filename;
}
