package RPS::Portal::Command::EmailCustomText;
use strict;
use warnings;

use lib '/app/tools/common/lib';
use RSApache::Response::XSLT;
use RSApache::Response::Download;
use Common::Assert;
use Common::Debug;

use lib '/app/tools/rps/lib';
use RPS::Portal::Command::Main;

use base 'RPS::Command';

sub area { return "portal"; }
sub cmd  { return "email_custom_text"; }

use constant kTemplate => '/app/tools/rps/templates/portal/main.xsl';

sub execute {
    my ($self) = @_;

    my $response = $self->SUPER::execute();
    return $response if $response;

    my $invite_flag = $self->getParam('invite_flag');
    my $notification_flag = $self->getParam('notification_flag');
    my $message;
    my $clientInfo = Common::DB::Item::Client->Lookup( client_id => Common::RSApp::GetClientID() );

    if ($invite_flag) {
        $clientInfo->custom_invite_text($self->getParam("form_custom_invite_text"));
        $clientInfo->save();
        $message = RPS::Message->new( type => "success", code => "invite_text_saved" );
    } elsif ($notification_flag) {
        $clientInfo->custom_notification_text($self->getParam("form_custom_notification_text"));
        $clientInfo->save();
        $message = RPS::Message->new( type => "success", code => "notification_text_saved" );
    }

    my $payor_id          = $self->getParam("PayorID")         || 0;
    my $artist_run_id     = $self->getParam("RoyaltyRunID")    || 0;
    my $mechanical_run_id = $self->getParam("MechanicalRunID") || 0;

    my $command = RPS::Portal::Command::Main->new( msg => $message->toString );

    if ( $payor_id && $payor_id =~ /^\d+$/ && $artist_run_id && $artist_run_id =~ /^\d+$/ ) {
        return RSApache::Response::Redirect->new(
            "/rps/artist_royalty?c=distribute&RoyaltyRunID=$artist_run_id&" .
            "PayorID=$payor_id&msg=success|notification_text_saved"
        );
    }

    if ( $payor_id && $payor_id =~ /^\d+$/ && $mechanical_run_id && $mechanical_run_id =~ /^\d+$/ ) {
        return RSApache::Response::Redirect->new(
            "/rps/mechanical?c=distribute&MechanicalRunID=$mechanical_run_id&" .
            "PayorID=$payor_id&msg=success|notification_text_saved"
        );
    }

    return RSApache::Response::Redirect->new( $command->getRedirect() );
}

1;
