#!/usr/bin/perl -Ilibs -I../www/libs

package API::RetailMarginAdmin;

use strict;
use warnings;

use Carp;
use Moose;
use Try::Tiny;

use ECS::RetailMargin;

use API::Controller;
extends "API::Controller",
        "SOAP::Server::Parameters";

__PACKAGE__->meta->make_immutable;

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

sub index {
    my ( $self ) = shift->new( @_ );

    my $rm = ECS::RetailMargin->new;
    $self->data->{ 'retailMargin' } = $rm->row_hash;

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

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

sub save {
    my ( $self ) = shift->new( @_ );

    $self->input->{ 'enabled' } ||= "NO";

    my $rm = ECS::RetailMargin->new( {
        'dbh' => $self->dbh,
    } );

    $self->_log_change( $rm, "enabled",     $self->input );
    $self->_log_change( $rm, "marginFloor", $self->input );

    $rm->set_column(         'enabled' => $self->input->{ 'enabled' } );
    $rm->set_column(         'marginFloor' => $self->input->{ 'marginFloor' } );
    $rm->update;

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

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

sub _log_change {
    my ( $self, $rm, $field, $input ) = @_;

    my $valueOld = $rm->row->$field;
    my $valueNew = $input->{ $field };

    # no change
    return if $valueOld eq $valueNew;

    my $schema = ECS::DB::Schema::getSchema( {
        'dbh'    => $self->dbh,
        'schema' => "RetailMarginFloorLog",
    } );
    $schema->create( {
        'retailMarginFloorID' => $rm->row->retailMarginFloorID,
        'field'               => $field,
        'valueOld'            => $valueOld,
        'valueNew'            => $valueNew,
        'employeeID'          => $input->{ 'employeeID' },
    } );

    return;
}

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

1;

