#!/usr/bin/perl
use strict;

package API::Warehouse;

our $Config;
BEGIN {
	use API::Config;
	$Config = $API::Config::Config;
}
use lib ($Config->{'Website_libs'});

use ECS::SQL;
use ECS::Error;
use ECS::Config;

my $website_config = \%ECS::Config::c;

# Requires
# - $p->{'input'}->{'warehouseStation'}
# Sets
# - $p->{'labelPrinter'}
# - $p->{'shippingLabelPrinter'}
# - $p->{'formsPrinter'}
sub getStationPrinters {
	my $p = shift;

	my $sql = 'SELECT COALESCE(IF(tmpLabelPrinter = \'\',NULL,tmpLabelPrinter),labelPrinter) as labelPrinter, formsPrinter, shippingLabelPrinter FROM warehouseStation WHERE warehouseStationID = '.ECS::SQL::quote({ 'DBH' => $p->{'DBH'}, 'value' => $p->{'input'}->{'warehouseStation'} });
	my $rd = ECS::SQL::query({ 'DBH' => $p->{'DBH'}, 'sql' => $sql });

	return 0 if (!$rd);

	if ($website_config->{'sandbox'} && ! $website_config->{'useActualPrinter'}) {
		# Always print to label printer by time-clock machine so that labels don't print into the warehouse and confuse packers
		$p->{'labelPrinter'} = 'labelproduct';
		$p->{'shippingLabelPrinter'} = 'labelproduct';
		$p->{'formsPrinter'} = 'Dell2150cn';

		return 1;
	}
	
	$p->{'labelPrinter'} = $rd->[0]->{'labelPrinter'};
	$p->{'shippingLabelPrinter'} = $rd->[0]->{'shippingLabelPrinter'};
	$p->{'formsPrinter'} = $rd->[0]->{'formsPrinter'};

	return 1;
}

sub getManagers {
	my $p = shift;
	
	# first get list of employeeIDs that have permission to do Packing Manager Override
	my $sql = "
		SELECT
			employeePermission.employeeID
		FROM permission
			JOIN employeePermission USING (permissionID)
		WHERE
			permission.name = 'Shipping Manager Override'
	";
	my $rd = ECS::SQL::query({ 'DBH' => $p->{'DBH'}, 'sql' => $sql });
	
	return [] if (!$rd);
	
	$sql = "SELECT nameFirst, nameLast, employeeNumber FROM employeeInfo WHERE employeeID IN (";
	
	foreach my $r (@{ $rd }) {
		$sql .= $r->{'employeeID'}.',';
	}
	
	chop($sql);
	$sql .= ") AND active = 'Y' AND employeeNumber IS NOT NULL";
	
	my $managers = ECS::SQL::query({ 'DBH' => $p->{'DBH'}, 'sql' => $sql });
	
	return [] if (!$managers);
	return $managers;
}

