#------------------------------------------------------------
# Copyright (C) 2010 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package Raptor::DB::Item::PeriodMonth;
use lib '/app/tools/raptor/lib';
use Raptor::DB::Item::Sale;
use lib '/app/tools/common/lib';
use Common::Assert;
use Common::DB::Item;
use Common::DB::ItemCollection;
use base 'Common::DB::Item';

use constant kTable => 'period_month';
use constant kDB    => Common::DB::Item::kCommonDB();

sub GetAllByRange {
    my $class = shift;
    my %args  = @_;

    my ( $begin, $end, $year ) = ( $args{begin}, $args{end}, $args{year} );

    assert( $begin, "Date required" );
    assert( $end,   "Date required" );

    my $dbo = Common::RSApp::GetClientDB();

    my $sql = "SELECT * FROM " . kTable . " WHERE date_begin >= " . $dbo->DBQuote($begin) . " AND date_begin  <  " . $dbo->DBQuote($end);

    $sql .= " AND year = " . $dbo->DBQuote($year) if ($year);
    $sql .= " ORDER BY date_begin";

    return $class->GetAll($sql);
}

# Get month periods starting with latest month to have sales.
#

sub GetLatestByRange {
    my $class = shift;
    my %args  = @_;

    my $months = $args{months};
    my $ytd    = $args{ytd};

    assert( $months || $ytd, "Months or ytd required" );

    my $dbo = Common::RSApp::GetClientDB();

    my ( $dateBegin, $dateEnd ) = Raptor::DB::Item::Sale->GetDateRange();

    # If no dates are returned (which will happen if there are no sales),
    # we'll default to today's date.
    #
    if ( !$dateEnd ) {
        my ( undef, undef, undef, $mday, $mon, $year, undef, undef, $isdst ) = localtime(time);
        $dateEnd = sprintf( "%4d-%02d-%02d", $year + 1900, $mon + 1, $mday );
    }

    my ($yearEnd) = split( /-/, $dateEnd );

    my $sql = "SELECT * FROM " . kTable;

    if ($months) {
        $sql .=
            " WHERE date_begin > DATE( DATE_SUB( '$dateEnd', interval "
          . $dbo->DBQuote($months)
          . " month ) ) "
          . " AND date_begin  <=  DATE( '$dateEnd' )";
    } else {
        $sql .= " WHERE year = $yearEnd " . " AND date_begin  <=  DATE( '$dateEnd' )";
    }

    $sql .= " ORDER BY date_begin";

    #die $sql;

    return $class->GetAll($sql);
}

1;
