#!/usr/bin/perl -Ilibs

package API::WholesalePricingAdmin;

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

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

use API::Config;

use ECS::Site;

extends "API::Controller";

has 'site' => (
    'is'    => "rw",
    'isa'   => "ECS::Site",
    'lazy' => 1,
    'builder' => "_build_site",
);

__PACKAGE__->meta->make_immutable;

###############################################################################
sub _build_site {
    my $self = shift;

    return ECS::Site->fromName( $self->input->{site} );
}

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

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

    return $self->result;
}

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

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

    return $self->result;
}

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

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

    return $self->result;
}

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

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

    my %sitesSaveData;
    my $brandID = $self->input->{brandID} || 0;
    my $doDelete = ( $self->input->{'submit'} eq 'Delete' );

    croak "must specify brandID to delete" if (
        $doDelete
        and not $brandID
    );

    my @columns = sort qw(
        customerGroupID
        brandID
        groupName
        discountValue
        gpClassID
    );
    my @updateCols = qw(
        discountValue
    );

    my %sitesPreviousValues;
    for my $field (keys %{ $self->input }) {

        next unless ($field =~ m/^discountValue_(.*)_(\d)$/);

        my $siteName = $1;
        my $customerGroupID = $2;

        if ( not $sitesPreviousValues{ $siteName } ) {
            my $site = ECS::Site->fromName( $siteName );
            my $sth = $site->site_dbhr->prepare(
                "SELECT ".join(", ", @columns)."
                FROM customerGroup
                WHERE brandID = 0"
            );
            $sth->execute();
            my $siteCustomerGroups = $sth->fetchall_hashref('customerGroupID');
            $sitesPreviousValues{ $siteName } = $siteCustomerGroups;
        }

        my $previousValues = $sitesPreviousValues{ $siteName };

        croak "could not retrieve customerGroup previousValues for site $siteName"
            unless $previousValues;

        my $groupPreviousValues = $previousValues->{ $customerGroupID };
        $sitesSaveData{ $siteName }->{ $customerGroupID } = {
            'discountValue' => sprintf("%.2f", $self->input->{$field} || 0) / 100,
            'customerGroupID' => $groupPreviousValues->{'customerGroupID'},
            'groupName' => $groupPreviousValues->{'groupName'},
            'brandID' => $brandID,
            'gpClassID' => $groupPreviousValues->{'gpClassID'},
        };
    }

    for my $siteName ( keys %sitesSaveData ) {
        my $saveData = $sitesSaveData{ $siteName };
        my $site = ECS::Site->fromName( $siteName );
        my $previousValues = $sitesPreviousValues{ $siteName };
        $self->logChanges({
            'site' => $site,
            'brandID' => $brandID,
            'action' => ($self->input->{'addNew'} 
                ? 'ADDED'
                : $self->input->{'submit'}),
            'saveData' => $saveData,
            'previousValues' => $previousValues,
            'updateCols' => \@updateCols,
        });

        if ( $doDelete ) {
            my $sth = $site->site_dbh->prepare(
                "DELETE FROM customerGroup WHERE brandID = ?"
            );
            $sth->execute( $brandID );
            next;
        }

        my @rows = sort keys %$saveData;
        if (@rows) {
            my @rowSQL = (join ", ", ("?") x @columns ) x @rows;
            my $sqlIns = join ", ", map { "( $_ )" } @rowSQL;
            my $sqlUpd = join ", ", map { "$_ = VALUES( $_ )" } @updateCols;

            my $sth = $site->site_dbh->prepare(
                "INSERT INTO customerGroup ( ".join(", ", @columns)." )
                VALUES $sqlIns
                ON DUPLICATE KEY UPDATE $sqlUpd"
            );

            my @binds = ();
            foreach my $ID (keys %$saveData) {
                my $data = $saveData->{$ID};
                for my $col (sort keys %{ $data }) {
                    push @binds, $data->{ $col };
                }
            }

            $sth->execute(@binds);
        }
    }

    if ( $doDelete ) {
        $self->data->{'redirect'} = './'; # admin index page
        return $self->result;
    }

    my $redirectURI = URI->new( $self->input->{'editURL'} );
    $self->data->{'redirect'} = $redirectURI->path_query;
    return $self->result;
}

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

sub logChanges {
    my ($self, $p) = @_;

    my $site = $p->{'site'} or croak "site required";

    if ($p->{brandID} != 0) {
        my $sth = $site->site_dbhr->prepare("SELECT * FROM customerGroup WHERE brandID = ?");
        $sth->execute($p->{brandID});
        $p->{previousValues} = $sth->fetchall_hashref('customerGroupID');
    }

    my $logSQL = qq{
        INSERT INTO customerGroupLog
        SET
            customerGroupID = ?,
            brandID = ?,
            modifyDate = NOW(),
            employeeID = ?,
            ipAddress = ?,
            field = ?,
            valueOld = ?,
            valueNew = ?,
            siteID = ?
    };
    my $sth = $site->site_dbh->prepare($logSQL);

    foreach my $field (@{$p->{updateCols}}) {
        foreach my $ID (keys %{$p->{saveData}}) {
            my ($valueOld, $valueNew);
            if ($p->{action} eq 'ADDED') {
                $valueOld = $p->{action};
                $valueNew = $p->{saveData}->{$ID}->{$field};
            }
            elsif ($p->{action} eq 'Delete') {
                $valueOld = $p->{saveData}->{$ID}->{$field};
                $valueNew = 'DELETED';
            }
            else {
                $valueOld = $p->{previousValues}->{$ID}->{$field};
                $valueNew = $p->{saveData}->{$ID}->{$field};
            }

            next if ($valueOld == $valueNew && $valueNew != 0);
            my @values = (
                $ID,
                $p->{brandID},
                $self->input->{'employeeID'},
                $ENV{'REMOTE_ADDR'},
                $field,
                $valueOld,
                $valueNew,
                $site->siteID,
            );
            $sth->execute(@values);
        }
    }

    return;
}

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

1;
