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

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 kTable => 'label_contract';
use constant kDB    => Common::DB::Item::kClientDB();

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

    my @where;

    # Are we paging alphanumerically?
    #
    my $alpha = $args{alpha};
    if ( defined $alpha ) {
        if ( '0' eq uc($alpha) ) {
            push @where, "title < 'A'";
        } elsif ( 'Z' eq $alpha ) {
            push @where, "title >= 'Z'";
        } else {
            push @where, "title >= '" . uc($alpha) . "'";
            push @where, "title < '" . chr( ord( uc($alpha) ) + 1 ) . "'";
        }
    }

    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 = "SELECT * FROM " . kTable . " $whereClause ORDER BY title";

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

sub GetByPayee {
    my ( $class, $payeeID ) = @_;
    assert($payeeID);

    my $sql = "SELECT * FROM " . kTable . " WHERE label_payee_id = " . $class->quote($payeeID) . " ORDER BY title";
    return $class->GetAll($sql);
}

sub GetByPayor {
    my ( $class, $payorID ) = @_;
    assert($payorID);

    my $sql = "SELECT * FROM " . kTable . " WHERE payor_id = " . $class->quote($payorID) . " ORDER BY title";
    return $class->GetAll($sql);
}

# !!! Odd that this is not referenced anyplace - might be something funny going on.
#
sub Search {
    my ( $class, $searchTerm ) = @_;
    assert( $searchTerm, "no valid param passed to label_contract search" );

    my $where =
        $class->SearchSyntax( field => "label_payee.name",      value => $searchTerm ) . " OR "
      . $class->SearchSyntax( field => "ac.client_contract_id", value => $searchTerm ) . " OR "
      . $class->SearchSyntax( field => "ac.title",              value => $searchTerm );

    my $order = "ac.title, label_payee.name";

    my $sql =
        "SELECT ac.* FROM "
      . kTable . " ac"
      . " LEFT JOIN label_payee ON label_payee.label_payee_id=ac.label_payee_id"
      . " WHERE $where"
      . " ORDER BY $order";

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

1;

