#!/usr/bin/perl -Ilibs

package API::ReasonCodeAdmin;

use strict;
use warnings;
use autodie;
use namespace::autoclean;

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

extends "API::Controller";

my %SECTIONS = (
    'inventoryAdjustment' => {
        'sortOrder' => 1,
        'title' => 'Inventory Adjustment',
        'reasonTable' => 'inventoryAdjustmentReason',
        'reasonTableField' => 'description',
    },
    'storeCredit' => {
        'sortOrder' => 2,
        'title' => 'Store Credit',
        'reasonTable' => 'storeCreditTransactionReason',
        'reasonTableField' => 'description',
    },
    'orderReturn' => {
        'sortOrder' => 3,
        'title' => 'CRMA / Order Return',
        'reasonTable' => 'orderReturnReason',
        'reasonTableField' => 'reason',
    },
    'vendorReturn' => {
        'sortOrder' => 4,
        'title' => 'VRMA / Purchase Credit',
        'reasonTable' => 'vendorReturnReason',
        'reasonTableField' => 'reason',
        'dispositionTable' => 'vendorReturnDisposition',
        'dispositionTableField' => 'disposition',
    },
);

my %TABLE_CONFIGS = (
    'inventoryAdjustmentReason' => {
        'textField' => 'description',
        'otherFields' => [
            {
                'name' => 'gpCode',
                'type' => "text",
                'label' => "GP Code",
            },
        ],
    },
    'storeCreditTransactionReason' => {
        'textField' => 'description',
    },
    'orderReturnReason' => {
        'textField' => 'reason',
        'otherFields' => [
            {
                'name' => 'tangible',
                'type' => 'boolean',
                'label' => 'Tangible',
            },
        ],
    },
    'vendorReturnReason' => {
        'textField' => 'reason',
    },
     'vendorReturnDisposition' => {
        'textField' => 'disposition',
    },
);

__PACKAGE__->meta->make_immutable;
return 1;

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

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

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

    $self->data->{'sections'} = [
        map {{
            'section' => $_,
            'title' => $SECTIONS{$_}->{'title'},
        }} sort {
            $SECTIONS{$a}->{'sortOrder'} <=> $SECTIONS{$b}->{'sortOrder'}
        } keys %SECTIONS
    ];

    my %sectionsData;
    $self->data->{'sectionsData'} = \%sectionsData;
    
    for my $sectionKey (keys %SECTIONS) {
        my $section = $SECTIONS{$sectionKey};
        
        my %sectionData;
        $sectionsData{$sectionKey} = \%sectionData;
        
        for my $type (qw(reason disposition)) {
            
            my $tableName = $section->{$type.'Table'};
            
            next unless $tableName;
            
            my $tableConfig = $TABLE_CONFIGS{$tableName};
            
            my $getContents = $self->dbhr->prepare(
                'SELECT
                    '.$tableName.'.*,
                    '.$tableName.'ID AS ID,
                    '.$tableConfig->{'textField'}.' AS content,
                    UNIX_TIMESTAMP(tsCreated) AS tsCreated,
                    CONCAT(employeeInfo.nameFirst, \' \', employeeInfo.nameLast) AS createdBy
                FROM
                    '.$tableName.'
                    LEFT JOIN employeeInfo ON ('.$tableName.'.employeeID = employeeInfo.employeeID)
                WHERE
                    isActive = \'YES\''
            );
            
            $getContents->execute();
            
            $sectionData{$type} = {
                'contents' => $getContents->fetchall_arrayref({}),
                'otherFields' => ($tableConfig->{'otherFields'} || []),
            };
        }
        
    }

    return $self->result;
}

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

sub addContent {
    my $self = shift->new({'input' => shift || {}});
    
    my $section = $SECTIONS{$self->input->{'section'}};
    
    die('unknown reason code section: '.$self->input->{'section'})
        unless $section;
    
    my $tableName = $section->{$self->input->{'type'}.'Table'};
    my $tableConfig = $TABLE_CONFIGS{$tableName};
    
    die('section does not store this type: '.$self->input->{'section'})
        unless $tableName;
    
    die('content is required')
        unless $self->input->{'content.0'};
    
    die('employeeID is required')
        unless $self->input->{'employeeID'};

    my @contentFields = ( $tableConfig->{'textField'} );
    for my $otherField (@{ $tableConfig->{'otherFields'} }) {
        if($otherField->{'type'} eq "text") {
            push @contentFields, $otherField->{'name'};
        }
    }

    my @contentValues = ();
    for my $i (0 .. $#contentFields) {
        push @contentValues, $self->input->{"content.$i"};
    }

    my $plh = join ", ", ("?") x @contentValues;
    my $sql = "INSERT INTO $tableName (
            " . join(", ", @contentFields) . ",
            isActive,
            employeeID,
            tsCreated
        ) VALUES ($plh, 'YES', ?, NOW())";
    my $insertContent = $self->dbh->prepare($sql);
    
    $insertContent->execute(
        @contentValues,
        $self->input->{'employeeID'},
    );
    
    $self->data->{'redirect'} = './#tabs-'.$self->input->{'section'};
    return $self->result;
}

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

sub removeContent {
    my $self = shift->new({'input' => shift || {}});
    
    my $section = $SECTIONS{$self->input->{'section'}};
    
    die('unknown reason code section: '.$self->input->{'section'})
        unless $section;
    
    my $tableName = $section->{$self->input->{'type'}.'Table'};
    
    die('section does not store this type: '.$self->input->{'section'})
        unless $tableName;
    
    die('itemID to remove is required')
        unless $self->input->{'itemID'};
    
    my $deactivateContent = $self->dbh->prepare(
        "UPDATE
            $tableName
        SET
            isActive = 'NO'
        WHERE
            ".$tableName."ID = ?"
    );
    
    $deactivateContent->execute(
        $self->input->{'itemID'},
    );
    
    $self->data->{'redirect'} = './#tabs-'.$self->input->{'section'};
    return $self->result;
}

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

sub setContentFieldValue {
    my $self = shift->new({'input' => shift || {}});
    
    my $section = $SECTIONS{$self->input->{'section'}};
    
    die('unknown reason code section: '.$self->input->{'section'})
        unless $section;
    
    my $tableName = $section->{$self->input->{'type'}.'Table'};
    
    die('section does not store this type: '.$self->input->{'section'})
        unless $tableName;
    
    die('itemID to change is required')
        unless $self->input->{'itemID'};
    
    my $fieldName = $self->input->{'field'};
    
    die('field to change is required')
        unless $fieldName;
    
    die('value to set is required')
        unless defined $self->input->{'value'};
    
    my $tableConfig = $TABLE_CONFIGS{$tableName};
    
    die('field specified ('.$fieldName.') does not belong to this section type')
        unless grep { $_->{'name'} eq $fieldName } @{
            $tableConfig->{'otherFields'} || []
        };
    
    my $setValue = $self->dbh->prepare(
        "UPDATE
            $tableName
        SET
            $fieldName = ?
        WHERE
            ".$tableName."ID = ?"
    );
    
    $setValue->execute(
        $self->input->{'value'},
        $self->input->{'itemID'},
    );
    
    $self->data->{'redirect'} = './#tabs-'.$self->input->{'section'};
    return $self->result;
}

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