#!/usr/bin/perl

use Getopt::Long;
use File::Copy;
use Date::Calc qw(Add_Delta_YM Days_in_Month);

use lib '/app/tools/common/lib';
use Common::Log;
use Common::Amazon::Mail;

use strict;
use warnings;

# variables for command options.
my $filePath;
my $fileName;
my $fileDate;

# program starts here.

# gets command options.
getOptions();

usage("missing file path") unless ( defined $filePath );
usage("missing file name") unless ( defined $fileName );
usage("missing file date") unless ( defined $fileDate );

my $startDate;
my $endDate;

if ( $fileDate =~ /(\d{4})(\d{2})(\d{2})/ ) {
    my ( $year, $month, $day ) = Add_Delta_YM( $1, $2, $3, 0, -1 );
    $startDate = sprintf( "%04d%02d%02d", $year, $month, 1 );
    $endDate =   sprintf( "%04d%02d%02d", $year, $month, Days_in_Month( $year, $month ) );
} else {
    die "Date must be in YYYYMMDD format.";
}

# Make the file name prettier.
my $newFileName = "RPS_Monthly_Billable_Revenue_By_Closed Period_" . $startDate . "-" . $endDate . ".csv";

# Copy file to rename it.
copy($filePath . "/" . $fileName, $filePath . "/" . $newFileName) or die "Copy failed: $!";

## add or change email list here
my $recipients = [ qw/
    cbreindel@theorchard.com
    cheryl@royaltyshare.com
    jgasson@theorchard.com
    Royaltyshareinvoices@theorchard.com
    onunez@theorchard.com
    oscar@royaltyshare.com
/ ];

# send an email about with the report
my $mail = Common::Amazon::Mail->new;
$mail->to($recipients);
$mail->cc('sysadmin@royaltyshare.com');
$mail->subject("RPS Monthly Billable Revenue By Closed Period $startDate-$endDate");
$mail->body("Here it is.  Enjoy!\n\n");
$mail->sendit( [ $filePath . "/" . $newFileName ] );

sub getOptions {

    # p - file path
    # n - file name
    # d - file date
    GetOptions(
        "path|p=s" => \$filePath,
        "name|n=s" => \$fileName,
        "date|d=s" => \$fileDate
    ) or exit;
}
