#!/usr/bin/perl -Ilibs

use strict;
use warnings;

use API::Controller;

use ECS::Order::Status::RuleCheck ();
use ECS::Order::Payment ();

package API::OrderStatusAdmin;

use Moose;

my %payment_method_label_to_type = (
	'Credit Card'    => 'creditcard',
	'PayPal'         => 'paypal',
	'PayPal Request' => 'paypalrequest',
	'ECS Gift Card'  => 'giftcard',
	'On Account'     => 'onaccount',
	'Wire Transfer'  => 'wiretransfer',
);

my %thresholdFields = (
    'mxScoreThreshold' => "MX Score",
    'orderValueThreshold' => "Order Value",
    'numOrdersThreshold' => "Num Orders",
    'numMonthsThreshold' => "Num Months",
);

extends 'API::Controller';

__PACKAGE__->meta->make_immutable;

###############################################################################

sub orderStatusIndex {
    my $self = (shift)->new({'input' => shift || {}});

    $self->data->{'templates'} = [ "index.html" ];

    $self->data->{'statusRules'} = ECS::Order::Status::RuleCheck::getStatusRules({
        'dbh' => $self->dbhr,
        })
        or $self->error("Failed to fetch order status rules");

    $self->data->{'useMaxMind'} = 0;
    $self->data->{ 'useApruvd' } = 0;
    $self->data->{ 'useInternal' } = 0;
	for my $rule (@{ $self->data->{'statusRules'} }) {
		if ($rule->{'name'} =~ m/^Payment Method: (.*)$/) {
			my $label = $1;
			
			if (my $method_type = $payment_method_label_to_type{$label}) {
				my $module = $ECS::Order::Payment::method_to_module{$method_type};
				my $action = $module->orderActionMap->{'submit'};
				
				$rule->{'paystatus'} = $ECS::Order::Payment::action_to_status{$action};
			}
		}
        if ($rule->{active} eq 'Y' && ($rule->{mxScoreThreshold} || 0) > 0) {
            $self->data->{'useMaxMind'} = 1;
        }
        if ( $rule->{ 'active' } eq "Y"
            and $rule->{ 'name' } =~ m/^Apruvd/
            ) {
            $self->data->{ 'useApruvd' } = 1;
        }
        if ( $rule->{ 'active' } eq "Y"
            and $rule->{ 'name' } eq "Poison Match"
            ) {
            $self->data->{ 'useInternal' } = 1;
        }

        my @thresholds;
        $rule->{'thresholds'} = \@thresholds;
        for my $field ( keys %thresholdFields ) {
            if ( defined $rule->{ $field } ) {
                push( @thresholds, {
                    'field' => $field,
                    'label' => $thresholdFields{ $field },
                    'value' => $rule->{ $field },
                } );
            }
        }

	}
	
	my %order_status_priority = %ECS::Order::Status::RuleCheck::status_priority;
	
	$self->data->{'orderStatusPriority'} = [
		grep { $order_status_priority{$_} >= 0 }
			sort { $order_status_priority{$b} <=> $order_status_priority{$a} }
				keys %order_status_priority
	];
	
	my %payment_status_priority = %ECS::Order::Payment::status_priority;
	
	$self->data->{'payStatusPriority'} = [
		'Failed',
		'Review',
		sort { $payment_status_priority{$a} <=> $payment_status_priority{$b} }
			keys %payment_status_priority
	];
	
    return $self->result;
}

###############################################################################

sub updateOrderStatus {
    my $self = (shift)->new({'input' => shift || {}});

    # translate form data into a hash
    my $orderStatusRules = {};
    for my $field (keys %{ $self->input }) {
        for my $thresholdField ( keys %thresholdFields ) {
            if($field =~ m/^${thresholdField}_(\d+)$/) {
                my $orderStatusRuleID = $1;
                my $value = $self->input->{$field};

                # if the value is non-numeric, skip it
                next unless $value =~ m/^\d+\.?\d*$/;

                $orderStatusRules->{$orderStatusRuleID}->{ $thresholdField }
                    = $value;
            }
        }
        if($field =~ m/^active_(\d+)$/) {
            my $orderStatusRuleID = $1;
            my $value = $self->input->{$field};
            $orderStatusRules->{$orderStatusRuleID}->{'active'}
                = $value;
        }
    }

    ECS::Order::Status::RuleCheck::setStatusRules({
        'dbh' => $self->dbh,
        'orderStatusRules' => $orderStatusRules,
    })
        or $self->error("Failed to update order status rules")
        and return $self->result;

    $self->data->{'redirect'} = ".";
    return $self->result;
}

###############################################################################

return 1;

