#!/usr/bin/perl
# Script to initialize the RSCOMMON.orchard_period table
#
use strict;
use Data::Dumper;
use Date::Calc qw(Days_in_Month);

use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::RSApp;

my @months = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' );

my $appSingleton = Common::RSApp->new( clientID => 0 );
my $cdbo = Common::RSApp::GetCommonDB();
my $dbh = $cdbo->DBH;

my $sql = "TRUNCATE orchard_period";
my $sth = $cdbo->DoCmd($sql);

my $period = 1; # 1/1/1999

my $_period = $period;

for my $year (1999 .. 2019)
{
    for my $month (1 .. 12)
    {
        my $startDate;
        my $endDate;
        my $periodID;
        my $periodName;

        if( $month =~ /^(1|4|7|10)$/ )
        {
            $startDate = sprintf("%04d-%02d-01", $year, $month);
            $endDate = sprintf("%04d-%02d-%02d", $year, $month+2, Days_in_Month($year, $month+2));

            $periodID = join(",", ($_period), ($_period+1), ($_period+2));

            $periodName = ($month == 1) ? "Q1$year" :
                          ($month == 4) ? "Q2$year" :
                          ($month == 7) ? "Q3$year" :
                                          "Q4$year";

            print "[$_period] m = $month  ### Period $periodID  -> ". $periodName . "  [$startDate - $endDate]\n";

            my $sql = "INSERT INTO orchard_period(period,name,start_date,end_date) VALUES("
                . join(",", $cdbo->DBQuote($periodID),
                            $cdbo->DBQuote($periodName), 
                            $cdbo->DBQuote($startDate), 
                            $cdbo->DBQuote($endDate) ) . ")";
            my $sth = $cdbo->DoCmd($sql);
        }

        $periodID = $_period;

        $periodName = $months[$month-1] . $year;
        $startDate = sprintf("%04d-%02d-01", $year, $month);
        $endDate = sprintf("%04d-%02d-%02d", $year, $month, Days_in_Month($year, $month));

        print "[$_period]  ### Period $periodID  -> ". $periodName . "  [$startDate - $endDate]\n";

        my $sql = "INSERT INTO orchard_period(period,name,start_date,end_date) VALUES("
            . join(",", $cdbo->DBQuote($periodID),
                        $cdbo->DBQuote($periodName), 
                        $cdbo->DBQuote($startDate), 
                        $cdbo->DBQuote($endDate) ) . ")";
        my $sth = $cdbo->DoCmd($sql);

        $_period++;
    }

    print "\n";

}


1;
