#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package RPS::DB::Item::Contract;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::Util qw(escape_mysql_regexp);
use Common::DB::ItemCollection;
use Common::DB::Item;
use Common::Assert;
use base 'Common::DB::Item';

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

# This will need to be able to return contracts from both new_artist_contract and label_contract.

sub _config {
    my ($class) = @_;

    return {
        'title'              => {},
        'artist_contract_id' => {},
        'label_contract_id'  => {},
    };

}

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

    my @where;

    if ( $args{payor_id} ) {
        push @where, "payor_id = " . $class->quote( $args{payor_id} );
    }

    my $whereClause;
    if ( scalar @where ) {
        $whereClause = "WHERE " . join( ' AND ', @where );
    }

    my $sql;

    if ( $args{artistContract} ) {
        my $whereExtended = $whereClause ? "$whereClause AND deleted = 0 " : " WHERE deleted = 0 ";
        $sql = qq/
            SELECT
                artist_contract_id as artist_contract_id,
                NULL as label_contract_id,
                title as title
            FROM new_artist_contract
            $whereExtended
        /;
    }

    if ( $args{artistContract} && $args{labelContract} ) {
        $sql .= "UNION ALL ";
    }

    if ( $args{labelContract} ) {
        $sql .= qq/
            SELECT
                NULL as artist_contract_id,
                label_contract_id as label_contract_id,
                title as title
            FROM label_contract
            $whereClause
        /;
    }

    $sql .= "ORDER BY title";

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

1;
