#------------------------------------------------------------
# Copyright (C) 2011 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package RPS::DB::Item::DynamicReport::Payee::Publishers;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use lib '/app/tools/rps/lib';

use Common::Log;
use Common::DB::Item;
use Common::DB::ItemCollection;
use Common::Assert;

use RPS::DB::Item::FinanceAccount;

use Data::Dumper;
use List::Compare;

use base 'RPS::DB::Item::DynamicReport';

use constant kDB => Common::DB::Item::kClientDB();

# Most if not all of the Catalog group will have the same base group of columns.

sub _config {
    my ($class) = @_;
    return {
        'publisher_id'                  => {},
        'publisher'                     => {},
        'client_account_no'             => {},
        'status'                        => {},
        'address_1'                     => {},
        'address_2'                     => {},
        'address_3'                     => {},
        'city'                          => {},
        'state'                         => {},
        'postal_code'                   => {},
        'country'                       => {},
        'email'                         => {},
        'phone'                         => {},
        'fax'                           => {},
        'publisher_type'                => {},
        'admin'                         => {},
        'agent'                         => {},
        'tax_id'                        => { _encrypted => 1 },
        'affiliate_id'                  => {},
        'comments'                      => { _encrypted => 1 },
        'distribution'                  => {},
        'distribution_status'           => {},
        'date_created'                  => {},
        'date_modified'                 => {},
        'created_by'                    => {},
        'modified_by'                   => {},
        'recipient_name'                => {},
        'recipient_email'               => {},
        'recipient_distribution_status' => {},
        'recipient_id'                  => {},

        # Transactions
        #        'total_no_licenses'  => {},
        'payor_name'         => {},
        'client_payor_no'    => {},
        'payor_status'       => {},
        'default_payor'      => {},
        'minimum_payment'    => {},
        'transaction_status' => {},
        'transaction_type'   => {},
        'amount'             => {},
        'transaction_date'   => {},
        'check_no'           => {},
        'memo'               => {},
        'balance'            => {},
    };

}

sub ReportQuery {
    my ( $class, %args ) = @_;

    my @select;
    $class->_BuildSelect( \@select, %args );

    my @joins;
    $class->_BuildJoins( \@joins, %args );

    my @groupBy;
    $class->_BuildGroupBy( \@groupBy, %args );

    my @orderBy;
    $class->_BuildOrderBy( \@orderBy, %args );

    my @where;
    $class->_BuildWhere( \@where, %args );

    my @from;
    $class->_BuildFrom( \@from, %args );

    my $sql;

    $sql .= 'SELECT ' . join( ",\n", @select ) . "\nFROM " . join( ',', @from );

    if ( scalar @joins ) {
        $sql .= "\n" . join( "\n", @joins );
    }

    if ( scalar @where ) {
        $sql .= "\nWHERE " . join( "\n  AND ", @where );
    }

    if ( scalar @groupBy ) {
        $sql .= "\nGROUP BY " . join( ',', @groupBy );
    }

    if ( scalar @orderBy ) {
        $sql .= "\nORDER BY " . join( ',', @orderBy );
    }

    # SQL is much easier to debug when it has new lines, but it doesn't log well.
    #$sql =~ s/\n/ /g;
    Log->debug("QUERY: $sql");

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

sub _BuildFrom {
    my ( $class, $from, %args ) = @_;

    push @$from, $class->table;
}

sub _BuildSelect {
    my ( $class, $select, %args ) = @_;
    my $table    = $class->table();
    my $tableKey = $class->tableKey();

    push @$select, "$table.publisher_name AS publisher";
    push @$select, "$table.client_account_id AS client_account_no";
    push @$select,
        "IF( $table.status = 0, 'inactive', "
      . "IF( $table.status = 1, 'active', "
      . "IF( $table.status = 2, 'on hold', 'unknown' ) ) ) AS status";
    push @$select, "$table.street_address AS address_1";
    push @$select, "$table.street_address_2 AS address_2";
    push @$select, "$table.street_address_3 AS address_3";
    push @$select, "$table.city AS city";
    push @$select, "$table.state_province AS state";
    push @$select, "$table.postal_code AS postal_code";
    push @$select, "$table.country_code AS country";
    push @$select, "$table.email AS email";
    push @$select, "$table.phone_number AS phone";
    push @$select, "$table.fax_number AS fax";
    push @$select, "IF( $table.is_agency, 'agency', " . "IF( $table.is_admin, 'administrator', 'standard' ) ) AS publisher_type";
    push @$select, "admin.publisher_name AS admin";
    push @$select, "agent.publisher_name AS agent";
    push @$select, "$table.tax_id AS tax_id";
    push @$select, "$table.affiliate_id AS affiliate_id";
    push @$select, "$table.comments AS comments";
    if ( $args{reportType} =~ /^(?:Publishers|PublishersAndRecipients)$/i ) {
        push @$select, "$table.distribution AS distribution";
        push @$select,
          "IF( $table.distribution = 1 AND $table.date_confirmed IS NULL, 'Waiting on confirmation', "
          . "IF( $table.distribution = 1 AND $table.date_confirmed IS NOT NULL, 'Confirmed', '' ) ) AS distribution_status";
    }
    push @$select, "$table.date_created AS date_created";
    push @$select, "$table.date_modified AS date_modified";
    push @$select, "$table.created_by AS created_by";
    push @$select, "$table.modified_by AS modified_by";
    push @$select, "$table.$tableKey AS publisher_id";

    # This is just for sorting purposes.
    push @$select, "IF($table.client_account_id REGEXP '^[[:digit:]]+" . '$'
      . "',LPAD($table.client_account_id,32,'0'),$table.client_account_id) as sort2";

    if ( $args{reportType} =~ /^PublishersAndRecipients$/i ) {
        push @$select, "publisher_statement_recipient.name  AS recipient_name";
        push @$select, "publisher_statement_recipient.email AS recipient_email";
        push @$select,
        qq/CASE
               WHEN publisher_statement_recipient.date_invited IS NOT NULL AND publisher_statement_recipient.date_confirmed IS NULL THEN 'Waiting on confirmation'
               WHEN publisher_statement_recipient.date_invited IS NOT NULL AND publisher_statement_recipient.date_confirmed IS NOT NULL THEN 'Confirmed'
               ELSE ''
           END AS recipient_distribution_status
        /;
        push @$select, "publisher_statement_recipient.statement_recipient_id AS recipient_id";
    }
    push @$select, "$table.key_id";
}

sub _transactionTypeSQL {
    return
        " IF( transaction.type_code = "
      . RPS::DB::Item::FinanceTransaction::kTypeOpeningBalance
      . ", 'opening balance', "
      . " IF( transaction.type_code = "
      . RPS::DB::Item::FinanceTransaction::kTypeAdjustment
      . ", 'adjustment', "
      . " IF( transaction.type_code = "
      . RPS::DB::Item::FinanceTransaction::kTypeAdvance
      . ", 'advance', "
      . " IF( transaction.type_code = "
      . RPS::DB::Item::FinanceTransaction::kTypePayment
      . ", 'payment', "
      . " IF( transaction.type_code = "
      . RPS::DB::Item::FinanceTransaction::kTypeClosingBalance
      . ", 'closing balance', "
      . " IF( transaction.type_code IS NULL, NULL, "
      . " 'unknown' ) ) ) ) ) ) ";
}

sub _BuildJoins {
    my ( $class, $joins, %args ) = @_;
    my $table = $class->table();

    push @$joins, "LEFT JOIN $table as agent ON (agent.${table}_id = $table.agent_id)";
    push @$joins, "LEFT JOIN $table as admin ON (admin.${table}_id = $table.admin_id)";

    if ( $args{reportType} eq 'PublishersAndRecipients' ) {
        push @$joins, 'LEFT JOIN publisher_statement_recipient ON (publisher.publisher_id = publisher_statement_recipient.publisher_id)';
    }

    #    push @$joins, "LEFT JOIN affiliate ON (affiliate.affiliate_id = $table.affiliate_id)";

}

sub _BuildGroupBy {
    my ( $class, $groupBy, %args ) = @_;
}

sub _BuildWhere {
    my ( $class, $where, %args ) = @_;

    my $table = $class->table();

    my $dateType  = $args{dateType};
    my $startDate = $args{startDate};
    my $endDate   = $args{endDate};

    if ($dateType) {
        if ($startDate) {
            push @$where, "TO_DAYS($table.$dateType) >= TO_DAYS(" . $class->quote($startDate) . ")";
        }
        if ($endDate) {
            push @$where, "TO_DAYS($table.$dateType) <= TO_DAYS(" . $class->quote($endDate) . ")";
        }
    }
}

sub _BuildOrderBy {
    my ( $class, $orderBy, %args ) = @_;
    push @$orderBy, "publisher";
    push @$orderBy, "sort2";
}

1;
