#!/usr/bin/perl -Ilibs -I../www/libs

use strict;
use warnings;

use API::Controller ();
use ECS::Site;
use ECS::dbConfig;
use ECS::SQL;
use ECS::Warehouse::Location::WarehouseZone;
use ECS::Warehouse::OrderTypePriority;

package API::OrderBatchAdmin;

use Moose;
use Data::Dumper;
use JSON;
extends 'API::Controller';

__PACKAGE__->meta->make_immutable;

#####################################################################################

sub viewIndex {
	my $self = (shift)->new({'input' => shift || {}});

    $self->data->{'templates'} = [ "index.html" ];

    return $self->result;
}

#####################################################################################

sub viewOrderBatchPriority {
	my $self = (shift)->new({'input' => shift || {}});
	
	## Get warehouseZoneID's
	my $allWarehousesZoneIDs = ECS::Warehouse::Location::WarehouseZone::search({
        'dbh'    => $self->dbhr,
        'search' => [],
    });
	
	## get order type priority
	my $allOrderTypePriorities = ECS::Warehouse::OrderTypePriority::search({
        'dbh'    => $self->dbhr,
        'search' => [],
    });
	
	$self->data->{'warehouseZones'}    = [ map { $_->pack } @{ $allWarehousesZoneIDs } ];
	$self->data->{'orderTypePriorities'} = [ sort { $a->{typePriority} <=> $b->{typePriority} } map { $_->pack } @{ $allOrderTypePriorities } ];
	$self->data->{'adminSelected'}     = "OrderBatchPriority.html";	
	$self->data->{'templates'}         = [ "index.html" ];
	$self->data->{'activeBreadcrumbTitle'}  = "Order Batch Priority";
	
	return $self->result;
}

#####################################################################################

sub viewOrderBatchCart {
	my $self = (shift)->new({'input' => shift || {}});
	
	my $getCarts = "
        SELECT 
			orderBatchCartID,
			cartEnabled,
			cartName,    
			rows,        
			columns,     
			labelFormat
        FROM orderBatchCart
        ORDER BY cartName ";
		
	my $sth = $self->dbhr->prepare($getCarts);
	$sth->execute();
    my $carts =  $sth->fetchall_arrayref({});
	
	$self->data->{'carts'}                  = $carts;
	$self->data->{'adminSelected'}          = "OrderBatchCart.html";
	$self->data->{'templates'}              = [ "index.html" ];
	$self->data->{'activeBreadcrumbTitle'}  = "Order Batch Cart";
	
	return $self->result;
}

#####################################################################################

sub viewOrderBatchConfig {
	my $self = (shift)->new({'input' => shift || {}});
	my $result = {};
	
	my $sql = "
        SELECT 
            priority,
            batchSize,
			minWeight,
			maxWeight,
            batchWeight,
            orderSize,
			stockType,
            orderBatchCartID,
            orderBatchCart.cartName,
			orderAddRuleEnabled
        FROM orderBatchConfig
         JOIN orderBatchCart
        USING (orderBatchCartID)
        WHERE batchType = ?
        ORDER BY priority, tsModified
    ";
	 my $sth = $self->dbhr->prepare($sql);
	foreach my $site ( ECS::Site->getAll()){		
		$sth->execute($site->name);	
		$result->{$site->name} = $sth->fetchall_arrayref({});
	}
	
	$sql = "
		SELECT 
			orderBatchCartID,
			cartEnabled,
			cartName,    
			rows,        
			columns,     
			labelFormat
		FROM orderBatchCart
		ORDER BY cartName";
	
	$sth = $self->dbhr->prepare($sql);
	$sth->execute();
	my $carts =  $sth->fetchall_arrayref({});
	
	$self->data->{ecsFormData}			    = $result->{ECS};
	$self->data->{tmsFormData} 				= $result->{TMS};
	$self->data->{carts}                    = $carts;
	$self->data->{'adminSelected'}          = "OrderBatchConfig.html";
	$self->data->{'templates'}              = [ "index.html" ];
	$self->data->{'activeBreadcrumbTitle'}  = "Order Batch Config";
	
	return $self->result;

}

#####################################################################################

sub saveOrderpriority {
	my $self = (shift)->new({'input' => shift || {}});
	
	my $newValues = decode_json($self->input->{'dataToSave'});
	my ( $newValue, $oldValue ) = '';
	
	foreach my $orderTypeID ( keys %$newValues ){
		my $obj = ECS::Warehouse::OrderTypePriority->new({
			'dbh'                 => $self->dbh,
            'orderTypePriorityID' => $orderTypeID,
		});
		
		next if ( $newValues->{$orderTypeID} == $obj->typePriority );
		
		$oldValue .= "{orderType: ".$obj->typeName.", priority: ".$obj->typePriority."}";
		$newValue .= "{orderType: ".$obj->typeName.", priority: ".$newValues->{$orderTypeID}."}";
		
		$obj->typePriority($newValues->{$orderTypeID});			
		
		$obj->save;
	}
	
	##log cahnges
	logOrderTypePriorityChanges({
		'dbh'           => $self->dbh,
		'newValue'      => $newValue,
		'oldValue'      => $oldValue,
		'changeType'    => 'Order Type',
		'employeeID'    => $self->input->{'employeeID'},
	});
		
	$self->data->{'dataType'} = "json";
	$self->data->{'data'} = {'success'=>1};
	
	return $self->result;
}

#####################################################################################

sub saveWarehouseZone {
	my $self = (shift)->new({'input' => shift || {}});
	
	my $newValues = decode_json($self->input->{'dataToSave'});
	my ($oldValue, $newValue) = '';

	foreach my $warehouseZoneID ( keys %$newValues ){
		my $obj = ECS::Warehouse::Location::WarehouseZone->new({
			'dbh'                 => $self->dbh,
            'warehouseZoneID'     => $warehouseZoneID,
		});
		
		next if ( $newValues->{$warehouseZoneID} == $obj->zonePriority );
		
		$oldValue .= "{Zone: ".$obj->zoneName.", priority: ".$obj->zonePriority."}";
		$newValue .= "{Zone: ".$obj->zoneName.", priority: ".$newValues->{$warehouseZoneID}."}";
		
		$obj->zonePriority($newValues->{$warehouseZoneID});		
		
		$obj->save;
	}
	
	##log cahnges
	logOrderTypePriorityChanges({
		'dbh'           => $self->dbh,
		'newValue'      => $newValue,
		'oldValue'      => $oldValue,
		'changeType'    => 'Warehouse Zone',
		'employeeID'    => $self->input->{'employeeID'},
	});
		
	
	$self->data->{'dataType'} = "json";
	$self->data->{'data'} = {'success'=>1};
	
	return $self->result;
}


####################################################################################

sub saveOrderBatchConfig {
	my $self = (shift)->new({'input' => shift || {}});
	
	my @priorityList = split("\0",$self->input->{priority});		# required
	my @batchSizeList = split("\0",$self->input->{batchSize});	# required
	my @orderSizeList = split("\0",$self->input->{orderSize});	
	my @minWeightList = split("\0",$self->input->{minWeight});
	my @maxWeightList = split("\0",$self->input->{maxWeight});
	my @batchWeightList = split("\0",$self->input->{batchWeight});
	my @stockTypeList = split("\0",$self->input->{stockType});
	my @orderBatchCartIDList = split("\0",$self->input->{orderBatchCartID});
	
	# clear out batch config for existing site
	my $deleteSql = "DELETE FROM orderBatchConfig WHERE batchType = ?";
	my $deleteHandle = $self->dbh->prepare($deleteSql);
	$deleteHandle->execute($self->input->{batchType});
	
	my $insertSql = "INSERT INTO orderBatchConfig (priority, batchSize, batchWeight, orderBatchCartID, orderSize, minWeight, maxWeight, stockType, batchType, orderAddRuleEnabled) values ( ?,?,?,?,?,?,?,?,?,?)";
	
	my $insertHandle = $self->dbh->prepare($insertSql);
	
	foreach my $i (0 .. $#priorityList) {
				my $j = $i + 1;
				my $orderAddRuleEnabled = (defined $self->input->{$j."_orderAddRule"}) ? 'YES' : 'NO';
				$insertHandle->execute(
					$priorityList[$i],
					$batchSizeList[$i],
					$batchWeightList[$i],
					$orderBatchCartIDList[$i],
					$orderSizeList[$i],
					$minWeightList[$i],
					$maxWeightList[$i],
					$stockTypeList[$i],
					$self->input->{batchType},
					$orderAddRuleEnabled
				);
			}
	
	$self->data->{'redirect'} = "./?action=viewOrderBatchConfig";
	return $self->result;
}

#####################################################################################
sub saveOrderBatchCart {
	my $self = (shift)->new({'input' => shift || {}});
	my $data = decode_json($self->input->{dataToSave});
	
	 my @fields = qw/
            orderBatchCartID
            cartName
            cartEnabled
            rows
            columns
            labelFormat
	/;
	
    my $sql = qq/
        INSERT INTO orderBatchCart 
        (${\join "," => @fields })
        VALUES (${\ join "," => map("?", @fields) })
        ON DUPLICATE KEY UPDATE
        ${\ join "," => map("$_ = VALUES($_)", @fields) };
    /;
	
    my $sth = $self->dbh->prepare($sql);
	
	foreach my $row ( @$data){
		$sth->execute(
			$row->{orderBatchCartID},
			$row->{cartName},
			$row->{cartEnabled},
			$row->{rows},
			$row->{columns},
			$row->{labelFormat}
		);
	}
	
	$self->data->{'redirect'} = "./?action=viewOrderBatchCart";
	
	return $self->result;
}

#####################################################################################

sub logOrderTypePriorityChanges {
    my $p = shift;
	my $sth = $p->{dbh};
	
	my $query = qq(INSERT orderBatchPriorityLog SET changeType = ?,newvalue = ?, oldValue = ?, employeeID = ?);
	eval {
		$sth = $p->{'dbh'}->prepare($query);
		$sth->execute($p->{changeType},$p->{newValue},$p->{oldValue}, $p->{employeeID});
	};
	return 0 if $@ or $sth->err;
}


1;
