#!/usr/bin/perl -Ilibs

use strict;
use warnings;

use JSON ();
use API::Controller;

package API::ETAChangeReasonAdmin;

use ECS::Purchasing::ETAChangeReason ();

use Moose;
use Try::Tiny;

extends 'API::Controller';

__PACKAGE__->meta->make_immutable;

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

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

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

    my $reasons = ECS::Purchasing::ETAChangeReason::getReasons({
        'DBH' => $self->dbhr,
        })
        or $self->error("Failed to fetch ETA reason codes");

    # Filter out the inactive reasons. They do not need to be displayed in the Admin
    $self->data->{'reasons'} = [grep { $_->{'active'} eq 'YES' } @{ $reasons }];

    return $self->result;
}

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

sub updateChangeReasons {
    my $self = (shift)->new({'input' => shift || {}});
	
	my $reasons;
	
	try {
		$reasons = JSON::from_json($self->input->{'reasons'});
	} catch {
		warn 'failed to JSON decode ETA reason codes: '.$_;
	};
	
	unless ($reasons) {
		$self->error('Failed to receive ETA reason codes data');
		return $self->result;
	}
	
	ECS::Purchasing::ETAChangeReason::setReasons({
		'DBH'     => $self->dbh,
		'reasons' => $reasons,
	})
		or $self->error('Failed to update ETA reason codes')
		and return $self->result;
	
    $self->data->{'redirect'} = '.';
    return $self->result;
}

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

return 1;

